Nav apraksta

class-wp-theme-json.php 68KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225
  1. <?php
  2. /**
  3. * WP_Theme_JSON class
  4. *
  5. * @package WordPress
  6. * @subpackage Theme
  7. * @since 5.8.0
  8. */
  9. /**
  10. * Class that encapsulates the processing of structures that adhere to the theme.json spec.
  11. *
  12. * This class is for internal core usage and is not supposed to be used by extenders (plugins and/or themes).
  13. * This is a low-level API that may need to do breaking changes. Please,
  14. * use get_global_settings, get_global_styles, and get_global_stylesheet instead.
  15. *
  16. * @access private
  17. */
  18. class WP_Theme_JSON {
  19. /**
  20. * Container of data in theme.json format.
  21. *
  22. * @since 5.8.0
  23. * @var array
  24. */
  25. protected $theme_json = null;
  26. /**
  27. * Holds block metadata extracted from block.json
  28. * to be shared among all instances so we don't
  29. * process it twice.
  30. *
  31. * @since 5.8.0
  32. * @var array
  33. */
  34. protected static $blocks_metadata = null;
  35. /**
  36. * The CSS selector for the top-level styles.
  37. *
  38. * @since 5.8.0
  39. * @var string
  40. */
  41. const ROOT_BLOCK_SELECTOR = 'body';
  42. /**
  43. * The sources of data this object can represent.
  44. *
  45. * @since 5.8.0
  46. * @var string[]
  47. */
  48. const VALID_ORIGINS = array(
  49. 'default',
  50. 'theme',
  51. 'custom',
  52. );
  53. /**
  54. * Presets are a set of values that serve
  55. * to bootstrap some styles: colors, font sizes, etc.
  56. *
  57. * They are a unkeyed array of values such as:
  58. *
  59. * ```php
  60. * array(
  61. * array(
  62. * 'slug' => 'unique-name-within-the-set',
  63. * 'name' => 'Name for the UI',
  64. * <value_key> => 'value'
  65. * ),
  66. * )
  67. * ```
  68. *
  69. * This contains the necessary metadata to process them:
  70. *
  71. * - path => Where to find the preset within the settings section.
  72. * - prevent_override => Disables override of default presets by theme presets.
  73. * The relationship between whether to override the defaults
  74. * and whether the defaults are enabled is inverse:
  75. * - If defaults are enabled => theme presets should not be overriden
  76. * - If defaults are disabled => theme presets should be overriden
  77. * For example, a theme sets defaultPalette to false,
  78. * making the default palette hidden from the user.
  79. * In that case, we want all the theme presets to be present,
  80. * so they should override the defaults by setting this false.
  81. * - use_default_names => whether to use the default names
  82. * - value_key => the key that represents the value
  83. * - value_func => optionally, instead of value_key, a function to generate
  84. * the value that takes a preset as an argument
  85. * (either value_key or value_func should be present)
  86. * - css_vars => template string to use in generating the CSS Custom Property.
  87. * Example output: "--wp--preset--duotone--blue: <value>" will generate as many CSS Custom Properties as presets defined
  88. * substituting the $slug for the slug's value for each preset value.
  89. * - classes => array containing a structure with the classes to
  90. * generate for the presets, where for each array item
  91. * the key is the class name and the value the property name.
  92. * The "$slug" substring will be replaced by the slug of each preset.
  93. * For example:
  94. * 'classes' => array(
  95. * '.has-$slug-color' => 'color',
  96. * '.has-$slug-background-color' => 'background-color',
  97. * '.has-$slug-border-color' => 'border-color',
  98. * )
  99. * - properties => array of CSS properties to be used by kses to
  100. * validate the content of each preset
  101. * by means of the remove_insecure_properties method.
  102. *
  103. * @since 5.8.0
  104. * @since 5.9.0 Added the `color.duotone` and `typography.fontFamilies` presets,
  105. * `use_default_names` preset key, and simplified the metadata structure.
  106. * @since 6.0.0 Replaced `override` with `prevent_override` and updated the
  107. * `prevent_overried` value for `color.duotone` to use `color.defaultDuotone`.
  108. * @var array
  109. */
  110. const PRESETS_METADATA = array(
  111. array(
  112. 'path' => array( 'color', 'palette' ),
  113. 'prevent_override' => array( 'color', 'defaultPalette' ),
  114. 'use_default_names' => false,
  115. 'value_key' => 'color',
  116. 'css_vars' => '--wp--preset--color--$slug',
  117. 'classes' => array(
  118. '.has-$slug-color' => 'color',
  119. '.has-$slug-background-color' => 'background-color',
  120. '.has-$slug-border-color' => 'border-color',
  121. ),
  122. 'properties' => array( 'color', 'background-color', 'border-color' ),
  123. ),
  124. array(
  125. 'path' => array( 'color', 'gradients' ),
  126. 'prevent_override' => array( 'color', 'defaultGradients' ),
  127. 'use_default_names' => false,
  128. 'value_key' => 'gradient',
  129. 'css_vars' => '--wp--preset--gradient--$slug',
  130. 'classes' => array( '.has-$slug-gradient-background' => 'background' ),
  131. 'properties' => array( 'background' ),
  132. ),
  133. array(
  134. 'path' => array( 'color', 'duotone' ),
  135. 'prevent_override' => array( 'color', 'defaultDuotone' ),
  136. 'use_default_names' => false,
  137. 'value_func' => 'wp_get_duotone_filter_property',
  138. 'css_vars' => '--wp--preset--duotone--$slug',
  139. 'classes' => array(),
  140. 'properties' => array( 'filter' ),
  141. ),
  142. array(
  143. 'path' => array( 'typography', 'fontSizes' ),
  144. 'prevent_override' => false,
  145. 'use_default_names' => true,
  146. 'value_key' => 'size',
  147. 'css_vars' => '--wp--preset--font-size--$slug',
  148. 'classes' => array( '.has-$slug-font-size' => 'font-size' ),
  149. 'properties' => array( 'font-size' ),
  150. ),
  151. array(
  152. 'path' => array( 'typography', 'fontFamilies' ),
  153. 'prevent_override' => false,
  154. 'use_default_names' => false,
  155. 'value_key' => 'fontFamily',
  156. 'css_vars' => '--wp--preset--font-family--$slug',
  157. 'classes' => array( '.has-$slug-font-family' => 'font-family' ),
  158. 'properties' => array( 'font-family' ),
  159. ),
  160. );
  161. /**
  162. * Metadata for style properties.
  163. *
  164. * Each element is a direct mapping from the CSS property name to the
  165. * path to the value in theme.json & block attributes.
  166. *
  167. * @since 5.8.0
  168. * @since 5.9.0 Added the `border-*`, `font-family`, `font-style`, `font-weight`,
  169. * `letter-spacing`, `margin-*`, `padding-*`, `--wp--style--block-gap`,
  170. * `text-decoration`, `text-transform`, and `filter` properties,
  171. * simplified the metadata structure.
  172. * @var array
  173. */
  174. const PROPERTIES_METADATA = array(
  175. 'background' => array( 'color', 'gradient' ),
  176. 'background-color' => array( 'color', 'background' ),
  177. 'border-radius' => array( 'border', 'radius' ),
  178. 'border-top-left-radius' => array( 'border', 'radius', 'topLeft' ),
  179. 'border-top-right-radius' => array( 'border', 'radius', 'topRight' ),
  180. 'border-bottom-left-radius' => array( 'border', 'radius', 'bottomLeft' ),
  181. 'border-bottom-right-radius' => array( 'border', 'radius', 'bottomRight' ),
  182. 'border-color' => array( 'border', 'color' ),
  183. 'border-width' => array( 'border', 'width' ),
  184. 'border-style' => array( 'border', 'style' ),
  185. 'color' => array( 'color', 'text' ),
  186. 'font-family' => array( 'typography', 'fontFamily' ),
  187. 'font-size' => array( 'typography', 'fontSize' ),
  188. 'font-style' => array( 'typography', 'fontStyle' ),
  189. 'font-weight' => array( 'typography', 'fontWeight' ),
  190. 'letter-spacing' => array( 'typography', 'letterSpacing' ),
  191. 'line-height' => array( 'typography', 'lineHeight' ),
  192. 'margin' => array( 'spacing', 'margin' ),
  193. 'margin-top' => array( 'spacing', 'margin', 'top' ),
  194. 'margin-right' => array( 'spacing', 'margin', 'right' ),
  195. 'margin-bottom' => array( 'spacing', 'margin', 'bottom' ),
  196. 'margin-left' => array( 'spacing', 'margin', 'left' ),
  197. 'padding' => array( 'spacing', 'padding' ),
  198. 'padding-top' => array( 'spacing', 'padding', 'top' ),
  199. 'padding-right' => array( 'spacing', 'padding', 'right' ),
  200. 'padding-bottom' => array( 'spacing', 'padding', 'bottom' ),
  201. 'padding-left' => array( 'spacing', 'padding', 'left' ),
  202. '--wp--style--block-gap' => array( 'spacing', 'blockGap' ),
  203. 'text-decoration' => array( 'typography', 'textDecoration' ),
  204. 'text-transform' => array( 'typography', 'textTransform' ),
  205. 'filter' => array( 'filter', 'duotone' ),
  206. );
  207. /**
  208. * Protected style properties.
  209. *
  210. * These style properties are only rendered if a setting enables it
  211. * via a value other than `null`.
  212. *
  213. * Each element maps the style property to the corresponding theme.json
  214. * setting key.
  215. *
  216. * @since 5.9.0
  217. */
  218. const PROTECTED_PROPERTIES = array(
  219. 'spacing.blockGap' => array( 'spacing', 'blockGap' ),
  220. );
  221. /**
  222. * The top-level keys a theme.json can have.
  223. *
  224. * @since 5.8.0 As `ALLOWED_TOP_LEVEL_KEYS`.
  225. * @since 5.9.0 Renamed from `ALLOWED_TOP_LEVEL_KEYS` to `VALID_TOP_LEVEL_KEYS`,
  226. * added the `customTemplates` and `templateParts` values.
  227. * @var string[]
  228. */
  229. const VALID_TOP_LEVEL_KEYS = array(
  230. 'customTemplates',
  231. 'patterns',
  232. 'settings',
  233. 'styles',
  234. 'templateParts',
  235. 'version',
  236. 'title',
  237. );
  238. /**
  239. * The valid properties under the settings key.
  240. *
  241. * @since 5.8.0 As `ALLOWED_SETTINGS`.
  242. * @since 5.9.0 Renamed from `ALLOWED_SETTINGS` to `VALID_SETTINGS`,
  243. * added new properties for `border`, `color`, `spacing`,
  244. * and `typography`, and renamed others according to the new schema.
  245. * @since 6.0.0 Added `color.defaultDuotone`.
  246. * @var array
  247. */
  248. const VALID_SETTINGS = array(
  249. 'appearanceTools' => null,
  250. 'border' => array(
  251. 'color' => null,
  252. 'radius' => null,
  253. 'style' => null,
  254. 'width' => null,
  255. ),
  256. 'color' => array(
  257. 'background' => null,
  258. 'custom' => null,
  259. 'customDuotone' => null,
  260. 'customGradient' => null,
  261. 'defaultDuotone' => null,
  262. 'defaultGradients' => null,
  263. 'defaultPalette' => null,
  264. 'duotone' => null,
  265. 'gradients' => null,
  266. 'link' => null,
  267. 'palette' => null,
  268. 'text' => null,
  269. ),
  270. 'custom' => null,
  271. 'layout' => array(
  272. 'contentSize' => null,
  273. 'wideSize' => null,
  274. ),
  275. 'spacing' => array(
  276. 'blockGap' => null,
  277. 'margin' => null,
  278. 'padding' => null,
  279. 'units' => null,
  280. ),
  281. 'typography' => array(
  282. 'customFontSize' => null,
  283. 'dropCap' => null,
  284. 'fontFamilies' => null,
  285. 'fontSizes' => null,
  286. 'fontStyle' => null,
  287. 'fontWeight' => null,
  288. 'letterSpacing' => null,
  289. 'lineHeight' => null,
  290. 'textDecoration' => null,
  291. 'textTransform' => null,
  292. ),
  293. );
  294. /**
  295. * The valid properties under the styles key.
  296. *
  297. * @since 5.8.0 As `ALLOWED_STYLES`.
  298. * @since 5.9.0 Renamed from `ALLOWED_STYLES` to `VALID_STYLES`,
  299. * added new properties for `border`, `filter`, `spacing`,
  300. * and `typography`.
  301. * @var array
  302. */
  303. const VALID_STYLES = array(
  304. 'border' => array(
  305. 'color' => null,
  306. 'radius' => null,
  307. 'style' => null,
  308. 'width' => null,
  309. ),
  310. 'color' => array(
  311. 'background' => null,
  312. 'gradient' => null,
  313. 'text' => null,
  314. ),
  315. 'filter' => array(
  316. 'duotone' => null,
  317. ),
  318. 'spacing' => array(
  319. 'margin' => null,
  320. 'padding' => null,
  321. 'blockGap' => 'top',
  322. ),
  323. 'typography' => array(
  324. 'fontFamily' => null,
  325. 'fontSize' => null,
  326. 'fontStyle' => null,
  327. 'fontWeight' => null,
  328. 'letterSpacing' => null,
  329. 'lineHeight' => null,
  330. 'textDecoration' => null,
  331. 'textTransform' => null,
  332. ),
  333. );
  334. /**
  335. * The valid elements that can be found under styles.
  336. *
  337. * @since 5.8.0
  338. * @var string[]
  339. */
  340. const ELEMENTS = array(
  341. 'link' => 'a',
  342. 'h1' => 'h1',
  343. 'h2' => 'h2',
  344. 'h3' => 'h3',
  345. 'h4' => 'h4',
  346. 'h5' => 'h5',
  347. 'h6' => 'h6',
  348. );
  349. /**
  350. * Options that settings.appearanceTools enables.
  351. *
  352. * @since 6.0.0
  353. * @var array
  354. */
  355. const APPEARANCE_TOOLS_OPT_INS = array(
  356. array( 'border', 'color' ),
  357. array( 'border', 'radius' ),
  358. array( 'border', 'style' ),
  359. array( 'border', 'width' ),
  360. array( 'color', 'link' ),
  361. array( 'spacing', 'blockGap' ),
  362. array( 'spacing', 'margin' ),
  363. array( 'spacing', 'padding' ),
  364. array( 'typography', 'lineHeight' ),
  365. );
  366. /**
  367. * The latest version of the schema in use.
  368. *
  369. * @since 5.8.0
  370. * @since 5.9.0 Changed value from 1 to 2.
  371. * @var int
  372. */
  373. const LATEST_SCHEMA = 2;
  374. /**
  375. * Constructor.
  376. *
  377. * @since 5.8.0
  378. *
  379. * @param array $theme_json A structure that follows the theme.json schema.
  380. * @param string $origin Optional. What source of data this object represents.
  381. * One of 'default', 'theme', or 'custom'. Default 'theme'.
  382. */
  383. public function __construct( $theme_json = array(), $origin = 'theme' ) {
  384. if ( ! in_array( $origin, static::VALID_ORIGINS, true ) ) {
  385. $origin = 'theme';
  386. }
  387. $this->theme_json = WP_Theme_JSON_Schema::migrate( $theme_json );
  388. $valid_block_names = array_keys( static::get_blocks_metadata() );
  389. $valid_element_names = array_keys( static::ELEMENTS );
  390. $theme_json = static::sanitize( $this->theme_json, $valid_block_names, $valid_element_names );
  391. $this->theme_json = static::maybe_opt_in_into_settings( $theme_json );
  392. // Internally, presets are keyed by origin.
  393. $nodes = static::get_setting_nodes( $this->theme_json );
  394. foreach ( $nodes as $node ) {
  395. foreach ( static::PRESETS_METADATA as $preset_metadata ) {
  396. $path = array_merge( $node['path'], $preset_metadata['path'] );
  397. $preset = _wp_array_get( $this->theme_json, $path, null );
  398. if ( null !== $preset ) {
  399. // If the preset is not already keyed by origin.
  400. if ( isset( $preset[0] ) || empty( $preset ) ) {
  401. _wp_array_set( $this->theme_json, $path, array( $origin => $preset ) );
  402. }
  403. }
  404. }
  405. }
  406. }
  407. /**
  408. * Enables some opt-in settings if theme declared support.
  409. *
  410. * @since 5.9.0
  411. *
  412. * @param array $theme_json A theme.json structure to modify.
  413. * @return array The modified theme.json structure.
  414. */
  415. protected static function maybe_opt_in_into_settings( $theme_json ) {
  416. $new_theme_json = $theme_json;
  417. if (
  418. isset( $new_theme_json['settings']['appearanceTools'] ) &&
  419. true === $new_theme_json['settings']['appearanceTools']
  420. ) {
  421. static::do_opt_in_into_settings( $new_theme_json['settings'] );
  422. }
  423. if ( isset( $new_theme_json['settings']['blocks'] ) && is_array( $new_theme_json['settings']['blocks'] ) ) {
  424. foreach ( $new_theme_json['settings']['blocks'] as &$block ) {
  425. if ( isset( $block['appearanceTools'] ) && ( true === $block['appearanceTools'] ) ) {
  426. static::do_opt_in_into_settings( $block );
  427. }
  428. }
  429. }
  430. return $new_theme_json;
  431. }
  432. /**
  433. * Enables some settings.
  434. *
  435. * @since 5.9.0
  436. *
  437. * @param array $context The context to which the settings belong.
  438. */
  439. protected static function do_opt_in_into_settings( &$context ) {
  440. foreach ( static::APPEARANCE_TOOLS_OPT_INS as $path ) {
  441. // Use "unset prop" as a marker instead of "null" because
  442. // "null" can be a valid value for some props (e.g. blockGap).
  443. if ( 'unset prop' === _wp_array_get( $context, $path, 'unset prop' ) ) {
  444. _wp_array_set( $context, $path, true );
  445. }
  446. }
  447. unset( $context['appearanceTools'] );
  448. }
  449. /**
  450. * Sanitizes the input according to the schemas.
  451. *
  452. * @since 5.8.0
  453. * @since 5.9.0 Added the `$valid_block_names` and `$valid_element_name` parameters.
  454. *
  455. * @param array $input Structure to sanitize.
  456. * @param array $valid_block_names List of valid block names.
  457. * @param array $valid_element_names List of valid element names.
  458. * @return array The sanitized output.
  459. */
  460. protected static function sanitize( $input, $valid_block_names, $valid_element_names ) {
  461. $output = array();
  462. if ( ! is_array( $input ) ) {
  463. return $output;
  464. }
  465. $output = array_intersect_key( $input, array_flip( static::VALID_TOP_LEVEL_KEYS ) );
  466. // Some styles are only meant to be available at the top-level (e.g.: blockGap),
  467. // hence, the schema for blocks & elements should not have them.
  468. $styles_non_top_level = static::VALID_STYLES;
  469. foreach ( array_keys( $styles_non_top_level ) as $section ) {
  470. foreach ( array_keys( $styles_non_top_level[ $section ] ) as $prop ) {
  471. if ( 'top' === $styles_non_top_level[ $section ][ $prop ] ) {
  472. unset( $styles_non_top_level[ $section ][ $prop ] );
  473. }
  474. }
  475. }
  476. // Build the schema based on valid block & element names.
  477. $schema = array();
  478. $schema_styles_elements = array();
  479. foreach ( $valid_element_names as $element ) {
  480. $schema_styles_elements[ $element ] = $styles_non_top_level;
  481. }
  482. $schema_styles_blocks = array();
  483. $schema_settings_blocks = array();
  484. foreach ( $valid_block_names as $block ) {
  485. $schema_settings_blocks[ $block ] = static::VALID_SETTINGS;
  486. $schema_styles_blocks[ $block ] = $styles_non_top_level;
  487. $schema_styles_blocks[ $block ]['elements'] = $schema_styles_elements;
  488. }
  489. $schema['styles'] = static::VALID_STYLES;
  490. $schema['styles']['blocks'] = $schema_styles_blocks;
  491. $schema['styles']['elements'] = $schema_styles_elements;
  492. $schema['settings'] = static::VALID_SETTINGS;
  493. $schema['settings']['blocks'] = $schema_settings_blocks;
  494. // Remove anything that's not present in the schema.
  495. foreach ( array( 'styles', 'settings' ) as $subtree ) {
  496. if ( ! isset( $input[ $subtree ] ) ) {
  497. continue;
  498. }
  499. if ( ! is_array( $input[ $subtree ] ) ) {
  500. unset( $output[ $subtree ] );
  501. continue;
  502. }
  503. $result = static::remove_keys_not_in_schema( $input[ $subtree ], $schema[ $subtree ] );
  504. if ( empty( $result ) ) {
  505. unset( $output[ $subtree ] );
  506. } else {
  507. $output[ $subtree ] = $result;
  508. }
  509. }
  510. return $output;
  511. }
  512. /**
  513. * Returns the metadata for each block.
  514. *
  515. * Example:
  516. *
  517. * {
  518. * 'core/paragraph': {
  519. * 'selector': 'p',
  520. * 'elements': {
  521. * 'link' => 'link selector',
  522. * 'etc' => 'element selector'
  523. * }
  524. * },
  525. * 'core/heading': {
  526. * 'selector': 'h1',
  527. * 'elements': {}
  528. * },
  529. * 'core/image': {
  530. * 'selector': '.wp-block-image',
  531. * 'duotone': 'img',
  532. * 'elements': {}
  533. * }
  534. * }
  535. *
  536. * @since 5.8.0
  537. * @since 5.9.0 Added `duotone` key with CSS selector.
  538. *
  539. * @return array Block metadata.
  540. */
  541. protected static function get_blocks_metadata() {
  542. if ( null !== static::$blocks_metadata ) {
  543. return static::$blocks_metadata;
  544. }
  545. static::$blocks_metadata = array();
  546. $registry = WP_Block_Type_Registry::get_instance();
  547. $blocks = $registry->get_all_registered();
  548. foreach ( $blocks as $block_name => $block_type ) {
  549. if (
  550. isset( $block_type->supports['__experimentalSelector'] ) &&
  551. is_string( $block_type->supports['__experimentalSelector'] )
  552. ) {
  553. static::$blocks_metadata[ $block_name ]['selector'] = $block_type->supports['__experimentalSelector'];
  554. } else {
  555. static::$blocks_metadata[ $block_name ]['selector'] = '.wp-block-' . str_replace( '/', '-', str_replace( 'core/', '', $block_name ) );
  556. }
  557. if (
  558. isset( $block_type->supports['color']['__experimentalDuotone'] ) &&
  559. is_string( $block_type->supports['color']['__experimentalDuotone'] )
  560. ) {
  561. static::$blocks_metadata[ $block_name ]['duotone'] = $block_type->supports['color']['__experimentalDuotone'];
  562. }
  563. // Assign defaults, then overwrite those that the block sets by itself.
  564. // If the block selector is compounded, will append the element to each
  565. // individual block selector.
  566. $block_selectors = explode( ',', static::$blocks_metadata[ $block_name ]['selector'] );
  567. foreach ( static::ELEMENTS as $el_name => $el_selector ) {
  568. $element_selector = array();
  569. foreach ( $block_selectors as $selector ) {
  570. $element_selector[] = $selector . ' ' . $el_selector;
  571. }
  572. static::$blocks_metadata[ $block_name ]['elements'][ $el_name ] = implode( ',', $element_selector );
  573. }
  574. }
  575. return static::$blocks_metadata;
  576. }
  577. /**
  578. * Given a tree, removes the keys that are not present in the schema.
  579. *
  580. * It is recursive and modifies the input in-place.
  581. *
  582. * @since 5.8.0
  583. *
  584. * @param array $tree Input to process.
  585. * @param array $schema Schema to adhere to.
  586. * @return array Returns the modified $tree.
  587. */
  588. protected static function remove_keys_not_in_schema( $tree, $schema ) {
  589. $tree = array_intersect_key( $tree, $schema );
  590. foreach ( $schema as $key => $data ) {
  591. if ( ! isset( $tree[ $key ] ) ) {
  592. continue;
  593. }
  594. if ( is_array( $schema[ $key ] ) && is_array( $tree[ $key ] ) ) {
  595. $tree[ $key ] = static::remove_keys_not_in_schema( $tree[ $key ], $schema[ $key ] );
  596. if ( empty( $tree[ $key ] ) ) {
  597. unset( $tree[ $key ] );
  598. }
  599. } elseif ( is_array( $schema[ $key ] ) && ! is_array( $tree[ $key ] ) ) {
  600. unset( $tree[ $key ] );
  601. }
  602. }
  603. return $tree;
  604. }
  605. /**
  606. * Returns the existing settings for each block.
  607. *
  608. * Example:
  609. *
  610. * {
  611. * 'root': {
  612. * 'color': {
  613. * 'custom': true
  614. * }
  615. * },
  616. * 'core/paragraph': {
  617. * 'spacing': {
  618. * 'customPadding': true
  619. * }
  620. * }
  621. * }
  622. *
  623. * @since 5.8.0
  624. *
  625. * @return array Settings per block.
  626. */
  627. public function get_settings() {
  628. if ( ! isset( $this->theme_json['settings'] ) ) {
  629. return array();
  630. } else {
  631. return $this->theme_json['settings'];
  632. }
  633. }
  634. /**
  635. * Returns the stylesheet that results of processing
  636. * the theme.json structure this object represents.
  637. *
  638. * @since 5.8.0
  639. * @since 5.9.0 Removed the `$type` parameter`, added the `$types` and `$origins` parameters.
  640. *
  641. * @param array $types Types of styles to load. Will load all by default. It accepts:
  642. * - `variables`: only the CSS Custom Properties for presets & custom ones.
  643. * - `styles`: only the styles section in theme.json.
  644. * - `presets`: only the classes for the presets.
  645. * @param array $origins A list of origins to include. By default it includes VALID_ORIGINS.
  646. * @return string Stylesheet.
  647. */
  648. public function get_stylesheet( $types = array( 'variables', 'styles', 'presets' ), $origins = null ) {
  649. if ( null === $origins ) {
  650. $origins = static::VALID_ORIGINS;
  651. }
  652. if ( is_string( $types ) ) {
  653. // Dispatch error and map old arguments to new ones.
  654. _deprecated_argument( __FUNCTION__, '5.9.0' );
  655. if ( 'block_styles' === $types ) {
  656. $types = array( 'styles', 'presets' );
  657. } elseif ( 'css_variables' === $types ) {
  658. $types = array( 'variables' );
  659. } else {
  660. $types = array( 'variables', 'styles', 'presets' );
  661. }
  662. }
  663. $blocks_metadata = static::get_blocks_metadata();
  664. $style_nodes = static::get_style_nodes( $this->theme_json, $blocks_metadata );
  665. $setting_nodes = static::get_setting_nodes( $this->theme_json, $blocks_metadata );
  666. $stylesheet = '';
  667. if ( in_array( 'variables', $types, true ) ) {
  668. $stylesheet .= $this->get_css_variables( $setting_nodes, $origins );
  669. }
  670. if ( in_array( 'styles', $types, true ) ) {
  671. $stylesheet .= $this->get_block_classes( $style_nodes );
  672. }
  673. if ( in_array( 'presets', $types, true ) ) {
  674. $stylesheet .= $this->get_preset_classes( $setting_nodes, $origins );
  675. }
  676. return $stylesheet;
  677. }
  678. /**
  679. * Returns the page templates of the active theme.
  680. *
  681. * @since 5.9.0
  682. *
  683. * @return array
  684. */
  685. public function get_custom_templates() {
  686. $custom_templates = array();
  687. if ( ! isset( $this->theme_json['customTemplates'] ) || ! is_array( $this->theme_json['customTemplates'] ) ) {
  688. return $custom_templates;
  689. }
  690. foreach ( $this->theme_json['customTemplates'] as $item ) {
  691. if ( isset( $item['name'] ) ) {
  692. $custom_templates[ $item['name'] ] = array(
  693. 'title' => isset( $item['title'] ) ? $item['title'] : '',
  694. 'postTypes' => isset( $item['postTypes'] ) ? $item['postTypes'] : array( 'page' ),
  695. );
  696. }
  697. }
  698. return $custom_templates;
  699. }
  700. /**
  701. * Returns the template part data of active theme.
  702. *
  703. * @since 5.9.0
  704. *
  705. * @return array
  706. */
  707. public function get_template_parts() {
  708. $template_parts = array();
  709. if ( ! isset( $this->theme_json['templateParts'] ) || ! is_array( $this->theme_json['templateParts'] ) ) {
  710. return $template_parts;
  711. }
  712. foreach ( $this->theme_json['templateParts'] as $item ) {
  713. if ( isset( $item['name'] ) ) {
  714. $template_parts[ $item['name'] ] = array(
  715. 'title' => isset( $item['title'] ) ? $item['title'] : '',
  716. 'area' => isset( $item['area'] ) ? $item['area'] : '',
  717. );
  718. }
  719. }
  720. return $template_parts;
  721. }
  722. /**
  723. * Converts each style section into a list of rulesets
  724. * containing the block styles to be appended to the stylesheet.
  725. *
  726. * See glossary at https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax
  727. *
  728. * For each section this creates a new ruleset such as:
  729. *
  730. * block-selector {
  731. * style-property-one: value;
  732. * }
  733. *
  734. * @since 5.8.0 As `get_block_styles()`.
  735. * @since 5.9.0 Renamed from `get_block_styles()` to `get_block_classes()`
  736. * and no longer returns preset classes.
  737. * Removed the `$setting_nodes` parameter.
  738. *
  739. * @param array $style_nodes Nodes with styles.
  740. * @return string The new stylesheet.
  741. */
  742. protected function get_block_classes( $style_nodes ) {
  743. $block_rules = '';
  744. foreach ( $style_nodes as $metadata ) {
  745. if ( null === $metadata['selector'] ) {
  746. continue;
  747. }
  748. $node = _wp_array_get( $this->theme_json, $metadata['path'], array() );
  749. $selector = $metadata['selector'];
  750. $settings = _wp_array_get( $this->theme_json, array( 'settings' ) );
  751. $declarations = static::compute_style_properties( $node, $settings );
  752. // 1. Separate the ones who use the general selector
  753. // and the ones who use the duotone selector.
  754. $declarations_duotone = array();
  755. foreach ( $declarations as $index => $declaration ) {
  756. if ( 'filter' === $declaration['name'] ) {
  757. unset( $declarations[ $index ] );
  758. $declarations_duotone[] = $declaration;
  759. }
  760. }
  761. /*
  762. * Reset default browser margin on the root body element.
  763. * This is set on the root selector **before** generating the ruleset
  764. * from the `theme.json`. This is to ensure that if the `theme.json` declares
  765. * `margin` in its `spacing` declaration for the `body` element then these
  766. * user-generated values take precedence in the CSS cascade.
  767. * @link https://github.com/WordPress/gutenberg/issues/36147.
  768. */
  769. if ( static::ROOT_BLOCK_SELECTOR === $selector ) {
  770. $block_rules .= 'body { margin: 0; }';
  771. }
  772. // 2. Generate the rules that use the general selector.
  773. $block_rules .= static::to_ruleset( $selector, $declarations );
  774. // 3. Generate the rules that use the duotone selector.
  775. if ( isset( $metadata['duotone'] ) && ! empty( $declarations_duotone ) ) {
  776. $selector_duotone = static::scope_selector( $metadata['selector'], $metadata['duotone'] );
  777. $block_rules .= static::to_ruleset( $selector_duotone, $declarations_duotone );
  778. }
  779. if ( static::ROOT_BLOCK_SELECTOR === $selector ) {
  780. $block_rules .= '.wp-site-blocks > .alignleft { float: left; margin-right: 2em; }';
  781. $block_rules .= '.wp-site-blocks > .alignright { float: right; margin-left: 2em; }';
  782. $block_rules .= '.wp-site-blocks > .aligncenter { justify-content: center; margin-left: auto; margin-right: auto; }';
  783. $has_block_gap_support = _wp_array_get( $this->theme_json, array( 'settings', 'spacing', 'blockGap' ) ) !== null;
  784. if ( $has_block_gap_support ) {
  785. $block_rules .= '.wp-site-blocks > * { margin-block-start: 0; margin-block-end: 0; }';
  786. $block_rules .= '.wp-site-blocks > * + * { margin-block-start: var( --wp--style--block-gap ); }';
  787. }
  788. }
  789. }
  790. return $block_rules;
  791. }
  792. /**
  793. * Creates new rulesets as classes for each preset value such as:
  794. *
  795. * .has-value-color {
  796. * color: value;
  797. * }
  798. *
  799. * .has-value-background-color {
  800. * background-color: value;
  801. * }
  802. *
  803. * .has-value-font-size {
  804. * font-size: value;
  805. * }
  806. *
  807. * .has-value-gradient-background {
  808. * background: value;
  809. * }
  810. *
  811. * p.has-value-gradient-background {
  812. * background: value;
  813. * }
  814. *
  815. * @since 5.9.0
  816. *
  817. * @param array $setting_nodes Nodes with settings.
  818. * @param array $origins List of origins to process presets from.
  819. * @return string The new stylesheet.
  820. */
  821. protected function get_preset_classes( $setting_nodes, $origins ) {
  822. $preset_rules = '';
  823. foreach ( $setting_nodes as $metadata ) {
  824. if ( null === $metadata['selector'] ) {
  825. continue;
  826. }
  827. $selector = $metadata['selector'];
  828. $node = _wp_array_get( $this->theme_json, $metadata['path'], array() );
  829. $preset_rules .= static::compute_preset_classes( $node, $selector, $origins );
  830. }
  831. return $preset_rules;
  832. }
  833. /**
  834. * Converts each styles section into a list of rulesets
  835. * to be appended to the stylesheet.
  836. * These rulesets contain all the css variables (custom variables and preset variables).
  837. *
  838. * See glossary at https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax
  839. *
  840. * For each section this creates a new ruleset such as:
  841. *
  842. * block-selector {
  843. * --wp--preset--category--slug: value;
  844. * --wp--custom--variable: value;
  845. * }
  846. *
  847. * @since 5.8.0
  848. * @since 5.9.0 Added the `$origins` parameter.
  849. *
  850. * @param array $nodes Nodes with settings.
  851. * @param array $origins List of origins to process.
  852. * @return string The new stylesheet.
  853. */
  854. protected function get_css_variables( $nodes, $origins ) {
  855. $stylesheet = '';
  856. foreach ( $nodes as $metadata ) {
  857. if ( null === $metadata['selector'] ) {
  858. continue;
  859. }
  860. $selector = $metadata['selector'];
  861. $node = _wp_array_get( $this->theme_json, $metadata['path'], array() );
  862. $declarations = array_merge( static::compute_preset_vars( $node, $origins ), static::compute_theme_vars( $node ) );
  863. $stylesheet .= static::to_ruleset( $selector, $declarations );
  864. }
  865. return $stylesheet;
  866. }
  867. /**
  868. * Given a selector and a declaration list,
  869. * creates the corresponding ruleset.
  870. *
  871. * @since 5.8.0
  872. *
  873. * @param string $selector CSS selector.
  874. * @param array $declarations List of declarations.
  875. * @return string CSS ruleset.
  876. */
  877. protected static function to_ruleset( $selector, $declarations ) {
  878. if ( empty( $declarations ) ) {
  879. return '';
  880. }
  881. $declaration_block = array_reduce(
  882. $declarations,
  883. static function ( $carry, $element ) {
  884. return $carry .= $element['name'] . ': ' . $element['value'] . ';'; },
  885. ''
  886. );
  887. return $selector . '{' . $declaration_block . '}';
  888. }
  889. /**
  890. * Function that appends a sub-selector to a existing one.
  891. *
  892. * Given the compounded $selector "h1, h2, h3"
  893. * and the $to_append selector ".some-class" the result will be
  894. * "h1.some-class, h2.some-class, h3.some-class".
  895. *
  896. * @since 5.8.0
  897. *
  898. * @param string $selector Original selector.
  899. * @param string $to_append Selector to append.
  900. * @return string
  901. */
  902. protected static function append_to_selector( $selector, $to_append ) {
  903. $new_selectors = array();
  904. $selectors = explode( ',', $selector );
  905. foreach ( $selectors as $sel ) {
  906. $new_selectors[] = $sel . $to_append;
  907. }
  908. return implode( ',', $new_selectors );
  909. }
  910. /**
  911. * Given a settings array, it returns the generated rulesets
  912. * for the preset classes.
  913. *
  914. * @since 5.8.0
  915. * @since 5.9.0 Added the `$origins` parameter.
  916. *
  917. * @param array $settings Settings to process.
  918. * @param string $selector Selector wrapping the classes.
  919. * @param array $origins List of origins to process.
  920. * @return string The result of processing the presets.
  921. */
  922. protected static function compute_preset_classes( $settings, $selector, $origins ) {
  923. if ( static::ROOT_BLOCK_SELECTOR === $selector ) {
  924. // Classes at the global level do not need any CSS prefixed,
  925. // and we don't want to increase its specificity.
  926. $selector = '';
  927. }
  928. $stylesheet = '';
  929. foreach ( static::PRESETS_METADATA as $preset_metadata ) {
  930. $slugs = static::get_settings_slugs( $settings, $preset_metadata, $origins );
  931. foreach ( $preset_metadata['classes'] as $class => $property ) {
  932. foreach ( $slugs as $slug ) {
  933. $css_var = static::replace_slug_in_string( $preset_metadata['css_vars'], $slug );
  934. $class_name = static::replace_slug_in_string( $class, $slug );
  935. $stylesheet .= static::to_ruleset(
  936. static::append_to_selector( $selector, $class_name ),
  937. array(
  938. array(
  939. 'name' => $property,
  940. 'value' => 'var(' . $css_var . ') !important',
  941. ),
  942. )
  943. );
  944. }
  945. }
  946. }
  947. return $stylesheet;
  948. }
  949. /**
  950. * Function that scopes a selector with another one. This works a bit like
  951. * SCSS nesting except the `&` operator isn't supported.
  952. *
  953. * <code>
  954. * $scope = '.a, .b .c';
  955. * $selector = '> .x, .y';
  956. * $merged = scope_selector( $scope, $selector );
  957. * // $merged is '.a > .x, .a .y, .b .c > .x, .b .c .y'
  958. * </code>
  959. *
  960. * @since 5.9.0
  961. *
  962. * @param string $scope Selector to scope to.
  963. * @param string $selector Original selector.
  964. * @return string Scoped selector.
  965. */
  966. protected static function scope_selector( $scope, $selector ) {
  967. $scopes = explode( ',', $scope );
  968. $selectors = explode( ',', $selector );
  969. $selectors_scoped = array();
  970. foreach ( $scopes as $outer ) {
  971. foreach ( $selectors as $inner ) {
  972. $selectors_scoped[] = trim( $outer ) . ' ' . trim( $inner );
  973. }
  974. }
  975. return implode( ', ', $selectors_scoped );
  976. }
  977. /**
  978. * Gets preset values keyed by slugs based on settings and metadata.
  979. *
  980. * <code>
  981. * $settings = array(
  982. * 'typography' => array(
  983. * 'fontFamilies' => array(
  984. * array(
  985. * 'slug' => 'sansSerif',
  986. * 'fontFamily' => '"Helvetica Neue", sans-serif',
  987. * ),
  988. * array(
  989. * 'slug' => 'serif',
  990. * 'colors' => 'Georgia, serif',
  991. * )
  992. * ),
  993. * ),
  994. * );
  995. * $meta = array(
  996. * 'path' => array( 'typography', 'fontFamilies' ),
  997. * 'value_key' => 'fontFamily',
  998. * );
  999. * $values_by_slug = get_settings_values_by_slug();
  1000. * // $values_by_slug === array(
  1001. * // 'sans-serif' => '"Helvetica Neue", sans-serif',
  1002. * // 'serif' => 'Georgia, serif',
  1003. * // );
  1004. * </code>
  1005. *
  1006. * @since 5.9.0
  1007. *
  1008. * @param array $settings Settings to process.
  1009. * @param array $preset_metadata One of the PRESETS_METADATA values.
  1010. * @param array $origins List of origins to process.
  1011. * @return array Array of presets where each key is a slug and each value is the preset value.
  1012. */
  1013. protected static function get_settings_values_by_slug( $settings, $preset_metadata, $origins ) {
  1014. $preset_per_origin = _wp_array_get( $settings, $preset_metadata['path'], array() );
  1015. $result = array();
  1016. foreach ( $origins as $origin ) {
  1017. if ( ! isset( $preset_per_origin[ $origin ] ) ) {
  1018. continue;
  1019. }
  1020. foreach ( $preset_per_origin[ $origin ] as $preset ) {
  1021. $slug = _wp_to_kebab_case( $preset['slug'] );
  1022. $value = '';
  1023. if ( isset( $preset_metadata['value_key'], $preset[ $preset_metadata['value_key'] ] ) ) {
  1024. $value_key = $preset_metadata['value_key'];
  1025. $value = $preset[ $value_key ];
  1026. } elseif (
  1027. isset( $preset_metadata['value_func'] ) &&
  1028. is_callable( $preset_metadata['value_func'] )
  1029. ) {
  1030. $value_func = $preset_metadata['value_func'];
  1031. $value = call_user_func( $value_func, $preset );
  1032. } else {
  1033. // If we don't have a value, then don't add it to the result.
  1034. continue;
  1035. }
  1036. $result[ $slug ] = $value;
  1037. }
  1038. }
  1039. return $result;
  1040. }
  1041. /**
  1042. * Similar to get_settings_values_by_slug, but doesn't compute the value.
  1043. *
  1044. * @since 5.9.0
  1045. *
  1046. * @param array $settings Settings to process.
  1047. * @param array $preset_metadata One of the PRESETS_METADATA values.
  1048. * @param array $origins List of origins to process.
  1049. * @return array Array of presets where the key and value are both the slug.
  1050. */
  1051. protected static function get_settings_slugs( $settings, $preset_metadata, $origins = null ) {
  1052. if ( null === $origins ) {
  1053. $origins = static::VALID_ORIGINS;
  1054. }
  1055. $preset_per_origin = _wp_array_get( $settings, $preset_metadata['path'], array() );
  1056. $result = array();
  1057. foreach ( $origins as $origin ) {
  1058. if ( ! isset( $preset_per_origin[ $origin ] ) ) {
  1059. continue;
  1060. }
  1061. foreach ( $preset_per_origin[ $origin ] as $preset ) {
  1062. $slug = _wp_to_kebab_case( $preset['slug'] );
  1063. // Use the array as a set so we don't get duplicates.
  1064. $result[ $slug ] = $slug;
  1065. }
  1066. }
  1067. return $result;
  1068. }
  1069. /**
  1070. * Transform a slug into a CSS Custom Property.
  1071. *
  1072. * @since 5.9.0
  1073. *
  1074. * @param string $input String to replace.
  1075. * @param string $slug The slug value to use to generate the custom property.
  1076. * @return string The CSS Custom Property. Something along the lines of `--wp--preset--color--black`.
  1077. */
  1078. protected static function replace_slug_in_string( $input, $slug ) {
  1079. return strtr( $input, array( '$slug' => $slug ) );
  1080. }
  1081. /**
  1082. * Given the block settings, it extracts the CSS Custom Properties
  1083. * for the presets and adds them to the $declarations array
  1084. * following the format:
  1085. *
  1086. * array(
  1087. * 'name' => 'property_name',
  1088. * 'value' => 'property_value,
  1089. * )
  1090. *
  1091. * @since 5.8.0
  1092. * @since 5.9.0 Added the `$origins` parameter.
  1093. *
  1094. * @param array $settings Settings to process.
  1095. * @param array $origins List of origins to process.
  1096. * @return array Returns the modified $declarations.
  1097. */
  1098. protected static function compute_preset_vars( $settings, $origins ) {
  1099. $declarations = array();
  1100. foreach ( static::PRESETS_METADATA as $preset_metadata ) {
  1101. $values_by_slug = static::get_settings_values_by_slug( $settings, $preset_metadata, $origins );
  1102. foreach ( $values_by_slug as $slug => $value ) {
  1103. $declarations[] = array(
  1104. 'name' => static::replace_slug_in_string( $preset_metadata['css_vars'], $slug ),
  1105. 'value' => $value,
  1106. );
  1107. }
  1108. }
  1109. return $declarations;
  1110. }
  1111. /**
  1112. * Given an array of settings, it extracts the CSS Custom Properties
  1113. * for the custom values and adds them to the $declarations
  1114. * array following the format:
  1115. *
  1116. * array(
  1117. * 'name' => 'property_name',
  1118. * 'value' => 'property_value,
  1119. * )
  1120. *
  1121. * @since 5.8.0
  1122. *
  1123. * @param array $settings Settings to process.
  1124. * @return array Returns the modified $declarations.
  1125. */
  1126. protected static function compute_theme_vars( $settings ) {
  1127. $declarations = array();
  1128. $custom_values = _wp_array_get( $settings, array( 'custom' ), array() );
  1129. $css_vars = static::flatten_tree( $custom_values );
  1130. foreach ( $css_vars as $key => $value ) {
  1131. $declarations[] = array(
  1132. 'name' => '--wp--custom--' . $key,
  1133. 'value' => $value,
  1134. );
  1135. }
  1136. return $declarations;
  1137. }
  1138. /**
  1139. * Given a tree, it creates a flattened one
  1140. * by merging the keys and binding the leaf values
  1141. * to the new keys.
  1142. *
  1143. * It also transforms camelCase names into kebab-case
  1144. * and substitutes '/' by '-'.
  1145. *
  1146. * This is thought to be useful to generate
  1147. * CSS Custom Properties from a tree,
  1148. * although there's nothing in the implementation
  1149. * of this function that requires that format.
  1150. *
  1151. * For example, assuming the given prefix is '--wp'
  1152. * and the token is '--', for this input tree:
  1153. *
  1154. * {
  1155. * 'some/property': 'value',
  1156. * 'nestedProperty': {
  1157. * 'sub-property': 'value'
  1158. * }
  1159. * }
  1160. *
  1161. * it'll return this output:
  1162. *
  1163. * {
  1164. * '--wp--some-property': 'value',
  1165. * '--wp--nested-property--sub-property': 'value'
  1166. * }
  1167. *
  1168. * @since 5.8.0
  1169. *
  1170. * @param array $tree Input tree to process.
  1171. * @param string $prefix Optional. Prefix to prepend to each variable. Default empty string.
  1172. * @param string $token Optional. Token to use between levels. Default '--'.
  1173. * @return array The flattened tree.
  1174. */
  1175. protected static function flatten_tree( $tree, $prefix = '', $token = '--' ) {
  1176. $result = array();
  1177. foreach ( $tree as $property => $value ) {
  1178. $new_key = $prefix . str_replace(
  1179. '/',
  1180. '-',
  1181. strtolower( _wp_to_kebab_case( $property ) )
  1182. );
  1183. if ( is_array( $value ) ) {
  1184. $new_prefix = $new_key . $token;
  1185. $result = array_merge(
  1186. $result,
  1187. static::flatten_tree( $value, $new_prefix, $token )
  1188. );
  1189. } else {
  1190. $result[ $new_key ] = $value;
  1191. }
  1192. }
  1193. return $result;
  1194. }
  1195. /**
  1196. * Given a styles array, it extracts the style properties
  1197. * and adds them to the $declarations array following the format:
  1198. *
  1199. * array(
  1200. * 'name' => 'property_name',
  1201. * 'value' => 'property_value,
  1202. * )
  1203. *
  1204. * @since 5.8.0
  1205. * @since 5.9.0 Added the `$settings` and `$properties` parameters.
  1206. *
  1207. * @param array $styles Styles to process.
  1208. * @param array $settings Theme settings.
  1209. * @param array $properties Properties metadata.
  1210. * @return array Returns the modified $declarations.
  1211. */
  1212. protected static function compute_style_properties( $styles, $settings = array(), $properties = null ) {
  1213. if ( null === $properties ) {
  1214. $properties = static::PROPERTIES_METADATA;
  1215. }
  1216. $declarations = array();
  1217. if ( empty( $styles ) ) {
  1218. return $declarations;
  1219. }
  1220. foreach ( $properties as $css_property => $value_path ) {
  1221. $value = static::get_property_value( $styles, $value_path );
  1222. // Look up protected properties, keyed by value path.
  1223. // Skip protected properties that are explicitly set to `null`.
  1224. if ( is_array( $value_path ) ) {
  1225. $path_string = implode( '.', $value_path );
  1226. if (
  1227. array_key_exists( $path_string, static::PROTECTED_PROPERTIES ) &&
  1228. _wp_array_get( $settings, static::PROTECTED_PROPERTIES[ $path_string ], null ) === null
  1229. ) {
  1230. continue;
  1231. }
  1232. }
  1233. // Skip if empty and not "0" or value represents array of longhand values.
  1234. $has_missing_value = empty( $value ) && ! is_numeric( $value );
  1235. if ( $has_missing_value || is_array( $value ) ) {
  1236. continue;
  1237. }
  1238. $declarations[] = array(
  1239. 'name' => $css_property,
  1240. 'value' => $value,
  1241. );
  1242. }
  1243. return $declarations;
  1244. }
  1245. /**
  1246. * Returns the style property for the given path.
  1247. *
  1248. * It also converts CSS Custom Property stored as
  1249. * "var:preset|color|secondary" to the form
  1250. * "--wp--preset--color--secondary".
  1251. *
  1252. * @since 5.8.0
  1253. * @since 5.9.0 Added support for values of array type, which are returned as is.
  1254. *
  1255. * @param array $styles Styles subtree.
  1256. * @param array $path Which property to process.
  1257. * @return string|array Style property value.
  1258. */
  1259. protected static function get_property_value( $styles, $path ) {
  1260. $value = _wp_array_get( $styles, $path, '' );
  1261. if ( '' === $value || is_array( $value ) ) {
  1262. return $value;
  1263. }
  1264. $prefix = 'var:';
  1265. $prefix_len = strlen( $prefix );
  1266. $token_in = '|';
  1267. $token_out = '--';
  1268. if ( 0 === strncmp( $value, $prefix, $prefix_len ) ) {
  1269. $unwrapped_name = str_replace(
  1270. $token_in,
  1271. $token_out,
  1272. substr( $value, $prefix_len )
  1273. );
  1274. $value = "var(--wp--$unwrapped_name)";
  1275. }
  1276. return $value;
  1277. }
  1278. /**
  1279. * Builds metadata for the setting nodes, which returns in the form of:
  1280. *
  1281. * [
  1282. * [
  1283. * 'path' => ['path', 'to', 'some', 'node' ],
  1284. * 'selector' => 'CSS selector for some node'
  1285. * ],
  1286. * [
  1287. * 'path' => [ 'path', 'to', 'other', 'node' ],
  1288. * 'selector' => 'CSS selector for other node'
  1289. * ],
  1290. * ]
  1291. *
  1292. * @since 5.8.0
  1293. *
  1294. * @param array $theme_json The tree to extract setting nodes from.
  1295. * @param array $selectors List of selectors per block.
  1296. * @return array
  1297. */
  1298. protected static function get_setting_nodes( $theme_json, $selectors = array() ) {
  1299. $nodes = array();
  1300. if ( ! isset( $theme_json['settings'] ) ) {
  1301. return $nodes;
  1302. }
  1303. // Top-level.
  1304. $nodes[] = array(
  1305. 'path' => array( 'settings' ),
  1306. 'selector' => static::ROOT_BLOCK_SELECTOR,
  1307. );
  1308. // Calculate paths for blocks.
  1309. if ( ! isset( $theme_json['settings']['blocks'] ) ) {
  1310. return $nodes;
  1311. }
  1312. foreach ( $theme_json['settings']['blocks'] as $name => $node ) {
  1313. $selector = null;
  1314. if ( isset( $selectors[ $name ]['selector'] ) ) {
  1315. $selector = $selectors[ $name ]['selector'];
  1316. }
  1317. $nodes[] = array(
  1318. 'path' => array( 'settings', 'blocks', $name ),
  1319. 'selector' => $selector,
  1320. );
  1321. }
  1322. return $nodes;
  1323. }
  1324. /**
  1325. * Builds metadata for the style nodes, which returns in the form of:
  1326. *
  1327. * [
  1328. * [
  1329. * 'path' => [ 'path', 'to', 'some', 'node' ],
  1330. * 'selector' => 'CSS selector for some node',
  1331. * 'duotone' => 'CSS selector for duotone for some node'
  1332. * ],
  1333. * [
  1334. * 'path' => ['path', 'to', 'other', 'node' ],
  1335. * 'selector' => 'CSS selector for other node',
  1336. * 'duotone' => null
  1337. * ],
  1338. * ]
  1339. *
  1340. * @since 5.8.0
  1341. *
  1342. * @param array $theme_json The tree to extract style nodes from.
  1343. * @param array $selectors List of selectors per block.
  1344. * @return array
  1345. */
  1346. protected static function get_style_nodes( $theme_json, $selectors = array() ) {
  1347. $nodes = array();
  1348. if ( ! isset( $theme_json['styles'] ) ) {
  1349. return $nodes;
  1350. }
  1351. // Top-level.
  1352. $nodes[] = array(
  1353. 'path' => array( 'styles' ),
  1354. 'selector' => static::ROOT_BLOCK_SELECTOR,
  1355. );
  1356. if ( isset( $theme_json['styles']['elements'] ) ) {
  1357. foreach ( $theme_json['styles']['elements'] as $element => $node ) {
  1358. $nodes[] = array(
  1359. 'path' => array( 'styles', 'elements', $element ),
  1360. 'selector' => static::ELEMENTS[ $element ],
  1361. );
  1362. }
  1363. }
  1364. // Blocks.
  1365. if ( ! isset( $theme_json['styles']['blocks'] ) ) {
  1366. return $nodes;
  1367. }
  1368. foreach ( $theme_json['styles']['blocks'] as $name => $node ) {
  1369. $selector = null;
  1370. if ( isset( $selectors[ $name ]['selector'] ) ) {
  1371. $selector = $selectors[ $name ]['selector'];
  1372. }
  1373. $duotone_selector = null;
  1374. if ( isset( $selectors[ $name ]['duotone'] ) ) {
  1375. $duotone_selector = $selectors[ $name ]['duotone'];
  1376. }
  1377. $nodes[] = array(
  1378. 'path' => array( 'styles', 'blocks', $name ),
  1379. 'selector' => $selector,
  1380. 'duotone' => $duotone_selector,
  1381. );
  1382. if ( isset( $theme_json['styles']['blocks'][ $name ]['elements'] ) ) {
  1383. foreach ( $theme_json['styles']['blocks'][ $name ]['elements'] as $element => $node ) {
  1384. $nodes[] = array(
  1385. 'path' => array( 'styles', 'blocks', $name, 'elements', $element ),
  1386. 'selector' => $selectors[ $name ]['elements'][ $element ],
  1387. );
  1388. }
  1389. }
  1390. }
  1391. return $nodes;
  1392. }
  1393. /**
  1394. * For metadata values that can either be booleans or paths to booleans, gets the value.
  1395. *
  1396. * ```php
  1397. * $data = array(
  1398. * 'color' => array(
  1399. * 'defaultPalette' => true
  1400. * )
  1401. * );
  1402. *
  1403. * static::get_metadata_boolean( $data, false );
  1404. * // => false
  1405. *
  1406. * static::get_metadata_boolean( $data, array( 'color', 'defaultPalette' ) );
  1407. * // => true
  1408. * ```
  1409. *
  1410. * @since 6.0.0
  1411. *
  1412. * @param array $data The data to inspect.
  1413. * @param bool|array $path Boolean or path to a boolean.
  1414. * @param bool $default Default value if the referenced path is missing.
  1415. * Default false.
  1416. * @return bool Value of boolean metadata.
  1417. */
  1418. protected static function get_metadata_boolean( $data, $path, $default = false ) {
  1419. if ( is_bool( $path ) ) {
  1420. return $path;
  1421. }
  1422. if ( is_array( $path ) ) {
  1423. $value = _wp_array_get( $data, $path );
  1424. if ( null !== $value ) {
  1425. return $value;
  1426. }
  1427. }
  1428. return $default;
  1429. }
  1430. /**
  1431. * Merge new incoming data.
  1432. *
  1433. * @since 5.8.0
  1434. * @since 5.9.0 Duotone preset also has origins.
  1435. *
  1436. * @param WP_Theme_JSON $incoming Data to merge.
  1437. */
  1438. public function merge( $incoming ) {
  1439. $incoming_data = $incoming->get_raw_data();
  1440. $this->theme_json = array_replace_recursive( $this->theme_json, $incoming_data );
  1441. /*
  1442. * The array_replace_recursive algorithm merges at the leaf level,
  1443. * but we don't want leaf arrays to be merged, so we overwrite it.
  1444. *
  1445. * For leaf values that are sequential arrays it will use the numeric indexes for replacement.
  1446. * We rather replace the existing with the incoming value, if it exists.
  1447. * This is the case of spacing.units.
  1448. *
  1449. * For leaf values that are associative arrays it will merge them as expected.
  1450. * This is also not the behavior we want for the current associative arrays (presets).
  1451. * We rather replace the existing with the incoming value, if it exists.
  1452. * This happens, for example, when we merge data from theme.json upon existing
  1453. * theme supports or when we merge anything coming from the same source twice.
  1454. * This is the case of color.palette, color.gradients, color.duotone,
  1455. * typography.fontSizes, or typography.fontFamilies.
  1456. *
  1457. * Additionally, for some preset types, we also want to make sure the
  1458. * values they introduce don't conflict with default values. We do so
  1459. * by checking the incoming slugs for theme presets and compare them
  1460. * with the equivalent default presets: if a slug is present as a default
  1461. * we remove it from the theme presets.
  1462. */
  1463. $nodes = static::get_setting_nodes( $incoming_data );
  1464. $slugs_global = static::get_default_slugs( $this->theme_json, array( 'settings' ) );
  1465. foreach ( $nodes as $node ) {
  1466. $slugs_node = static::get_default_slugs( $this->theme_json, $node['path'] );
  1467. $slugs = array_merge_recursive( $slugs_global, $slugs_node );
  1468. // Replace the spacing.units.
  1469. $path = array_merge( $node['path'], array( 'spacing', 'units' ) );
  1470. $content = _wp_array_get( $incoming_data, $path, null );
  1471. if ( isset( $content ) ) {
  1472. _wp_array_set( $this->theme_json, $path, $content );
  1473. }
  1474. // Replace the presets.
  1475. foreach ( static::PRESETS_METADATA as $preset ) {
  1476. $override_preset = ! static::get_metadata_boolean( $this->theme_json['settings'], $preset['prevent_override'], true );
  1477. foreach ( static::VALID_ORIGINS as $origin ) {
  1478. $base_path = array_merge( $node['path'], $preset['path'] );
  1479. $path = array_merge( $base_path, array( $origin ) );
  1480. $content = _wp_array_get( $incoming_data, $path, null );
  1481. if ( ! isset( $content ) ) {
  1482. continue;
  1483. }
  1484. if ( 'theme' === $origin && $preset['use_default_names'] ) {
  1485. foreach ( $content as &$item ) {
  1486. if ( ! array_key_exists( 'name', $item ) ) {
  1487. $name = static::get_name_from_defaults( $item['slug'], $base_path );
  1488. if ( null !== $name ) {
  1489. $item['name'] = $name;
  1490. }
  1491. }
  1492. }
  1493. }
  1494. if (
  1495. ( 'theme' !== $origin ) ||
  1496. ( 'theme' === $origin && $override_preset )
  1497. ) {
  1498. _wp_array_set( $this->theme_json, $path, $content );
  1499. } else {
  1500. $slugs_for_preset = _wp_array_get( $slugs, $preset['path'], array() );
  1501. $content = static::filter_slugs( $content, $slugs_for_preset );
  1502. _wp_array_set( $this->theme_json, $path, $content );
  1503. }
  1504. }
  1505. }
  1506. }
  1507. }
  1508. /**
  1509. * Converts all filter (duotone) presets into SVGs.
  1510. *
  1511. * @since 5.9.1
  1512. *
  1513. * @param array $origins List of origins to process.
  1514. * @return string SVG filters.
  1515. */
  1516. public function get_svg_filters( $origins ) {
  1517. $blocks_metadata = static::get_blocks_metadata();
  1518. $setting_nodes = static::get_setting_nodes( $this->theme_json, $blocks_metadata );
  1519. $filters = '';
  1520. foreach ( $setting_nodes as $metadata ) {
  1521. $node = _wp_array_get( $this->theme_json, $metadata['path'], array() );
  1522. if ( empty( $node['color']['duotone'] ) ) {
  1523. continue;
  1524. }
  1525. $duotone_presets = $node['color']['duotone'];
  1526. foreach ( $origins as $origin ) {
  1527. if ( ! isset( $duotone_presets[ $origin ] ) ) {
  1528. continue;
  1529. }
  1530. foreach ( $duotone_presets[ $origin ] as $duotone_preset ) {
  1531. $filters .= wp_get_duotone_filter_svg( $duotone_preset );
  1532. }
  1533. }
  1534. }
  1535. return $filters;
  1536. }
  1537. /**
  1538. * Returns whether a presets should be overridden or not.
  1539. *
  1540. * @since 5.9.0
  1541. * @deprecated 6.0.0 Use {@see 'get_metadata_boolean'} instead.
  1542. *
  1543. * @param array $theme_json The theme.json like structure to inspect.
  1544. * @param array $path Path to inspect.
  1545. * @param bool|array $override Data to compute whether to override the preset.
  1546. * @return boolean
  1547. */
  1548. protected static function should_override_preset( $theme_json, $path, $override ) {
  1549. _deprecated_function( __METHOD__, '6.0.0', 'get_metadata_boolean' );
  1550. if ( is_bool( $override ) ) {
  1551. return $override;
  1552. }
  1553. /*
  1554. * The relationship between whether to override the defaults
  1555. * and whether the defaults are enabled is inverse:
  1556. *
  1557. * - If defaults are enabled => theme presets should not be overridden
  1558. * - If defaults are disabled => theme presets should be overridden
  1559. *
  1560. * For example, a theme sets defaultPalette to false,
  1561. * making the default palette hidden from the user.
  1562. * In that case, we want all the theme presets to be present,
  1563. * so they should override the defaults.
  1564. */
  1565. if ( is_array( $override ) ) {
  1566. $value = _wp_array_get( $theme_json, array_merge( $path, $override ) );
  1567. if ( isset( $value ) ) {
  1568. return ! $value;
  1569. }
  1570. // Search the top-level key if none was found for this node.
  1571. $value = _wp_array_get( $theme_json, array_merge( array( 'settings' ), $override ) );
  1572. if ( isset( $value ) ) {
  1573. return ! $value;
  1574. }
  1575. return true;
  1576. }
  1577. }
  1578. /**
  1579. * Returns the default slugs for all the presets in an associative array
  1580. * whose keys are the preset paths and the leafs is the list of slugs.
  1581. *
  1582. * For example:
  1583. *
  1584. * array(
  1585. * 'color' => array(
  1586. * 'palette' => array( 'slug-1', 'slug-2' ),
  1587. * 'gradients' => array( 'slug-3', 'slug-4' ),
  1588. * ),
  1589. * )
  1590. *
  1591. * @since 5.9.0
  1592. *
  1593. * @param array $data A theme.json like structure.
  1594. * @param array $node_path The path to inspect. It's 'settings' by default.
  1595. * @return array
  1596. */
  1597. protected static function get_default_slugs( $data, $node_path ) {
  1598. $slugs = array();
  1599. foreach ( static::PRESETS_METADATA as $metadata ) {
  1600. $path = array_merge( $node_path, $metadata['path'], array( 'default' ) );
  1601. $preset = _wp_array_get( $data, $path, null );
  1602. if ( ! isset( $preset ) ) {
  1603. continue;
  1604. }
  1605. $slugs_for_preset = array();
  1606. $slugs_for_preset = array_map(
  1607. static function( $value ) {
  1608. return isset( $value['slug'] ) ? $value['slug'] : null;
  1609. },
  1610. $preset
  1611. );
  1612. _wp_array_set( $slugs, $metadata['path'], $slugs_for_preset );
  1613. }
  1614. return $slugs;
  1615. }
  1616. /**
  1617. * Get a `default`'s preset name by a provided slug.
  1618. *
  1619. * @since 5.9.0
  1620. *
  1621. * @param string $slug The slug we want to find a match from default presets.
  1622. * @param array $base_path The path to inspect. It's 'settings' by default.
  1623. * @return string|null
  1624. */
  1625. protected function get_name_from_defaults( $slug, $base_path ) {
  1626. $path = array_merge( $base_path, array( 'default' ) );
  1627. $default_content = _wp_array_get( $this->theme_json, $path, null );
  1628. if ( ! $default_content ) {
  1629. return null;
  1630. }
  1631. foreach ( $default_content as $item ) {
  1632. if ( $slug === $item['slug'] ) {
  1633. return $item['name'];
  1634. }
  1635. }
  1636. return null;
  1637. }
  1638. /**
  1639. * Removes the preset values whose slug is equal to any of given slugs.
  1640. *
  1641. * @since 5.9.0
  1642. *
  1643. * @param array $node The node with the presets to validate.
  1644. * @param array $slugs The slugs that should not be overridden.
  1645. * @return array The new node.
  1646. */
  1647. protected static function filter_slugs( $node, $slugs ) {
  1648. if ( empty( $slugs ) ) {
  1649. return $node;
  1650. }
  1651. $new_node = array();
  1652. foreach ( $node as $value ) {
  1653. if ( isset( $value['slug'] ) && ! in_array( $value['slug'], $slugs, true ) ) {
  1654. $new_node[] = $value;
  1655. }
  1656. }
  1657. return $new_node;
  1658. }
  1659. /**
  1660. * Removes insecure data from theme.json.
  1661. *
  1662. * @since 5.9.0
  1663. *
  1664. * @param array $theme_json Structure to sanitize.
  1665. * @return array Sanitized structure.
  1666. */
  1667. public static function remove_insecure_properties( $theme_json ) {
  1668. $sanitized = array();
  1669. $theme_json = WP_Theme_JSON_Schema::migrate( $theme_json );
  1670. $valid_block_names = array_keys( static::get_blocks_metadata() );
  1671. $valid_element_names = array_keys( static::ELEMENTS );
  1672. $theme_json = static::sanitize( $theme_json, $valid_block_names, $valid_element_names );
  1673. $blocks_metadata = static::get_blocks_metadata();
  1674. $style_nodes = static::get_style_nodes( $theme_json, $blocks_metadata );
  1675. foreach ( $style_nodes as $metadata ) {
  1676. $input = _wp_array_get( $theme_json, $metadata['path'], array() );
  1677. if ( empty( $input ) ) {
  1678. continue;
  1679. }
  1680. $output = static::remove_insecure_styles( $input );
  1681. if ( ! empty( $output ) ) {
  1682. _wp_array_set( $sanitized, $metadata['path'], $output );
  1683. }
  1684. }
  1685. $setting_nodes = static::get_setting_nodes( $theme_json );
  1686. foreach ( $setting_nodes as $metadata ) {
  1687. $input = _wp_array_get( $theme_json, $metadata['path'], array() );
  1688. if ( empty( $input ) ) {
  1689. continue;
  1690. }
  1691. $output = static::remove_insecure_settings( $input );
  1692. if ( ! empty( $output ) ) {
  1693. _wp_array_set( $sanitized, $metadata['path'], $output );
  1694. }
  1695. }
  1696. if ( empty( $sanitized['styles'] ) ) {
  1697. unset( $theme_json['styles'] );
  1698. } else {
  1699. $theme_json['styles'] = $sanitized['styles'];
  1700. }
  1701. if ( empty( $sanitized['settings'] ) ) {
  1702. unset( $theme_json['settings'] );
  1703. } else {
  1704. $theme_json['settings'] = $sanitized['settings'];
  1705. }
  1706. return $theme_json;
  1707. }
  1708. /**
  1709. * Processes a setting node and returns the same node
  1710. * without the insecure settings.
  1711. *
  1712. * @since 5.9.0
  1713. *
  1714. * @param array $input Node to process.
  1715. * @return array
  1716. */
  1717. protected static function remove_insecure_settings( $input ) {
  1718. $output = array();
  1719. foreach ( static::PRESETS_METADATA as $preset_metadata ) {
  1720. foreach ( static::VALID_ORIGINS as $origin ) {
  1721. $path_with_origin = array_merge( $preset_metadata['path'], array( $origin ) );
  1722. $presets = _wp_array_get( $input, $path_with_origin, null );
  1723. if ( null === $presets ) {
  1724. continue;
  1725. }
  1726. $escaped_preset = array();
  1727. foreach ( $presets as $preset ) {
  1728. if (
  1729. esc_attr( esc_html( $preset['name'] ) ) === $preset['name'] &&
  1730. sanitize_html_class( $preset['slug'] ) === $preset['slug']
  1731. ) {
  1732. $value = null;
  1733. if ( isset( $preset_metadata['value_key'], $preset[ $preset_metadata['value_key'] ] ) ) {
  1734. $value = $preset[ $preset_metadata['value_key'] ];
  1735. } elseif (
  1736. isset( $preset_metadata['value_func'] ) &&
  1737. is_callable( $preset_metadata['value_func'] )
  1738. ) {
  1739. $value = call_user_func( $preset_metadata['value_func'], $preset );
  1740. }
  1741. $preset_is_valid = true;
  1742. foreach ( $preset_metadata['properties'] as $property ) {
  1743. if ( ! static::is_safe_css_declaration( $property, $value ) ) {
  1744. $preset_is_valid = false;
  1745. break;
  1746. }
  1747. }
  1748. if ( $preset_is_valid ) {
  1749. $escaped_preset[] = $preset;
  1750. }
  1751. }
  1752. }
  1753. if ( ! empty( $escaped_preset ) ) {
  1754. _wp_array_set( $output, $path_with_origin, $escaped_preset );
  1755. }
  1756. }
  1757. }
  1758. return $output;
  1759. }
  1760. /**
  1761. * Processes a style node and returns the same node
  1762. * without the insecure styles.
  1763. *
  1764. * @since 5.9.0
  1765. *
  1766. * @param array $input Node to process.
  1767. * @return array
  1768. */
  1769. protected static function remove_insecure_styles( $input ) {
  1770. $output = array();
  1771. $declarations = static::compute_style_properties( $input );
  1772. foreach ( $declarations as $declaration ) {
  1773. if ( static::is_safe_css_declaration( $declaration['name'], $declaration['value'] ) ) {
  1774. $path = static::PROPERTIES_METADATA[ $declaration['name'] ];
  1775. // Check the value isn't an array before adding so as to not
  1776. // double up shorthand and longhand styles.
  1777. $value = _wp_array_get( $input, $path, array() );
  1778. if ( ! is_array( $value ) ) {
  1779. _wp_array_set( $output, $path, $value );
  1780. }
  1781. }
  1782. }
  1783. return $output;
  1784. }
  1785. /**
  1786. * Checks that a declaration provided by the user is safe.
  1787. *
  1788. * @since 5.9.0
  1789. *
  1790. * @param string $property_name Property name in a CSS declaration, i.e. the `color` in `color: red`.
  1791. * @param string $property_value Value in a CSS declaration, i.e. the `red` in `color: red`.
  1792. * @return bool
  1793. */
  1794. protected static function is_safe_css_declaration( $property_name, $property_value ) {
  1795. $style_to_validate = $property_name . ': ' . $property_value;
  1796. $filtered = esc_html( safecss_filter_attr( $style_to_validate ) );
  1797. return ! empty( trim( $filtered ) );
  1798. }
  1799. /**
  1800. * Returns the raw data.
  1801. *
  1802. * @since 5.8.0
  1803. *
  1804. * @return array Raw data.
  1805. */
  1806. public function get_raw_data() {
  1807. return $this->theme_json;
  1808. }
  1809. /**
  1810. * Transforms the given editor settings according the
  1811. * add_theme_support format to the theme.json format.
  1812. *
  1813. * @since 5.8.0
  1814. *
  1815. * @param array $settings Existing editor settings.
  1816. * @return array Config that adheres to the theme.json schema.
  1817. */
  1818. public static function get_from_editor_settings( $settings ) {
  1819. $theme_settings = array(
  1820. 'version' => static::LATEST_SCHEMA,
  1821. 'settings' => array(),
  1822. );
  1823. // Deprecated theme supports.
  1824. if ( isset( $settings['disableCustomColors'] ) ) {
  1825. if ( ! isset( $theme_settings['settings']['color'] ) ) {
  1826. $theme_settings['settings']['color'] = array();
  1827. }
  1828. $theme_settings['settings']['color']['custom'] = ! $settings['disableCustomColors'];
  1829. }
  1830. if ( isset( $settings['disableCustomGradients'] ) ) {
  1831. if ( ! isset( $theme_settings['settings']['color'] ) ) {
  1832. $theme_settings['settings']['color'] = array();
  1833. }
  1834. $theme_settings['settings']['color']['customGradient'] = ! $settings['disableCustomGradients'];
  1835. }
  1836. if ( isset( $settings['disableCustomFontSizes'] ) ) {
  1837. if ( ! isset( $theme_settings['settings']['typography'] ) ) {
  1838. $theme_settings['settings']['typography'] = array();
  1839. }
  1840. $theme_settings['settings']['typography']['customFontSize'] = ! $settings['disableCustomFontSizes'];
  1841. }
  1842. if ( isset( $settings['enableCustomLineHeight'] ) ) {
  1843. if ( ! isset( $theme_settings['settings']['typography'] ) ) {
  1844. $theme_settings['settings']['typography'] = array();
  1845. }
  1846. $theme_settings['settings']['typography']['lineHeight'] = $settings['enableCustomLineHeight'];
  1847. }
  1848. if ( isset( $settings['enableCustomUnits'] ) ) {
  1849. if ( ! isset( $theme_settings['settings']['spacing'] ) ) {
  1850. $theme_settings['settings']['spacing'] = array();
  1851. }
  1852. $theme_settings['settings']['spacing']['units'] = ( true === $settings['enableCustomUnits'] ) ?
  1853. array( 'px', 'em', 'rem', 'vh', 'vw', '%' ) :
  1854. $settings['enableCustomUnits'];
  1855. }
  1856. if ( isset( $settings['colors'] ) ) {
  1857. if ( ! isset( $theme_settings['settings']['color'] ) ) {
  1858. $theme_settings['settings']['color'] = array();
  1859. }
  1860. $theme_settings['settings']['color']['palette'] = $settings['colors'];
  1861. }
  1862. if ( isset( $settings['gradients'] ) ) {
  1863. if ( ! isset( $theme_settings['settings']['color'] ) ) {
  1864. $theme_settings['settings']['color'] = array();
  1865. }
  1866. $theme_settings['settings']['color']['gradients'] = $settings['gradients'];
  1867. }
  1868. if ( isset( $settings['fontSizes'] ) ) {
  1869. $font_sizes = $settings['fontSizes'];
  1870. // Back-compatibility for presets without units.
  1871. foreach ( $font_sizes as $key => $font_size ) {
  1872. if ( is_numeric( $font_size['size'] ) ) {
  1873. $font_sizes[ $key ]['size'] = $font_size['size'] . 'px';
  1874. }
  1875. }
  1876. if ( ! isset( $theme_settings['settings']['typography'] ) ) {
  1877. $theme_settings['settings']['typography'] = array();
  1878. }
  1879. $theme_settings['settings']['typography']['fontSizes'] = $font_sizes;
  1880. }
  1881. if ( isset( $settings['enableCustomSpacing'] ) ) {
  1882. if ( ! isset( $theme_settings['settings']['spacing'] ) ) {
  1883. $theme_settings['settings']['spacing'] = array();
  1884. }
  1885. $theme_settings['settings']['spacing']['padding'] = $settings['enableCustomSpacing'];
  1886. }
  1887. return $theme_settings;
  1888. }
  1889. /**
  1890. * Returns the current theme's wanted patterns(slugs) to be
  1891. * registered from Pattern Directory.
  1892. *
  1893. * @since 6.0.0
  1894. *
  1895. * @return string[]
  1896. */
  1897. public function get_patterns() {
  1898. if ( isset( $this->theme_json['patterns'] ) && is_array( $this->theme_json['patterns'] ) ) {
  1899. return $this->theme_json['patterns'];
  1900. }
  1901. return array();
  1902. }
  1903. /**
  1904. * Returns a valid theme.json as provided by a theme.
  1905. *
  1906. * Unlike get_raw_data() this returns the presets flattened, as provided by a theme.
  1907. * This also uses appearanceTools instead of their opt-ins if all of them are true.
  1908. *
  1909. * @since 6.0.0
  1910. *
  1911. * @return array
  1912. */
  1913. public function get_data() {
  1914. $output = $this->theme_json;
  1915. $nodes = static::get_setting_nodes( $output );
  1916. /**
  1917. * Flatten the theme & custom origins into a single one.
  1918. *
  1919. * For example, the following:
  1920. *
  1921. * {
  1922. * "settings": {
  1923. * "color": {
  1924. * "palette": {
  1925. * "theme": [ {} ],
  1926. * "custom": [ {} ]
  1927. * }
  1928. * }
  1929. * }
  1930. * }
  1931. *
  1932. * will be converted to:
  1933. *
  1934. * {
  1935. * "settings": {
  1936. * "color": {
  1937. * "palette": [ {} ]
  1938. * }
  1939. * }
  1940. * }
  1941. */
  1942. foreach ( $nodes as $node ) {
  1943. foreach ( static::PRESETS_METADATA as $preset_metadata ) {
  1944. $path = array_merge( $node['path'], $preset_metadata['path'] );
  1945. $preset = _wp_array_get( $output, $path, null );
  1946. if ( null === $preset ) {
  1947. continue;
  1948. }
  1949. $items = array();
  1950. if ( isset( $preset['theme'] ) ) {
  1951. foreach ( $preset['theme'] as $item ) {
  1952. $slug = $item['slug'];
  1953. unset( $item['slug'] );
  1954. $items[ $slug ] = $item;
  1955. }
  1956. }
  1957. if ( isset( $preset['custom'] ) ) {
  1958. foreach ( $preset['custom'] as $item ) {
  1959. $slug = $item['slug'];
  1960. unset( $item['slug'] );
  1961. $items[ $slug ] = $item;
  1962. }
  1963. }
  1964. $flattened_preset = array();
  1965. foreach ( $items as $slug => $value ) {
  1966. $flattened_preset[] = array_merge( array( 'slug' => $slug ), $value );
  1967. }
  1968. _wp_array_set( $output, $path, $flattened_preset );
  1969. }
  1970. }
  1971. // If all of the static::APPEARANCE_TOOLS_OPT_INS are true,
  1972. // this code unsets them and sets 'appearanceTools' instead.
  1973. foreach ( $nodes as $node ) {
  1974. $all_opt_ins_are_set = true;
  1975. foreach ( static::APPEARANCE_TOOLS_OPT_INS as $opt_in_path ) {
  1976. $full_path = array_merge( $node['path'], $opt_in_path );
  1977. // Use "unset prop" as a marker instead of "null" because
  1978. // "null" can be a valid value for some props (e.g. blockGap).
  1979. $opt_in_value = _wp_array_get( $output, $full_path, 'unset prop' );
  1980. if ( 'unset prop' === $opt_in_value ) {
  1981. $all_opt_ins_are_set = false;
  1982. break;
  1983. }
  1984. }
  1985. if ( $all_opt_ins_are_set ) {
  1986. _wp_array_set( $output, array_merge( $node['path'], array( 'appearanceTools' ) ), true );
  1987. foreach ( static::APPEARANCE_TOOLS_OPT_INS as $opt_in_path ) {
  1988. $full_path = array_merge( $node['path'], $opt_in_path );
  1989. // Use "unset prop" as a marker instead of "null" because
  1990. // "null" can be a valid value for some props (e.g. blockGap).
  1991. $opt_in_value = _wp_array_get( $output, $full_path, 'unset prop' );
  1992. if ( true !== $opt_in_value ) {
  1993. continue;
  1994. }
  1995. // The following could be improved to be path independent.
  1996. // At the moment it relies on a couple of assumptions:
  1997. //
  1998. // - all opt-ins having a path of size 2.
  1999. // - there's two sources of settings: the top-level and the block-level.
  2000. if (
  2001. ( 1 === count( $node['path'] ) ) &&
  2002. ( 'settings' === $node['path'][0] )
  2003. ) {
  2004. // Top-level settings.
  2005. unset( $output['settings'][ $opt_in_path[0] ][ $opt_in_path[1] ] );
  2006. if ( empty( $output['settings'][ $opt_in_path[0] ] ) ) {
  2007. unset( $output['settings'][ $opt_in_path[0] ] );
  2008. }
  2009. } elseif (
  2010. ( 3 === count( $node['path'] ) ) &&
  2011. ( 'settings' === $node['path'][0] ) &&
  2012. ( 'blocks' === $node['path'][1] )
  2013. ) {
  2014. // Block-level settings.
  2015. $block_name = $node['path'][2];
  2016. unset( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ][ $opt_in_path[1] ] );
  2017. if ( empty( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ] ) ) {
  2018. unset( $output['settings']['blocks'][ $block_name ][ $opt_in_path[0] ] );
  2019. }
  2020. }
  2021. }
  2022. }
  2023. }
  2024. wp_recursive_ksort( $output );
  2025. return $output;
  2026. }
  2027. }