common.inc 44 KB

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