common.inc 44 KB

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