Drupal investigation

common.inc 43KB

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