common.inc 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311
  1. <?php
  2. /**
  3. * @file
  4. * Common functions that many Drupal modules will need to reference.
  5. *
  6. * The functions that are critical and need to be available even when serving
  7. * a cached page are instead located in bootstrap.inc.
  8. */
  9. use Drupal\Component\Serialization\Json;
  10. use Drupal\Component\Utility\Bytes;
  11. use Drupal\Component\Utility\Html;
  12. use Drupal\Component\Utility\SortArray;
  13. use Drupal\Component\Utility\UrlHelper;
  14. use Drupal\Core\Cache\Cache;
  15. use Drupal\Core\Render\Element\Link;
  16. use Drupal\Core\Render\Markup;
  17. use Drupal\Core\StringTranslation\TranslatableMarkup;
  18. use Drupal\Core\StringTranslation\PluralTranslatableMarkup;
  19. use Drupal\Core\Render\BubbleableMetadata;
  20. use Drupal\Core\Render\Element;
  21. /**
  22. * @defgroup php_wrappers PHP wrapper functions
  23. * @{
  24. * Functions that are wrappers or custom implementations of PHP functions.
  25. *
  26. * Certain PHP functions should not be used in Drupal. Instead, Drupal's
  27. * replacement functions should be used.
  28. *
  29. * For example, for improved or more secure UTF8-handling, or RFC-compliant
  30. * handling of URLs in Drupal.
  31. *
  32. * For ease of use and memorizing, all these wrapper functions use the same name
  33. * as the original PHP function, but prefixed with "drupal_". Beware, however,
  34. * that not all wrapper functions support the same arguments as the original
  35. * functions.
  36. *
  37. * You should always use these wrapper functions in your code.
  38. *
  39. * Wrong:
  40. * @code
  41. * $my_substring = substr($original_string, 0, 5);
  42. * @endcode
  43. *
  44. * Correct:
  45. * @code
  46. * $my_substring = mb_substr($original_string, 0, 5);
  47. * @endcode
  48. *
  49. * @}
  50. */
  51. /**
  52. * Return status for saving which involved creating a new item.
  53. */
  54. const SAVED_NEW = 1;
  55. /**
  56. * Return status for saving which involved an update to an existing item.
  57. */
  58. const SAVED_UPDATED = 2;
  59. /**
  60. * Return status for saving which deleted an existing item.
  61. */
  62. const SAVED_DELETED = 3;
  63. /**
  64. * The default aggregation group for CSS files added to the page.
  65. */
  66. const CSS_AGGREGATE_DEFAULT = 0;
  67. /**
  68. * The default aggregation group for theme CSS files added to the page.
  69. */
  70. const CSS_AGGREGATE_THEME = 100;
  71. /**
  72. * The default weight for CSS rules that style HTML elements ("base" styles).
  73. */
  74. const CSS_BASE = -200;
  75. /**
  76. * The default weight for CSS rules that layout a page.
  77. */
  78. const CSS_LAYOUT = -100;
  79. /**
  80. * The default weight for CSS rules that style design components (and their associated states and themes.)
  81. */
  82. const CSS_COMPONENT = 0;
  83. /**
  84. * The default weight for CSS rules that style states and are not included with components.
  85. */
  86. const CSS_STATE = 100;
  87. /**
  88. * The default weight for CSS rules that style themes and are not included with components.
  89. */
  90. const CSS_THEME = 200;
  91. /**
  92. * The default group for JavaScript settings added to the page.
  93. */
  94. const JS_SETTING = -200;
  95. /**
  96. * The default group for JavaScript and jQuery libraries added to the page.
  97. */
  98. const JS_LIBRARY = -100;
  99. /**
  100. * The default group for module JavaScript code added to the page.
  101. */
  102. const JS_DEFAULT = 0;
  103. /**
  104. * The default group for theme JavaScript code added to the page.
  105. */
  106. const JS_THEME = 100;
  107. /**
  108. * The delimiter used to split plural strings.
  109. *
  110. * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
  111. * Use \Drupal\Core\StringTranslation\PluralTranslatableMarkup::DELIMITER
  112. * instead.
  113. */
  114. const LOCALE_PLURAL_DELIMITER = PluralTranslatableMarkup::DELIMITER;
  115. /**
  116. * Prepares a 'destination' URL query parameter.
  117. *
  118. * Used to direct the user back to the referring page after completing a form.
  119. * By default the current URL is returned. If a destination exists in the
  120. * previous request, that destination is returned. As such, a destination can
  121. * persist across multiple pages.
  122. *
  123. * @return array
  124. * An associative array containing the key:
  125. * - destination: The value of the current request's 'destination' query
  126. * parameter, if present. This can be either a relative or absolute URL.
  127. * However, for security, redirection to external URLs is not performed.
  128. * If the query parameter isn't present, then the URL of the current
  129. * request is returned.
  130. *
  131. * @ingroup form_api
  132. *
  133. * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
  134. * Use the redirect.destination service.
  135. *
  136. * @see \Drupal\Core\EventSubscriber\RedirectResponseSubscriber::checkRedirectUrl()
  137. * @see https://www.drupal.org/node/2448603
  138. */
  139. function drupal_get_destination() {
  140. return \Drupal::destination()->getAsArray();
  141. }
  142. /**
  143. * @defgroup validation Input validation
  144. * @{
  145. * Functions to validate user input.
  146. */
  147. /**
  148. * Verifies the syntax of the given email address.
  149. *
  150. * @param string $mail
  151. * A string containing an email address.
  152. *
  153. * @return bool
  154. * TRUE if the address is in a valid format.
  155. *
  156. * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
  157. * Use \Drupal::service('email.validator')->isValid().
  158. *
  159. * @see https://www.drupal.org/node/2912661
  160. */
  161. function valid_email_address($mail) {
  162. return \Drupal::service('email.validator')->isValid($mail);
  163. }
  164. /**
  165. * @} End of "defgroup validation".
  166. */
  167. /**
  168. * @defgroup sanitization Sanitization functions
  169. * @{
  170. * Functions to sanitize values.
  171. *
  172. * See https://www.drupal.org/writing-secure-code for information
  173. * on writing secure code.
  174. */
  175. /**
  176. * Strips dangerous protocols from a URI and encodes it for output to HTML.
  177. *
  178. * @param $uri
  179. * A plain-text URI that might contain dangerous protocols.
  180. *
  181. * @return string
  182. * A URI stripped of dangerous protocols and encoded for output to an HTML
  183. * attribute value. Because it is already encoded, it should not be set as a
  184. * value within a $attributes array passed to Drupal\Core\Template\Attribute,
  185. * because Drupal\Core\Template\Attribute expects those values to be
  186. * plain-text strings. To pass a filtered URI to
  187. * Drupal\Core\Template\Attribute, call
  188. * \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols() instead.
  189. *
  190. * @deprecated in Drupal 8.0.x-dev, will be removed before Drupal 9.0.0.
  191. * Use UrlHelper::stripDangerousProtocols() or UrlHelper::filterBadProtocol()
  192. * instead. UrlHelper::stripDangerousProtocols() can be used in conjunction
  193. * with \Drupal\Component\Render\FormattableMarkup and an @variable
  194. * placeholder which will perform the necessary escaping.
  195. * UrlHelper::filterBadProtocol() is functionality equivalent to check_url()
  196. * apart from the fact it is protected from double escaping bugs. Note that
  197. * this method no longer marks its output as safe.
  198. *
  199. * @see \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols()
  200. * @see \Drupal\Component\Utility\UrlHelper::filterBadProtocol()
  201. * @see https://www.drupal.org/node/2560027
  202. */
  203. function check_url($uri) {
  204. return Html::escape(UrlHelper::stripDangerousProtocols($uri));
  205. }
  206. /**
  207. * @} End of "defgroup sanitization".
  208. */
  209. /**
  210. * @defgroup format Formatting
  211. * @{
  212. * Functions to format numbers, strings, dates, etc.
  213. */
  214. /**
  215. * Generates a string representation for the given byte count.
  216. *
  217. * @param $size
  218. * A size in bytes.
  219. * @param $langcode
  220. * Optional language code to translate to a language other than what is used
  221. * to display the page.
  222. *
  223. * @return \Drupal\Core\StringTranslation\TranslatableMarkup
  224. * A translated string representation of the size.
  225. */
  226. function format_size($size, $langcode = NULL) {
  227. if ($size < Bytes::KILOBYTE) {
  228. return \Drupal::translation()->formatPlural($size, '1 byte', '@count bytes', [], ['langcode' => $langcode]);
  229. }
  230. else {
  231. // Convert bytes to kilobytes.
  232. $size = $size / Bytes::KILOBYTE;
  233. $units = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  234. foreach ($units as $unit) {
  235. if (round($size, 2) >= Bytes::KILOBYTE) {
  236. $size = $size / Bytes::KILOBYTE;
  237. }
  238. else {
  239. break;
  240. }
  241. }
  242. $args = ['@size' => round($size, 2)];
  243. $options = ['langcode' => $langcode];
  244. switch ($unit) {
  245. case 'KB':
  246. return new TranslatableMarkup('@size KB', $args, $options);
  247. case 'MB':
  248. return new TranslatableMarkup('@size MB', $args, $options);
  249. case 'GB':
  250. return new TranslatableMarkup('@size GB', $args, $options);
  251. case 'TB':
  252. return new TranslatableMarkup('@size TB', $args, $options);
  253. case 'PB':
  254. return new TranslatableMarkup('@size PB', $args, $options);
  255. case 'EB':
  256. return new TranslatableMarkup('@size EB', $args, $options);
  257. case 'ZB':
  258. return new TranslatableMarkup('@size ZB', $args, $options);
  259. case 'YB':
  260. return new TranslatableMarkup('@size YB', $args, $options);
  261. }
  262. }
  263. }
  264. /**
  265. * Formats a date, using a date type or a custom date format string.
  266. *
  267. * @param $timestamp
  268. * A UNIX timestamp to format.
  269. * @param $type
  270. * (optional) The format to use, one of:
  271. * - One of the built-in formats: 'short', 'medium',
  272. * 'long', 'html_datetime', 'html_date', 'html_time',
  273. * 'html_yearless_date', 'html_week', 'html_month', 'html_year'.
  274. * - The name of a date type defined by a date format config entity.
  275. * - The machine name of an administrator-defined date format.
  276. * - 'custom', to use $format.
  277. * Defaults to 'medium'.
  278. * @param $format
  279. * (optional) If $type is 'custom', a PHP date format string suitable for
  280. * input to date(). Use a backslash to escape ordinary text, so it does not
  281. * get interpreted as date format characters.
  282. * @param $timezone
  283. * (optional) Time zone identifier, as described at
  284. * http://php.net/manual/timezones.php Defaults to the time zone used to
  285. * display the page.
  286. * @param $langcode
  287. * (optional) Language code to translate to. Defaults to the language used to
  288. * display the page.
  289. *
  290. * @return
  291. * A translated date string in the requested format.
  292. *
  293. * @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
  294. * Use \Drupal::service('date.formatter')->format().
  295. *
  296. * @see \Drupal\Core\Datetime\DateFormatter::format()
  297. * @see https://www.drupal.org/node/1876852
  298. */
  299. function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {
  300. return \Drupal::service('date.formatter')->format($timestamp, $type, $format, $timezone, $langcode);
  301. }
  302. /**
  303. * Returns an ISO8601 formatted date based on the given date.
  304. *
  305. * @param $date
  306. * A UNIX timestamp.
  307. *
  308. * @return string
  309. * An ISO8601 formatted date.
  310. */
  311. function date_iso8601($date) {
  312. // The DATE_ISO8601 constant cannot be used here because it does not match
  313. // date('c') and produces invalid RDF markup.
  314. return date('c', $date);
  315. }
  316. /**
  317. * @} End of "defgroup format".
  318. */
  319. /**
  320. * Formats an attribute string for an HTTP header.
  321. *
  322. * @param $attributes
  323. * An associative array of attributes such as 'rel'.
  324. *
  325. * @return
  326. * A ; separated string ready for insertion in a HTTP header. No escaping is
  327. * performed for HTML entities, so this string is not safe to be printed.
  328. */
  329. function drupal_http_header_attributes(array $attributes = []) {
  330. foreach ($attributes as $attribute => &$data) {
  331. if (is_array($data)) {
  332. $data = implode(' ', $data);
  333. }
  334. $data = $attribute . '="' . $data . '"';
  335. }
  336. return $attributes ? ' ' . implode('; ', $attributes) : '';
  337. }
  338. /**
  339. * Attempts to set the PHP maximum execution time.
  340. *
  341. * This function is a wrapper around the PHP function set_time_limit().
  342. * When called, set_time_limit() restarts the timeout counter from zero.
  343. * In other words, if the timeout is the default 30 seconds, and 25 seconds
  344. * into script execution a call such as set_time_limit(20) is made, the
  345. * script will run for a total of 45 seconds before timing out.
  346. *
  347. * If the current time limit is not unlimited it is possible to decrease the
  348. * total time limit if the sum of the new time limit and the current time spent
  349. * running the script is inferior to the original time limit. It is inherent to
  350. * the way set_time_limit() works, it should rather be called with an
  351. * appropriate value every time you need to allocate a certain amount of time
  352. * to execute a task than only once at the beginning of the script.
  353. *
  354. * Before calling set_time_limit(), we check if this function is available
  355. * because it could be disabled by the server administrator. We also hide all
  356. * the errors that could occur when calling set_time_limit(), because it is
  357. * not possible to reliably ensure that PHP or a security extension will
  358. * not issue a warning/error if they prevent the use of this function.
  359. *
  360. * @param $time_limit
  361. * An integer specifying the new time limit, in seconds. A value of 0
  362. * indicates unlimited execution time.
  363. *
  364. * @ingroup php_wrappers
  365. */
  366. function drupal_set_time_limit($time_limit) {
  367. if (function_exists('set_time_limit')) {
  368. $current = ini_get('max_execution_time');
  369. // Do not set time limit if it is currently unlimited.
  370. if ($current != 0) {
  371. @set_time_limit($time_limit);
  372. }
  373. }
  374. }
  375. /**
  376. * Returns the base URL path (i.e., directory) of the Drupal installation.
  377. *
  378. * Function base_path() adds a "/" to the beginning and end of the returned path
  379. * if the path is not empty. At the very least, this will return "/".
  380. *
  381. * Examples:
  382. * - http://example.com returns "/" because the path is empty.
  383. * - http://example.com/drupal/folder returns "/drupal/folder/".
  384. */
  385. function base_path() {
  386. return $GLOBALS['base_path'];
  387. }
  388. /**
  389. * Deletes old cached CSS files.
  390. *
  391. * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
  392. * Use \Drupal\Core\Asset\AssetCollectionOptimizerInterface::deleteAll().
  393. *
  394. * @see https://www.drupal.org/node/2317841
  395. */
  396. function drupal_clear_css_cache() {
  397. \Drupal::service('asset.css.collection_optimizer')->deleteAll();
  398. }
  399. /**
  400. * Constructs an array of the defaults that are used for JavaScript assets.
  401. *
  402. * @param $data
  403. * (optional) The default data parameter for the JavaScript asset array.
  404. *
  405. * @see hook_js_alter()
  406. */
  407. function drupal_js_defaults($data = NULL) {
  408. return [
  409. 'type' => 'file',
  410. 'group' => JS_DEFAULT,
  411. 'weight' => 0,
  412. 'scope' => 'header',
  413. 'cache' => TRUE,
  414. 'preprocess' => TRUE,
  415. 'attributes' => [],
  416. 'version' => NULL,
  417. 'data' => $data,
  418. 'browsers' => [],
  419. ];
  420. }
  421. /**
  422. * Adds JavaScript to change the state of an element based on another element.
  423. *
  424. * A "state" means a certain property on a DOM element, such as "visible" or
  425. * "checked". A state can be applied to an element, depending on the state of
  426. * another element on the page. In general, states depend on HTML attributes and
  427. * DOM element properties, which change due to user interaction.
  428. *
  429. * Since states are driven by JavaScript only, it is important to understand
  430. * that all states are applied on presentation only, none of the states force
  431. * any server-side logic, and that they will not be applied for site visitors
  432. * without JavaScript support. All modules implementing states have to make
  433. * sure that the intended logic also works without JavaScript being enabled.
  434. *
  435. * #states is an associative array in the form of:
  436. * @code
  437. * array(
  438. * STATE1 => CONDITIONS_ARRAY1,
  439. * STATE2 => CONDITIONS_ARRAY2,
  440. * ...
  441. * )
  442. * @endcode
  443. * Each key is the name of a state to apply to the element, such as 'visible'.
  444. * Each value is a list of conditions that denote when the state should be
  445. * applied.
  446. *
  447. * Multiple different states may be specified to act on complex conditions:
  448. * @code
  449. * array(
  450. * 'visible' => CONDITIONS,
  451. * 'checked' => OTHER_CONDITIONS,
  452. * )
  453. * @endcode
  454. *
  455. * Every condition is a key/value pair, whose key is a jQuery selector that
  456. * denotes another element on the page, and whose value is an array of
  457. * conditions, which must bet met on that element:
  458. * @code
  459. * array(
  460. * 'visible' => array(
  461. * JQUERY_SELECTOR => REMOTE_CONDITIONS,
  462. * JQUERY_SELECTOR => REMOTE_CONDITIONS,
  463. * ...
  464. * ),
  465. * )
  466. * @endcode
  467. * All conditions must be met for the state to be applied.
  468. *
  469. * Each remote condition is a key/value pair specifying conditions on the other
  470. * element that need to be met to apply the state to the element:
  471. * @code
  472. * array(
  473. * 'visible' => array(
  474. * ':input[name="remote_checkbox"]' => array('checked' => TRUE),
  475. * ),
  476. * )
  477. * @endcode
  478. *
  479. * For example, to show a textfield only when a checkbox is checked:
  480. * @code
  481. * $form['toggle_me'] = array(
  482. * '#type' => 'checkbox',
  483. * '#title' => t('Tick this box to type'),
  484. * );
  485. * $form['settings'] = array(
  486. * '#type' => 'textfield',
  487. * '#states' => array(
  488. * // Only show this field when the 'toggle_me' checkbox is enabled.
  489. * 'visible' => array(
  490. * ':input[name="toggle_me"]' => array('checked' => TRUE),
  491. * ),
  492. * ),
  493. * );
  494. * @endcode
  495. *
  496. * The following states may be applied to an element:
  497. * - enabled
  498. * - disabled
  499. * - required
  500. * - optional
  501. * - visible
  502. * - invisible
  503. * - checked
  504. * - unchecked
  505. * - expanded
  506. * - collapsed
  507. *
  508. * The following states may be used in remote conditions:
  509. * - empty
  510. * - filled
  511. * - checked
  512. * - unchecked
  513. * - expanded
  514. * - collapsed
  515. * - value
  516. *
  517. * The following states exist for both elements and remote conditions, but are
  518. * not fully implemented and may not change anything on the element:
  519. * - relevant
  520. * - irrelevant
  521. * - valid
  522. * - invalid
  523. * - touched
  524. * - untouched
  525. * - readwrite
  526. * - readonly
  527. *
  528. * When referencing select lists and radio buttons in remote conditions, a
  529. * 'value' condition must be used:
  530. * @code
  531. * '#states' => array(
  532. * // Show the settings if 'bar' has been selected for 'foo'.
  533. * 'visible' => array(
  534. * ':input[name="foo"]' => array('value' => 'bar'),
  535. * ),
  536. * ),
  537. * @endcode
  538. *
  539. * @param $elements
  540. * A renderable array element having a #states property as described above.
  541. *
  542. * @see form_example_states_form()
  543. */
  544. function drupal_process_states(&$elements) {
  545. $elements['#attached']['library'][] = 'core/drupal.states';
  546. // Elements of '#type' => 'item' are not actual form input elements, but we
  547. // still want to be able to show/hide them. Since there's no actual HTML input
  548. // element available, setting #attributes does not make sense, but a wrapper
  549. // is available, so setting #wrapper_attributes makes it work.
  550. $key = ($elements['#type'] == 'item') ? '#wrapper_attributes' : '#attributes';
  551. $elements[$key]['data-drupal-states'] = Json::encode($elements['#states']);
  552. }
  553. /**
  554. * Assists in attaching the tableDrag JavaScript behavior to a themed table.
  555. *
  556. * Draggable tables should be used wherever an outline or list of sortable items
  557. * needs to be arranged by an end-user. Draggable tables are very flexible and
  558. * can manipulate the value of form elements placed within individual columns.
  559. *
  560. * To set up a table to use drag and drop in place of weight select-lists or in
  561. * place of a form that contains parent relationships, the form must be themed
  562. * into a table. The table must have an ID attribute set and it
  563. * may be set as follows:
  564. * @code
  565. * $table = array(
  566. * '#type' => 'table',
  567. * '#header' => $header,
  568. * '#rows' => $rows,
  569. * '#attributes' => array(
  570. * 'id' => 'my-module-table',
  571. * ),
  572. * );
  573. * return \Drupal::service('renderer')->render($table);
  574. * @endcode
  575. *
  576. * In the theme function for the form, a special class must be added to each
  577. * form element within the same column, "grouping" them together.
  578. *
  579. * In a situation where a single weight column is being sorted in the table, the
  580. * classes could be added like this (in the theme function):
  581. * @code
  582. * $form['my_elements'][$delta]['weight']['#attributes']['class'] = array('my-elements-weight');
  583. * @endcode
  584. *
  585. * Each row of the table must also have a class of "draggable" in order to
  586. * enable the drag handles:
  587. * @code
  588. * $row = array(...);
  589. * $rows[] = array(
  590. * 'data' => $row,
  591. * 'class' => array('draggable'),
  592. * );
  593. * @endcode
  594. *
  595. * When tree relationships are present, the two additional classes
  596. * 'tabledrag-leaf' and 'tabledrag-root' can be used to refine the behavior:
  597. * - Rows with the 'tabledrag-leaf' class cannot have child rows.
  598. * - Rows with the 'tabledrag-root' class cannot be nested under a parent row.
  599. *
  600. * Calling drupal_attach_tabledrag() would then be written as such:
  601. * @code
  602. * drupal_attach_tabledrag('my-module-table', array(
  603. * 'action' => 'order',
  604. * 'relationship' => 'sibling',
  605. * 'group' => 'my-elements-weight',
  606. * );
  607. * @endcode
  608. *
  609. * In a more complex case where there are several groups in one column (such as
  610. * the block regions on the admin/structure/block page), a separate subgroup
  611. * class must also be added to differentiate the groups.
  612. * @code
  613. * $form['my_elements'][$region][$delta]['weight']['#attributes']['class'] = array('my-elements-weight', 'my-elements-weight-' . $region);
  614. * @endcode
  615. *
  616. * The 'group' option is still 'my-element-weight', and the additional
  617. * 'subgroup' option will be passed in as 'my-elements-weight-' . $region. This
  618. * also means that you'll need to call drupal_attach_tabledrag() once for every
  619. * region added.
  620. *
  621. * @code
  622. * foreach ($regions as $region) {
  623. * drupal_attach_tabledrag('my-module-table', array(
  624. * 'action' => 'order',
  625. * 'relationship' => 'sibling',
  626. * 'group' => 'my-elements-weight',
  627. * 'subgroup' => 'my-elements-weight-' . $region,
  628. * ));
  629. * }
  630. * @endcode
  631. *
  632. * In a situation where tree relationships are present, adding multiple
  633. * subgroups is not necessary, because the table will contain indentations that
  634. * provide enough information about the sibling and parent relationships. See
  635. * MenuForm::BuildOverviewForm for an example creating a table
  636. * containing parent relationships.
  637. *
  638. * @param $element
  639. * A form element to attach the tableDrag behavior to.
  640. * @param array $options
  641. * These options are used to generate JavaScript settings necessary to
  642. * configure the tableDrag behavior appropriately for this particular table.
  643. * An associative array containing the following keys:
  644. * - 'table_id': String containing the target table's id attribute.
  645. * If the table does not have an id, one will need to be set,
  646. * such as <table id="my-module-table">.
  647. * - 'action': String describing the action to be done on the form item.
  648. * Either 'match' 'depth', or 'order':
  649. * - 'match' is typically used for parent relationships.
  650. * - 'order' is typically used to set weights on other form elements with
  651. * the same group.
  652. * - 'depth' updates the target element with the current indentation.
  653. * - 'relationship': String describing where the "action" option
  654. * should be performed. Either 'parent', 'sibling', 'group', or 'self':
  655. * - 'parent' will only look for fields up the tree.
  656. * - 'sibling' will look for fields in the same group in rows above and
  657. * below it.
  658. * - 'self' affects the dragged row itself.
  659. * - 'group' affects the dragged row, plus any children below it (the entire
  660. * dragged group).
  661. * - 'group': A class name applied on all related form elements for this action.
  662. * - 'subgroup': (optional) If the group has several subgroups within it, this
  663. * string should contain the class name identifying fields in the same
  664. * subgroup.
  665. * - 'source': (optional) If the $action is 'match', this string should contain
  666. * the classname identifying what field will be used as the source value
  667. * when matching the value in $subgroup.
  668. * - 'hidden': (optional) The column containing the field elements may be
  669. * entirely hidden from view dynamically when the JavaScript is loaded. Set
  670. * to FALSE if the column should not be hidden.
  671. * - 'limit': (optional) Limit the maximum amount of parenting in this table.
  672. *
  673. * @see MenuForm::BuildOverviewForm()
  674. */
  675. function drupal_attach_tabledrag(&$element, array $options) {
  676. // Add default values to elements.
  677. $options = $options + [
  678. 'subgroup' => NULL,
  679. 'source' => NULL,
  680. 'hidden' => TRUE,
  681. 'limit' => 0,
  682. ];
  683. $group = $options['group'];
  684. $tabledrag_id = &drupal_static(__FUNCTION__);
  685. $tabledrag_id = (!isset($tabledrag_id)) ? 0 : $tabledrag_id + 1;
  686. // If a subgroup or source isn't set, assume it is the same as the group.
  687. $target = isset($options['subgroup']) ? $options['subgroup'] : $group;
  688. $source = isset($options['source']) ? $options['source'] : $target;
  689. $element['#attached']['drupalSettings']['tableDrag'][$options['table_id']][$group][$tabledrag_id] = [
  690. 'target' => $target,
  691. 'source' => $source,
  692. 'relationship' => $options['relationship'],
  693. 'action' => $options['action'],
  694. 'hidden' => $options['hidden'],
  695. 'limit' => $options['limit'],
  696. ];
  697. $element['#attached']['library'][] = 'core/drupal.tabledrag';
  698. }
  699. /**
  700. * Deletes old cached JavaScript files and variables.
  701. *
  702. * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
  703. * Use \Drupal\Core\Asset\AssetCollectionOptimizerInterface::deleteAll().
  704. *
  705. * @see https://www.drupal.org/node/2317841
  706. */
  707. function drupal_clear_js_cache() {
  708. \Drupal::service('asset.js.collection_optimizer')->deleteAll();
  709. }
  710. /**
  711. * Pre-render callback: Renders a link into #markup.
  712. *
  713. * @deprecated in Drupal 8.x, will be removed before Drupal 9.0.
  714. * Use \Drupal\Core\Render\Element\Link::preRenderLink().
  715. */
  716. function drupal_pre_render_link($element) {
  717. return Link::preRenderLink($element);
  718. }
  719. /**
  720. * Pre-render callback: Collects child links into a single array.
  721. *
  722. * This function can be added as a pre_render callback for a renderable array,
  723. * usually one which will be themed by links.html.twig. It iterates through all
  724. * unrendered children of the element, collects any #links properties it finds,
  725. * merges them into the parent element's #links array, and prevents those
  726. * children from being rendered separately.
  727. *
  728. * The purpose of this is to allow links to be logically grouped into related
  729. * categories, so that each child group can be rendered as its own list of
  730. * links if drupal_render() is called on it, but calling drupal_render() on the
  731. * parent element will still produce a single list containing all the remaining
  732. * links, regardless of what group they were in.
  733. *
  734. * A typical example comes from node links, which are stored in a renderable
  735. * array similar to this:
  736. * @code
  737. * $build['links'] = array(
  738. * '#theme' => 'links__node',
  739. * '#pre_render' => array('drupal_pre_render_links'),
  740. * 'comment' => array(
  741. * '#theme' => 'links__node__comment',
  742. * '#links' => array(
  743. * // An array of links associated with node comments, suitable for
  744. * // passing in to links.html.twig.
  745. * ),
  746. * ),
  747. * 'statistics' => array(
  748. * '#theme' => 'links__node__statistics',
  749. * '#links' => array(
  750. * // An array of links associated with node statistics, suitable for
  751. * // passing in to links.html.twig.
  752. * ),
  753. * ),
  754. * 'translation' => array(
  755. * '#theme' => 'links__node__translation',
  756. * '#links' => array(
  757. * // An array of links associated with node translation, suitable for
  758. * // passing in to links.html.twig.
  759. * ),
  760. * ),
  761. * );
  762. * @endcode
  763. *
  764. * In this example, the links are grouped by functionality, which can be
  765. * helpful to themers who want to display certain kinds of links independently.
  766. * For example, adding this code to node.html.twig will result in the comment
  767. * links being rendered as a single list:
  768. * @code
  769. * {{ content.links.comment }}
  770. * @endcode
  771. *
  772. * (where a node's content has been transformed into $content before handing
  773. * control to the node.html.twig template).
  774. *
  775. * The pre_render function defined here allows the above flexibility, but also
  776. * allows the following code to be used to render all remaining links into a
  777. * single list, regardless of their group:
  778. * @code
  779. * {{ content.links }}
  780. * @endcode
  781. *
  782. * In the above example, this will result in the statistics and translation
  783. * links being rendered together in a single list (but not the comment links,
  784. * which were rendered previously on their own).
  785. *
  786. * Because of the way this function works, the individual properties of each
  787. * group (for example, a group-specific #theme property such as
  788. * 'links__node__comment' in the example above, or any other property such as
  789. * #attributes or #pre_render that is attached to it) are only used when that
  790. * group is rendered on its own. When the group is rendered together with other
  791. * children, these child-specific properties are ignored, and only the overall
  792. * properties of the parent are used.
  793. */
  794. function drupal_pre_render_links($element) {
  795. $element += ['#links' => [], '#attached' => []];
  796. foreach (Element::children($element) as $key) {
  797. $child = &$element[$key];
  798. // If the child has links which have not been printed yet and the user has
  799. // access to it, merge its links in to the parent.
  800. if (isset($child['#links']) && empty($child['#printed']) && Element::isVisibleElement($child)) {
  801. $element['#links'] += $child['#links'];
  802. // Mark the child as having been printed already (so that its links
  803. // cannot be mistakenly rendered twice).
  804. $child['#printed'] = TRUE;
  805. }
  806. // Merge attachments.
  807. if (isset($child['#attached'])) {
  808. $element['#attached'] = BubbleableMetadata::mergeAttachments($element['#attached'], $child['#attached']);
  809. }
  810. }
  811. return $element;
  812. }
  813. /**
  814. * Renders final HTML given a structured array tree.
  815. *
  816. * @deprecated as of Drupal 8.0.x, will be removed before Drupal 9.0.0. Use the
  817. * 'renderer' service instead.
  818. *
  819. * @see \Drupal\Core\Render\RendererInterface::renderRoot()
  820. * @see https://www.drupal.org/node/2912696
  821. */
  822. function drupal_render_root(&$elements) {
  823. return \Drupal::service('renderer')->renderRoot($elements);
  824. }
  825. /**
  826. * Renders HTML given a structured array tree.
  827. *
  828. * @deprecated as of Drupal 8.0.x, will be removed before Drupal 9.0.0. Use the
  829. * 'renderer' service instead.
  830. *
  831. * @see \Drupal\Core\Render\RendererInterface::render()
  832. * @see https://www.drupal.org/node/2912696
  833. */
  834. function drupal_render(&$elements, $is_recursive_call = FALSE) {
  835. return \Drupal::service('renderer')->render($elements, $is_recursive_call);
  836. }
  837. /**
  838. * Renders children of an element and concatenates them.
  839. *
  840. * @param array $element
  841. * The structured array whose children shall be rendered.
  842. * @param array $children_keys
  843. * (optional) If the keys of the element's children are already known, they
  844. * can be passed in to save another run of
  845. * \Drupal\Core\Render\Element::children().
  846. *
  847. * @return string|\Drupal\Component\Render\MarkupInterface
  848. * The rendered HTML of all children of the element.
  849. *
  850. * @deprecated in Drupal 8.0.x and will be removed before 9.0.0. Avoid early
  851. * rendering when possible or loop through the elements and render them as
  852. * they are available.
  853. *
  854. * @see \Drupal\Core\Render\RendererInterface::render()
  855. * @see https://www.drupal.org/node/2912757
  856. */
  857. function drupal_render_children(&$element, $children_keys = NULL) {
  858. if ($children_keys === NULL) {
  859. $children_keys = Element::children($element);
  860. }
  861. $output = '';
  862. foreach ($children_keys as $key) {
  863. if (!empty($element[$key])) {
  864. $output .= \Drupal::service('renderer')->render($element[$key]);
  865. }
  866. }
  867. return Markup::create($output);
  868. }
  869. /**
  870. * Renders an element.
  871. *
  872. * This function renders an element. The top level element is shown with show()
  873. * before rendering, so it will always be rendered even if hide() had been
  874. * previously used on it.
  875. *
  876. * @param $element
  877. * The element to be rendered.
  878. *
  879. * @return
  880. * The rendered element.
  881. *
  882. * @see \Drupal\Core\Render\RendererInterface
  883. * @see show()
  884. * @see hide()
  885. */
  886. function render(&$element) {
  887. if (!$element && $element !== 0) {
  888. return NULL;
  889. }
  890. if (is_array($element)) {
  891. // Early return if this element was pre-rendered (no need to re-render).
  892. if (isset($element['#printed']) && $element['#printed'] == TRUE && isset($element['#markup']) && strlen($element['#markup']) > 0) {
  893. return $element['#markup'];
  894. }
  895. show($element);
  896. return \Drupal::service('renderer')->render($element);
  897. }
  898. else {
  899. // Safe-guard for inappropriate use of render() on flat variables: return
  900. // the variable as-is.
  901. return $element;
  902. }
  903. }
  904. /**
  905. * Hides an element from later rendering.
  906. *
  907. * The first time render() or drupal_render() is called on an element tree,
  908. * as each element in the tree is rendered, it is marked with a #printed flag
  909. * and the rendered children of the element are cached. Subsequent calls to
  910. * render() or drupal_render() will not traverse the child tree of this element
  911. * again: they will just use the cached children. So if you want to hide an
  912. * element, be sure to call hide() on the element before its parent tree is
  913. * rendered for the first time, as it will have no effect on subsequent
  914. * renderings of the parent tree.
  915. *
  916. * @param $element
  917. * The element to be hidden.
  918. *
  919. * @return
  920. * The element.
  921. *
  922. * @see render()
  923. * @see show()
  924. */
  925. function hide(&$element) {
  926. $element['#printed'] = TRUE;
  927. return $element;
  928. }
  929. /**
  930. * Shows a hidden element for later rendering.
  931. *
  932. * You can also use render($element), which shows the element while rendering
  933. * it.
  934. *
  935. * The first time render() or drupal_render() is called on an element tree,
  936. * as each element in the tree is rendered, it is marked with a #printed flag
  937. * and the rendered children of the element are cached. Subsequent calls to
  938. * render() or drupal_render() will not traverse the child tree of this element
  939. * again: they will just use the cached children. So if you want to show an
  940. * element, be sure to call show() on the element before its parent tree is
  941. * rendered for the first time, as it will have no effect on subsequent
  942. * renderings of the parent tree.
  943. *
  944. * @param $element
  945. * The element to be shown.
  946. *
  947. * @return
  948. * The element.
  949. *
  950. * @see render()
  951. * @see hide()
  952. */
  953. function show(&$element) {
  954. $element['#printed'] = FALSE;
  955. return $element;
  956. }
  957. /**
  958. * Retrieves the default properties for the defined element type.
  959. *
  960. * @param $type
  961. * An element type as defined by an element plugin.
  962. *
  963. * @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
  964. * Use \Drupal::service('element_info')->getInfo() instead.
  965. *
  966. * @see https://www.drupal.org/node/2235461
  967. */
  968. function element_info($type) {
  969. return \Drupal::service('element_info')->getInfo($type);
  970. }
  971. /**
  972. * Retrieves a single property for the defined element type.
  973. *
  974. * @param $type
  975. * An element type as defined by an element plugin.
  976. * @param $property_name
  977. * The property within the element type that should be returned.
  978. * @param $default
  979. * (Optional) The value to return if the element type does not specify a
  980. * value for the property. Defaults to NULL.
  981. *
  982. * @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
  983. * Use \Drupal::service('element_info')->getInfoProperty() instead.
  984. *
  985. * @see https://www.drupal.org/node/2235461
  986. */
  987. function element_info_property($type, $property_name, $default = NULL) {
  988. return \Drupal::service('element_info')->getInfoProperty($type, $property_name, $default);
  989. }
  990. /**
  991. * Flushes all persistent caches, resets all variables, and rebuilds all data structures.
  992. *
  993. * At times, it is necessary to re-initialize the entire system to account for
  994. * changed or new code. This function:
  995. * - Clears all persistent caches:
  996. * - The bootstrap cache bin containing base system, module system, and theme
  997. * system information.
  998. * - The common 'default' cache bin containing arbitrary caches.
  999. * - The page cache.
  1000. * - The URL alias path cache.
  1001. * - Resets all static variables that have been defined via drupal_static().
  1002. * - Clears asset (JS/CSS) file caches.
  1003. * - Updates the system with latest information about extensions (modules and
  1004. * themes).
  1005. * - Updates the bootstrap flag for modules implementing bootstrap_hooks().
  1006. * - Rebuilds the full database schema information (invoking hook_schema()).
  1007. * - Rebuilds data structures of all modules (invoking hook_rebuild()). In
  1008. * core this means
  1009. * - blocks, node types, date formats and actions are synchronized with the
  1010. * database
  1011. * - The 'active' status of fields is refreshed.
  1012. * - Rebuilds the menu router.
  1013. *
  1014. * This means the entire system is reset so all caches and static variables are
  1015. * effectively empty. After that is guaranteed, information about the currently
  1016. * active code is updated, and rebuild operations are successively called in
  1017. * order to synchronize the active system according to the current information
  1018. * defined in code.
  1019. *
  1020. * All modules need to ensure that all of their caches are flushed when
  1021. * hook_cache_flush() is invoked; any previously known information must no
  1022. * longer exist. All following hook_rebuild() operations must be based on fresh
  1023. * and current system data. All modules must be able to rely on this contract.
  1024. *
  1025. * @see \Drupal\Core\Cache\CacheHelper::getBins()
  1026. * @see hook_cache_flush()
  1027. * @see hook_rebuild()
  1028. *
  1029. * This function also resets the theme, which means it is not initialized
  1030. * anymore and all previously added JavaScript and CSS is gone. Normally, this
  1031. * function is called as an end-of-POST-request operation that is followed by a
  1032. * redirect, so this effect is not visible. Since the full reset is the whole
  1033. * point of this function, callers need to take care for backing up all needed
  1034. * variables and properly restoring or re-initializing them on their own. For
  1035. * convenience, this function automatically re-initializes the maintenance theme
  1036. * if it was initialized before.
  1037. *
  1038. * @todo Try to clear page/JS/CSS caches last, so cached pages can still be
  1039. * served during this possibly long-running operation. (Conflict on bootstrap
  1040. * cache though.)
  1041. * @todo Add a global lock to ensure that caches are not primed in concurrent
  1042. * requests.
  1043. */
  1044. function drupal_flush_all_caches() {
  1045. $module_handler = \Drupal::moduleHandler();
  1046. // Flush all persistent caches.
  1047. // This is executed based on old/previously known information, which is
  1048. // sufficient, since new extensions cannot have any primed caches yet.
  1049. $module_handler->invokeAll('cache_flush');
  1050. foreach (Cache::getBins() as $service_id => $cache_backend) {
  1051. $cache_backend->deleteAll();
  1052. }
  1053. // Flush asset file caches.
  1054. \Drupal::service('asset.css.collection_optimizer')->deleteAll();
  1055. \Drupal::service('asset.js.collection_optimizer')->deleteAll();
  1056. _drupal_flush_css_js();
  1057. // Reset all static caches.
  1058. drupal_static_reset();
  1059. // Invalidate the container.
  1060. \Drupal::service('kernel')->invalidateContainer();
  1061. // Wipe the Twig PHP Storage cache.
  1062. \Drupal::service('twig')->invalidate();
  1063. // Rebuild module and theme data.
  1064. $module_data = system_rebuild_module_data();
  1065. /** @var \Drupal\Core\Extension\ThemeHandlerInterface $theme_handler */
  1066. $theme_handler = \Drupal::service('theme_handler');
  1067. $theme_handler->refreshInfo();
  1068. // In case the active theme gets requested later in the same request we need
  1069. // to reset the theme manager.
  1070. \Drupal::theme()->resetActiveTheme();
  1071. // Rebuild and reboot a new kernel. A simple DrupalKernel reboot is not
  1072. // sufficient, since the list of enabled modules might have been adjusted
  1073. // above due to changed code.
  1074. $files = [];
  1075. foreach ($module_data as $name => $extension) {
  1076. if ($extension->status) {
  1077. $files[$name] = $extension;
  1078. }
  1079. }
  1080. \Drupal::service('kernel')->updateModules($module_handler->getModuleList(), $files);
  1081. // New container, new module handler.
  1082. $module_handler = \Drupal::moduleHandler();
  1083. // Ensure that all modules that are currently supposed to be enabled are
  1084. // actually loaded.
  1085. $module_handler->loadAll();
  1086. // Rebuild all information based on new module data.
  1087. $module_handler->invokeAll('rebuild');
  1088. // Clear all plugin caches.
  1089. \Drupal::service('plugin.cache_clearer')->clearCachedDefinitions();
  1090. // Rebuild the menu router based on all rebuilt data.
  1091. // Important: This rebuild must happen last, so the menu router is guaranteed
  1092. // to be based on up to date information.
  1093. \Drupal::service('router.builder')->rebuild();
  1094. // Re-initialize the maintenance theme, if the current request attempted to
  1095. // use it. Unlike regular usages of this function, the installer and update
  1096. // scripts need to flush all caches during GET requests/page building.
  1097. if (function_exists('_drupal_maintenance_theme')) {
  1098. \Drupal::theme()->resetActiveTheme();
  1099. drupal_maintenance_theme();
  1100. }
  1101. }
  1102. /**
  1103. * Changes the dummy query string added to all CSS and JavaScript files.
  1104. *
  1105. * Changing the dummy query string appended to CSS and JavaScript files forces
  1106. * all browsers to reload fresh files.
  1107. */
  1108. function _drupal_flush_css_js() {
  1109. // The timestamp is converted to base 36 in order to make it more compact.
  1110. Drupal::state()->set('system.css_js_query_string', base_convert(REQUEST_TIME, 10, 36));
  1111. }
  1112. /**
  1113. * Outputs debug information.
  1114. *
  1115. * The debug information is passed on to trigger_error() after being converted
  1116. * to a string using _drupal_debug_message().
  1117. *
  1118. * @param $data
  1119. * Data to be output.
  1120. * @param $label
  1121. * Label to prefix the data.
  1122. * @param $print_r
  1123. * Flag to switch between print_r() and var_export() for data conversion to
  1124. * string. Set $print_r to FALSE to use var_export() instead of print_r().
  1125. * Passing recursive data structures to var_export() will generate an error.
  1126. */
  1127. function debug($data, $label = NULL, $print_r = TRUE) {
  1128. // Print $data contents to string.
  1129. $string = Html::escape($print_r ? print_r($data, TRUE) : var_export($data, TRUE));
  1130. // Display values with pre-formatting to increase readability.
  1131. $string = '<pre>' . $string . '</pre>';
  1132. trigger_error(trim($label ? "$label: $string" : $string));
  1133. }
  1134. /**
  1135. * Checks whether a version is compatible with a given dependency.
  1136. *
  1137. * @param $v
  1138. * A parsed dependency structure e.g. from ModuleHandler::parseDependency().
  1139. * @param $current_version
  1140. * The version to check against (like 4.2).
  1141. *
  1142. * @return
  1143. * NULL if compatible, otherwise the original dependency version string that
  1144. * caused the incompatibility.
  1145. *
  1146. * @see \Drupal\Core\Extension\ModuleHandler::parseDependency()
  1147. */
  1148. function drupal_check_incompatibility($v, $current_version) {
  1149. if (!empty($v['versions'])) {
  1150. foreach ($v['versions'] as $required_version) {
  1151. if ((isset($required_version['op']) && !version_compare($current_version, $required_version['version'], $required_version['op']))) {
  1152. return $v['original_version'];
  1153. }
  1154. }
  1155. }
  1156. }
  1157. /**
  1158. * Returns a string of supported archive extensions.
  1159. *
  1160. * @return
  1161. * A space-separated string of extensions suitable for use by the file
  1162. * validation system.
  1163. */
  1164. function archiver_get_extensions() {
  1165. $valid_extensions = [];
  1166. foreach (\Drupal::service('plugin.manager.archiver')->getDefinitions() as $archive) {
  1167. foreach ($archive['extensions'] as $extension) {
  1168. foreach (explode('.', $extension) as $part) {
  1169. if (!in_array($part, $valid_extensions)) {
  1170. $valid_extensions[] = $part;
  1171. }
  1172. }
  1173. }
  1174. }
  1175. return implode(' ', $valid_extensions);
  1176. }
  1177. /**
  1178. * Creates the appropriate archiver for the specified file.
  1179. *
  1180. * @param $file
  1181. * The full path of the archive file. Note that stream wrapper paths are
  1182. * supported, but not remote ones.
  1183. *
  1184. * @return
  1185. * A newly created instance of the archiver class appropriate
  1186. * for the specified file, already bound to that file.
  1187. * If no appropriate archiver class was found, will return FALSE.
  1188. */
  1189. function archiver_get_archiver($file) {
  1190. // Archivers can only work on local paths
  1191. $filepath = \Drupal::service('file_system')->realpath($file);
  1192. if (!is_file($filepath)) {
  1193. throw new Exception(t('Archivers can only operate on local files: %file not supported', ['%file' => $file]));
  1194. }
  1195. return \Drupal::service('plugin.manager.archiver')->getInstance(['filepath' => $filepath]);
  1196. }
  1197. /**
  1198. * Assembles the Drupal Updater registry.
  1199. *
  1200. * An Updater is a class that knows how to update various parts of the Drupal
  1201. * file system, for example to update modules that have newer releases, or to
  1202. * install a new theme.
  1203. *
  1204. * @return array
  1205. * The Drupal Updater class registry.
  1206. *
  1207. * @see \Drupal\Core\Updater\Updater
  1208. * @see hook_updater_info()
  1209. * @see hook_updater_info_alter()
  1210. */
  1211. function drupal_get_updaters() {
  1212. $updaters = &drupal_static(__FUNCTION__);
  1213. if (!isset($updaters)) {
  1214. $updaters = \Drupal::moduleHandler()->invokeAll('updater_info');
  1215. \Drupal::moduleHandler()->alter('updater_info', $updaters);
  1216. uasort($updaters, [SortArray::class, 'sortByWeightElement']);
  1217. }
  1218. return $updaters;
  1219. }
  1220. /**
  1221. * Assembles the Drupal FileTransfer registry.
  1222. *
  1223. * @return
  1224. * The Drupal FileTransfer class registry.
  1225. *
  1226. * @see \Drupal\Core\FileTransfer\FileTransfer
  1227. * @see hook_filetransfer_info()
  1228. * @see hook_filetransfer_info_alter()
  1229. */
  1230. function drupal_get_filetransfer_info() {
  1231. $info = &drupal_static(__FUNCTION__);
  1232. if (!isset($info)) {
  1233. $info = \Drupal::moduleHandler()->invokeAll('filetransfer_info');
  1234. \Drupal::moduleHandler()->alter('filetransfer_info', $info);
  1235. uasort($info, [SortArray::class, 'sortByWeightElement']);
  1236. }
  1237. return $info;
  1238. }