entity.module 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569
  1. <?php
  2. /**
  3. * @file
  4. * Module file for the entity API.
  5. */
  6. module_load_include('inc', 'entity', 'modules/callbacks');
  7. module_load_include('inc', 'entity', 'includes/entity.property');
  8. /**
  9. * Defines status codes used for exportable entities.
  10. */
  11. /**
  12. * A bit flag used to let us know if an entity is in the database.
  13. */
  14. /**
  15. * A bit flag used to let us know if an entity has been customly defined.
  16. */
  17. define('ENTITY_CUSTOM', 0x01);
  18. /**
  19. * Deprecated, but still here for backward compatibility.
  20. */
  21. define('ENTITY_IN_DB', 0x01);
  22. /**
  23. * A bit flag used to let us know if an entity is a 'default' in code.
  24. */
  25. define('ENTITY_IN_CODE', 0x02);
  26. /**
  27. * A bit flag used to mark entities as overridden, e.g. they were originally
  28. * definded in code and are saved now in the database. Same as
  29. * (ENTITY_CUSTOM | ENTITY_IN_CODE).
  30. */
  31. define('ENTITY_OVERRIDDEN', 0x03);
  32. /**
  33. * A bit flag used to mark entities as fixed, thus not changeable for any
  34. * user.
  35. */
  36. define('ENTITY_FIXED', 0x04 | 0x02);
  37. /**
  38. * Determines whether for the given entity type a given operation is available.
  39. *
  40. * @param $entity_type
  41. * The type of the entity.
  42. * @param $op
  43. * One of 'create', 'view', 'save', 'delete', 'revision delete', 'access' or
  44. * 'form'.
  45. *
  46. * @return boolean
  47. * Whether the entity type supports the given operation.
  48. */
  49. function entity_type_supports($entity_type, $op) {
  50. $info = entity_get_info($entity_type);
  51. $keys = array(
  52. 'view' => 'view callback',
  53. 'create' => 'creation callback',
  54. 'delete' => 'deletion callback',
  55. 'revision delete' => 'revision deletion callback',
  56. 'save' => 'save callback',
  57. 'access' => 'access callback',
  58. 'form' => 'form callback'
  59. );
  60. if (isset($info[$keys[$op]])) {
  61. return TRUE;
  62. }
  63. if ($op == 'revision delete') {
  64. return in_array('EntityAPIControllerInterface', class_implements($info['controller class']));
  65. }
  66. if ($op == 'form') {
  67. return (bool) entity_ui_controller($entity_type);
  68. }
  69. if ($op != 'access') {
  70. return in_array('EntityAPIControllerInterface', class_implements($info['controller class']));
  71. }
  72. return FALSE;
  73. }
  74. /**
  75. * Menu loader function: load an entity from its path.
  76. *
  77. * This can be used to load entities of all types in menu paths:
  78. *
  79. * @code
  80. * $items['myentity/%entity_object'] = array(
  81. * 'load arguments' => array('myentity'),
  82. * 'title' => ...,
  83. * 'page callback' => ...,
  84. * 'page arguments' => array(...),
  85. * 'access arguments' => array(...),
  86. * );
  87. * @endcode
  88. *
  89. * @param $entity_id
  90. * The ID of the entity to load, passed by the menu URL.
  91. * @param $entity_type
  92. * The type of the entity to load.
  93. * @return
  94. * A fully loaded entity object, or FALSE in case of error.
  95. */
  96. function entity_object_load($entity_id, $entity_type) {
  97. $entities = entity_load($entity_type, array($entity_id));
  98. return reset($entities);
  99. }
  100. /**
  101. * Page callback to show links to add an entity of a specific bundle.
  102. *
  103. * Entity modules that provide a further description to their bundles may wish
  104. * to implement their own version of this to show these.
  105. *
  106. * @param $entity_type
  107. * The type of the entity.
  108. */
  109. function entity_ui_bundle_add_page($entity_type) {
  110. // Set the title, as we're a MENU_LOCAL_ACTION and hence just get tab titles.
  111. module_load_include('inc', 'entity', 'includes/entity.ui');
  112. drupal_set_title(entity_ui_get_action_title('add', $entity_type));
  113. // Get entity info for our bundles.
  114. $info = entity_get_info($entity_type);
  115. $items = array();
  116. foreach ($info['bundles'] as $bundle_name => $bundle_info) {
  117. // Create an empty entity with just the bundle set to check for access.
  118. $dummy_entity = entity_create($entity_type, array(
  119. $info['entity keys']['bundle'] => $bundle_name,
  120. ));
  121. // If modules use a uid, they can default to the current-user
  122. // in their create() method on the storage controller.
  123. if (entity_access('create', $entity_type, $dummy_entity, $account = NULL)) {
  124. $add_path = $info['admin ui']['path'] . '/add/' . $bundle_name;
  125. $items[] = l(t('Add @label', array('@label' => $bundle_info['label'])), $add_path);
  126. }
  127. }
  128. return theme('item_list', array('items' => $items));
  129. }
  130. /**
  131. * Page callback to add an entity of a specific bundle.
  132. *
  133. * @param $entity_type
  134. * The type of the entity.
  135. * @param $bundle_name
  136. * The bundle machine name.
  137. */
  138. function entity_ui_get_bundle_add_form($entity_type, $bundle_name) {
  139. $info = entity_get_info($entity_type);
  140. $bundle_key = $info['entity keys']['bundle'];
  141. // Make a stub entity of the right bundle to pass to the entity_ui_get_form().
  142. $values = array(
  143. $bundle_key => $bundle_name,
  144. );
  145. $entity = entity_create($entity_type, $values);
  146. return entity_ui_get_form($entity_type, $entity, 'add');
  147. }
  148. /**
  149. * Page callback for viewing an entity.
  150. *
  151. * @param Entity $entity
  152. * The entity to be rendered.
  153. *
  154. * @return array
  155. * A renderable array of the entity in full view mode.
  156. */
  157. function entity_ui_entity_page_view($entity) {
  158. module_load_include('inc', 'entity', 'includes/entity.ui');
  159. return $entity->view('full', NULL, TRUE);
  160. }
  161. /**
  162. * Gets the page title for the passed operation.
  163. */
  164. function entity_ui_get_page_title($op, $entity_type, $entity = NULL) {
  165. module_load_include('inc', 'entity', 'includes/entity.ui');
  166. $label = entity_label($entity_type, $entity);
  167. switch ($op) {
  168. case 'view':
  169. return $label;
  170. case 'edit':
  171. return t('Edit @label', array('@label' => $label));
  172. case 'clone':
  173. return t('Clone @label', array('@label' => $label));
  174. case 'revert':
  175. return t('Revert @label', array('@label' => $label));
  176. case 'delete':
  177. return t('Delete @label', array('@label' => $label));
  178. case 'export':
  179. return t('Export @label', array('@label' => $label));
  180. }
  181. if (isset($entity)) {
  182. list(, , $bundle) = entity_extract_ids($entity_type, $entity);
  183. }
  184. else {
  185. $bundle = NULL;
  186. }
  187. return entity_ui_get_action_title($op, $entity_type, $bundle);
  188. }
  189. /**
  190. * A wrapper around entity_load() to load a single entity by name or numeric id.
  191. *
  192. * @todo: Re-name entity_load() to entity_load_multiple() in d8 core and this
  193. * to entity_load().
  194. *
  195. * @param $entity_type
  196. * The entity type to load, e.g. node or user.
  197. * @param $id
  198. * The entity id, either the numeric id or the entity name. In case the entity
  199. * type has specified a name key, both the numeric id and the name may be
  200. * passed.
  201. *
  202. * @return
  203. * The entity object, or FALSE.
  204. *
  205. * @see entity_load()
  206. */
  207. function entity_load_single($entity_type, $id) {
  208. $entities = entity_load($entity_type, array($id));
  209. return reset($entities);
  210. }
  211. /**
  212. * A wrapper around entity_load() to return entities keyed by name key if existing.
  213. *
  214. * @param $entity_type
  215. * The entity type to load, e.g. node or user.
  216. * @param $names
  217. * An array of entity names or ids, or FALSE to load all entities.
  218. * @param $conditions
  219. * (deprecated) An associative array of conditions on the base table, where
  220. * the keys are the database fields and the values are the values those
  221. * fields must have. Instead, it is preferable to use EntityFieldQuery to
  222. * retrieve a list of entity IDs loadable by this function.
  223. *
  224. * @return
  225. * An array of entity objects indexed by their names (or ids if the entity
  226. * type has no name key).
  227. *
  228. * @see entity_load()
  229. */
  230. function entity_load_multiple_by_name($entity_type, $names = FALSE, $conditions = array()) {
  231. $entities = entity_load($entity_type, $names, $conditions);
  232. $info = entity_get_info($entity_type);
  233. if (!isset($info['entity keys']['name'])) {
  234. return $entities;
  235. }
  236. return entity_key_array_by_property($entities, $info['entity keys']['name']);
  237. }
  238. /**
  239. * Permanently save an entity.
  240. *
  241. * In case of failures, an exception is thrown.
  242. *
  243. * @param $entity_type
  244. * The type of the entity.
  245. * @param $entity
  246. * The entity to save.
  247. *
  248. * @return
  249. * For entity types provided by the CRUD API, SAVED_NEW or SAVED_UPDATED is
  250. * returned depending on the operation performed. If there is no information
  251. * how to save the entity, FALSE is returned.
  252. *
  253. * @see entity_type_supports()
  254. */
  255. function entity_save($entity_type, $entity) {
  256. $info = entity_get_info($entity_type);
  257. if (method_exists($entity, 'save')) {
  258. return $entity->save();
  259. }
  260. elseif (isset($info['save callback'])) {
  261. $info['save callback']($entity);
  262. }
  263. elseif (in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
  264. return entity_get_controller($entity_type)->save($entity);
  265. }
  266. else {
  267. return FALSE;
  268. }
  269. }
  270. /**
  271. * Permanently delete the given entity.
  272. *
  273. * In case of failures, an exception is thrown.
  274. *
  275. * @param $entity_type
  276. * The type of the entity.
  277. * @param $id
  278. * The uniform identifier of the entity to delete.
  279. *
  280. * @return
  281. * FALSE, if there were no information how to delete the entity.
  282. *
  283. * @see entity_type_supports()
  284. */
  285. function entity_delete($entity_type, $id) {
  286. return entity_delete_multiple($entity_type, array($id));
  287. }
  288. /**
  289. * Permanently delete multiple entities.
  290. *
  291. * @param $entity_type
  292. * The type of the entity.
  293. * @param $ids
  294. * An array of entity ids of the entities to delete. In case the entity makes
  295. * use of a name key, both the names or numeric ids may be passed.
  296. * @return
  297. * FALSE if the given entity type isn't compatible to the CRUD API.
  298. */
  299. function entity_delete_multiple($entity_type, $ids) {
  300. $info = entity_get_info($entity_type);
  301. if (isset($info['deletion callback'])) {
  302. foreach ($ids as $id) {
  303. $info['deletion callback']($id);
  304. }
  305. }
  306. elseif (in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
  307. entity_get_controller($entity_type)->delete($ids);
  308. }
  309. else {
  310. return FALSE;
  311. }
  312. }
  313. /**
  314. * Loads an entity revision.
  315. *
  316. * @param $entity_type
  317. * The type of the entity.
  318. * @param $revision_id
  319. * The id of the revision to load.
  320. *
  321. * @return
  322. * The entity object, or FALSE if there is no entity with the given revision
  323. * id.
  324. */
  325. function entity_revision_load($entity_type, $revision_id) {
  326. $info = entity_get_info($entity_type);
  327. if (!empty($info['entity keys']['revision'])) {
  328. $entity_revisions = entity_load($entity_type, FALSE, array($info['entity keys']['revision'] => $revision_id));
  329. return reset($entity_revisions);
  330. }
  331. return FALSE;
  332. }
  333. /**
  334. * Deletes an entity revision.
  335. *
  336. * @param $entity_type
  337. * The type of the entity.
  338. * @param $revision_id
  339. * The revision ID to delete.
  340. *
  341. * @return
  342. * TRUE if the entity revision could be deleted, FALSE otherwise.
  343. */
  344. function entity_revision_delete($entity_type, $revision_id) {
  345. $info = entity_get_info($entity_type);
  346. if (isset($info['revision deletion callback'])) {
  347. return $info['revision deletion callback']($revision_id, $entity_type);
  348. }
  349. elseif (in_array('EntityAPIControllerRevisionableInterface', class_implements($info['controller class']))) {
  350. return entity_get_controller($entity_type)->deleteRevision($revision_id);
  351. }
  352. return FALSE;
  353. }
  354. /**
  355. * Checks whether the given entity is the default revision.
  356. *
  357. * Note that newly created entities will always be created in default revision,
  358. * thus TRUE is returned for not yet saved entities.
  359. *
  360. * @param $entity_type
  361. * The type of the entity.
  362. * @param $entity
  363. * The entity object to check.
  364. *
  365. * @return boolean
  366. * A boolean indicating whether the entity is in default revision is returned.
  367. * If the entity is not revisionable or is new, TRUE is returned.
  368. *
  369. * @see entity_revision_set_default()
  370. */
  371. function entity_revision_is_default($entity_type, $entity) {
  372. $info = entity_get_info($entity_type);
  373. if (empty($info['entity keys']['revision'])) {
  374. return TRUE;
  375. }
  376. // Newly created entities will always be created in default revision.
  377. if (!empty($entity->is_new) || empty($entity->{$info['entity keys']['id']})) {
  378. return TRUE;
  379. }
  380. if (in_array('EntityAPIControllerRevisionableInterface', class_implements($info['controller class']))) {
  381. $key = !empty($info['entity keys']['default revision']) ? $info['entity keys']['default revision'] : 'default_revision';
  382. return !empty($entity->$key);
  383. }
  384. else {
  385. // Else, just load the default entity and compare the ID. Usually, the
  386. // entity should be already statically cached anyway.
  387. $default = entity_load_single($entity_type, $entity->{$info['entity keys']['id']});
  388. return $default->{$info['entity keys']['revision']} == $entity->{$info['entity keys']['revision']};
  389. }
  390. }
  391. /**
  392. * Sets a given entity revision as default revision.
  393. *
  394. * Note that the default revision flag will only be supported by entity types
  395. * based upon the EntityAPIController, i.e. implementing the
  396. * EntityAPIControllerRevisionableInterface.
  397. *
  398. * @param $entity_type
  399. * The type of the entity.
  400. * @param $entity
  401. * The entity revision to update.
  402. *
  403. * @see entity_revision_is_default()
  404. */
  405. function entity_revision_set_default($entity_type, $entity) {
  406. $info = entity_get_info($entity_type);
  407. if (!empty($info['entity keys']['revision'])) {
  408. $key = !empty($info['entity keys']['default revision']) ? $info['entity keys']['default revision'] : 'default_revision';
  409. $entity->$key = TRUE;
  410. }
  411. }
  412. /**
  413. * Create a new entity object.
  414. *
  415. * @param $entity_type
  416. * The type of the entity.
  417. * @param $values
  418. * An array of values to set, keyed by property name. If the entity type has
  419. * bundles the bundle key has to be specified.
  420. * @return
  421. * A new instance of the entity type or FALSE if there is no information for
  422. * the given entity type.
  423. *
  424. * @see entity_type_supports()
  425. */
  426. function entity_create($entity_type, array $values) {
  427. $info = entity_get_info($entity_type);
  428. if (isset($info['creation callback'])) {
  429. return $info['creation callback']($values, $entity_type);
  430. }
  431. elseif (in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
  432. return entity_get_controller($entity_type)->create($values);
  433. }
  434. return FALSE;
  435. }
  436. /**
  437. * Exports an entity.
  438. *
  439. * Note: Currently, this only works for entity types provided with the entity
  440. * CRUD API.
  441. *
  442. * @param $entity_type
  443. * The type of the entity.
  444. * @param $entity
  445. * The entity to export.
  446. * @param $prefix
  447. * An optional prefix for each line.
  448. * @return
  449. * The exported entity as serialized string. The format is determined by the
  450. * respective entity controller, e.g. it is JSON for the EntityAPIController.
  451. * The output is suitable for entity_import().
  452. */
  453. function entity_export($entity_type, $entity, $prefix = '') {
  454. if (method_exists($entity, 'export')) {
  455. return $entity->export($prefix);
  456. }
  457. $info = entity_get_info($entity_type);
  458. if (in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
  459. return entity_get_controller($entity_type)->export($entity, $prefix);
  460. }
  461. }
  462. /**
  463. * Imports an entity.
  464. *
  465. * Note: Currently, this only works for entity types provided with the entity
  466. * CRUD API.
  467. *
  468. * @param $entity_type
  469. * The type of the entity.
  470. * @param string $export
  471. * The string containing the serialized entity as produced by
  472. * entity_export().
  473. * @return
  474. * The imported entity object not yet saved.
  475. */
  476. function entity_import($entity_type, $export) {
  477. $info = entity_get_info($entity_type);
  478. if (in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
  479. return entity_get_controller($entity_type)->import($export);
  480. }
  481. }
  482. /**
  483. * Checks whether an entity type is fieldable.
  484. *
  485. * @param $entity_type
  486. * The type of the entity.
  487. *
  488. * @return
  489. * TRUE if the entity type is fieldable, FALSE otherwise.
  490. */
  491. function entity_type_is_fieldable($entity_type) {
  492. $info = entity_get_info($entity_type);
  493. return !empty($info['fieldable']);
  494. }
  495. /**
  496. * Builds a structured array representing the entity's content.
  497. *
  498. * The content built for the entity will vary depending on the $view_mode
  499. * parameter.
  500. *
  501. * Note: Currently, this only works for entity types provided with the entity
  502. * CRUD API.
  503. *
  504. * @param $entity_type
  505. * The type of the entity.
  506. * @param $entity
  507. * An entity object.
  508. * @param $view_mode
  509. * A view mode as used by this entity type, e.g. 'full', 'teaser'...
  510. * @param $langcode
  511. * (optional) A language code to use for rendering. Defaults to the global
  512. * content language of the current request.
  513. * @return
  514. * The renderable array.
  515. */
  516. function entity_build_content($entity_type, $entity, $view_mode = 'full', $langcode = NULL) {
  517. $info = entity_get_info($entity_type);
  518. if (method_exists($entity, 'buildContent')) {
  519. return $entity->buildContent($view_mode, $langcode);
  520. }
  521. elseif (in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
  522. return entity_get_controller($entity_type)->buildContent($entity, $view_mode, $langcode);
  523. }
  524. }
  525. /**
  526. * Returns the entity identifier, i.e. the entities name or numeric id.
  527. *
  528. * Unlike entity_extract_ids() this function returns the name of the entity
  529. * instead of the numeric id, in case the entity type has specified a name key.
  530. *
  531. * @param $entity_type
  532. * The type of the entity.
  533. * @param $entity
  534. * An entity object.
  535. *
  536. * @see entity_extract_ids()
  537. */
  538. function entity_id($entity_type, $entity) {
  539. if (method_exists($entity, 'identifier')) {
  540. return $entity->identifier();
  541. }
  542. $info = entity_get_info($entity_type);
  543. $key = isset($info['entity keys']['name']) ? $info['entity keys']['name'] : $info['entity keys']['id'];
  544. return isset($entity->$key) ? $entity->$key : NULL;
  545. }
  546. /**
  547. * Generate an array for rendering the given entities.
  548. *
  549. * Entities being viewed, are generally expected to be fully-loaded entity
  550. * objects, thus have their name or id key set. However, it is possible to
  551. * view a single entity without any id, e.g. for generating a preview during
  552. * creation.
  553. *
  554. * @param $entity_type
  555. * The type of the entity.
  556. * @param $entities
  557. * An array of entities to render.
  558. * @param $view_mode
  559. * A view mode as used by this entity type, e.g. 'full', 'teaser'...
  560. * @param $langcode
  561. * (optional) A language code to use for rendering. Defaults to the global
  562. * content language of the current request.
  563. * @param $page
  564. * (optional) If set will control if the entity is rendered: if TRUE
  565. * the entity will be rendered without its title, so that it can be embeded
  566. * in another context. If FALSE the entity will be displayed with its title
  567. * in a mode suitable for lists.
  568. * If unset, the page mode will be enabled if the current path is the URI
  569. * of the entity, as returned by entity_uri().
  570. * This parameter is only supported for entities which controller is a
  571. * EntityAPIControllerInterface.
  572. * @return
  573. * The renderable array, keyed by the entity type and by entity identifiers,
  574. * for which the entity name is used if existing - see entity_id(). If there
  575. * is no information on how to view an entity, FALSE is returned.
  576. */
  577. function entity_view($entity_type, $entities, $view_mode = 'full', $langcode = NULL, $page = NULL) {
  578. $info = entity_get_info($entity_type);
  579. if (isset($info['view callback'])) {
  580. $entities = entity_key_array_by_property($entities, $info['entity keys']['id']);
  581. return $info['view callback']($entities, $view_mode, $langcode, $entity_type);
  582. }
  583. elseif (in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
  584. return entity_get_controller($entity_type)->view($entities, $view_mode, $langcode, $page);
  585. }
  586. return FALSE;
  587. }
  588. /**
  589. * Determines whether the given user can perform actions on an entity.
  590. *
  591. * For create operations, the pattern is to create an entity and then
  592. * check if the user has create access.
  593. *
  594. * @code
  595. * $node = entity_create('node', array('type' => 'page'));
  596. * $access = entity_access('create', 'node', $node, $account);
  597. * @endcode
  598. *
  599. * @param $op
  600. * The operation being performed. One of 'view', 'update', 'create' or
  601. * 'delete'.
  602. * @param $entity_type
  603. * The entity type of the entity to check for.
  604. * @param $entity
  605. * Optionally an entity to check access for. If no entity is given, it will be
  606. * determined whether access is allowed for all entities of the given type.
  607. * @param $account
  608. * The user to check for. Leave it to NULL to check for the global user.
  609. *
  610. * @return boolean
  611. * Whether access is allowed or not. If the entity type does not specify any
  612. * access information, NULL is returned.
  613. *
  614. * @see entity_type_supports()
  615. */
  616. function entity_access($op, $entity_type, $entity = NULL, $account = NULL) {
  617. if (($info = entity_get_info()) && isset($info[$entity_type]['access callback'])) {
  618. return $info[$entity_type]['access callback']($op, $entity, $account, $entity_type);
  619. }
  620. }
  621. /**
  622. * Gets the edit form for any entity.
  623. *
  624. * This helper makes use of drupal_get_form() and the regular form builder
  625. * function of the entity type to retrieve and process the form as usual.
  626. *
  627. * In order to use this helper to show an entity add form, the new entity object
  628. * can be created via entity_create() or entity_property_values_create_entity().
  629. *
  630. * @param $entity_type
  631. * The type of the entity.
  632. * @param $entity
  633. * The entity to show the edit form for.
  634. * @return
  635. * The renderable array of the form. If there is no entity form or missing
  636. * metadata, FALSE is returned.
  637. *
  638. * @see entity_type_supports()
  639. */
  640. function entity_form($entity_type, $entity) {
  641. $info = entity_get_info($entity_type);
  642. if (isset($info['form callback'])) {
  643. return $info['form callback']($entity, $entity_type);
  644. }
  645. // If there is an UI controller, the providing module has to implement the
  646. // entity form using entity_ui_get_form().
  647. elseif (entity_ui_controller($entity_type)) {
  648. return entity_metadata_form_entity_ui($entity, $entity_type);
  649. }
  650. return FALSE;
  651. }
  652. /**
  653. * Converts an array of entities to be keyed by the values of a given property.
  654. *
  655. * @param array $entities
  656. * The array of entities to convert.
  657. * @param $property
  658. * The name of entity property, by which the array should be keyed. To get
  659. * reasonable results, the property has to have unique values.
  660. *
  661. * @return array
  662. * The same entities in the same order, but keyed by their $property values.
  663. */
  664. function entity_key_array_by_property(array $entities, $property) {
  665. $ret = array();
  666. foreach ($entities as $entity) {
  667. $key = isset($entity->$property) ? $entity->$property : NULL;
  668. $ret[$key] = $entity;
  669. }
  670. return $ret;
  671. }
  672. /**
  673. * Get the entity info for the entity types provided via the entity CRUD API.
  674. *
  675. * @return
  676. * An array in the same format as entity_get_info(), containing the entities
  677. * whose controller class implements the EntityAPIControllerInterface.
  678. */
  679. function entity_crud_get_info() {
  680. $types = array();
  681. foreach (entity_get_info() as $type => $info) {
  682. if (isset($info['controller class']) && in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
  683. $types[$type] = $info;
  684. }
  685. }
  686. return $types;
  687. }
  688. /**
  689. * Checks if a given entity has a certain exportable status.
  690. *
  691. * @param $entity_type
  692. * The type of the entity.
  693. * @param $entity
  694. * The entity to check the status on.
  695. * @param $status
  696. * The constant status like ENTITY_CUSTOM, ENTITY_IN_CODE, ENTITY_OVERRIDDEN
  697. * or ENTITY_FIXED.
  698. *
  699. * @return
  700. * TRUE if the entity has the status, FALSE otherwise.
  701. */
  702. function entity_has_status($entity_type, $entity, $status) {
  703. $info = entity_get_info($entity_type);
  704. $status_key = empty($info['entity keys']['status']) ? 'status' : $info['entity keys']['status'];
  705. return isset($entity->{$status_key}) && ($entity->{$status_key} & $status) == $status;
  706. }
  707. /**
  708. * Export a variable. Copied from ctools.
  709. *
  710. * This is a replacement for var_export(), allowing us to more nicely
  711. * format exports. It will recurse down into arrays and will try to
  712. * properly export bools when it can.
  713. */
  714. function entity_var_export($var, $prefix = '') {
  715. if (is_array($var)) {
  716. if (empty($var)) {
  717. $output = 'array()';
  718. }
  719. else {
  720. $output = "array(\n";
  721. foreach ($var as $key => $value) {
  722. $output .= " '$key' => " . entity_var_export($value, ' ') . ",\n";
  723. }
  724. $output .= ')';
  725. }
  726. }
  727. elseif (is_bool($var)) {
  728. $output = $var ? 'TRUE' : 'FALSE';
  729. }
  730. else {
  731. $output = var_export($var, TRUE);
  732. }
  733. if ($prefix) {
  734. $output = str_replace("\n", "\n$prefix", $output);
  735. }
  736. return $output;
  737. }
  738. /**
  739. * Export a variable in pretty formatted JSON.
  740. */
  741. function entity_var_json_export($var, $prefix = '') {
  742. if (is_array($var) && $var) {
  743. // Defines whether we use a JSON array or object.
  744. $use_array = ($var == array_values($var));
  745. $output = $use_array ? "[" : "{";
  746. foreach ($var as $key => $value) {
  747. if ($use_array) {
  748. $values[] = entity_var_json_export($value, ' ');
  749. }
  750. else {
  751. $values[] = entity_var_json_export((string) $key, ' ') . ' : ' . entity_var_json_export($value, ' ');
  752. }
  753. }
  754. // Use several lines for long content. However for objects with a single
  755. // entry keep the key in the first line.
  756. if (strlen($content = implode(', ', $values)) > 70 && ($use_array || count($values) > 1)) {
  757. $output .= "\n " . implode(",\n ", $values) . "\n";
  758. }
  759. elseif (strpos($content, "\n") !== FALSE) {
  760. $output .= " " . $content . "\n";
  761. }
  762. else {
  763. $output .= " " . $content . ' ';
  764. }
  765. $output .= $use_array ? ']' : '}';
  766. }
  767. else {
  768. $output = drupal_json_encode($var);
  769. }
  770. if ($prefix) {
  771. $output = str_replace("\n", "\n$prefix", $output);
  772. }
  773. return $output;
  774. }
  775. /**
  776. * Rebuild the default entities provided in code.
  777. *
  778. * Exportable entities provided in code get saved to the database once a module
  779. * providing defaults in code is activated. This allows module and entity_load()
  780. * to easily deal with exportable entities just by relying on the database.
  781. *
  782. * The defaults get rebuilt if the cache is cleared or new modules providing
  783. * defaults are enabled, such that the defaults in the database are up to date.
  784. * A default entity gets updated with the latest defaults in code during rebuild
  785. * as long as the default has not been overridden. Once a module providing
  786. * defaults is disabled, its default entities get removed from the database
  787. * unless they have been overridden. In that case the overridden entity is left
  788. * in the database, but its status gets updated to 'custom'.
  789. *
  790. * @param $entity_types
  791. * (optional) If specified, only the defaults of the given entity types are
  792. * rebuilt.
  793. */
  794. function entity_defaults_rebuild($entity_types = NULL) {
  795. if (!isset($entity_types)) {
  796. $entity_types = array();
  797. foreach (entity_crud_get_info() as $type => $info) {
  798. if (!empty($info['exportable'])) {
  799. $entity_types[] = $type;
  800. }
  801. };
  802. }
  803. foreach ($entity_types as $type) {
  804. _entity_defaults_rebuild($type);
  805. }
  806. }
  807. /**
  808. * Actually rebuild the defaults of a given entity type.
  809. */
  810. function _entity_defaults_rebuild($entity_type) {
  811. if (lock_acquire('entity_rebuild_' . $entity_type)) {
  812. $info = entity_get_info($entity_type);
  813. $hook = isset($info['export']['default hook']) ? $info['export']['default hook'] : 'default_' . $entity_type;
  814. $keys = $info['entity keys'] + array('module' => 'module', 'status' => 'status', 'name' => $info['entity keys']['id']);
  815. // Check for the existence of the module and status columns.
  816. if (!in_array($keys['status'], $info['schema_fields_sql']['base table']) || !in_array($keys['module'], $info['schema_fields_sql']['base table'])) {
  817. trigger_error("Missing database columns for the exportable entity $entity_type as defined by entity_exportable_schema_fields(). Update the according module and run update.php!", E_USER_WARNING);
  818. return;
  819. }
  820. // Invoke the hook and collect default entities.
  821. $entities = array();
  822. foreach (module_implements($hook) as $module) {
  823. foreach ((array) module_invoke($module, $hook) as $name => $entity) {
  824. $entity->{$keys['name']} = $name;
  825. $entity->{$keys['module']} = $module;
  826. $entities[$name] = $entity;
  827. }
  828. }
  829. drupal_alter($hook, $entities);
  830. // Check for defaults that disappeared.
  831. $existing_defaults = entity_load_multiple_by_name($entity_type, FALSE, array($keys['status'] => array(ENTITY_OVERRIDDEN, ENTITY_IN_CODE, ENTITY_FIXED)));
  832. foreach ($existing_defaults as $name => $entity) {
  833. if (empty($entities[$name])) {
  834. $entity->is_rebuild = TRUE;
  835. if (entity_has_status($entity_type, $entity, ENTITY_OVERRIDDEN)) {
  836. $entity->{$keys['status']} = ENTITY_CUSTOM;
  837. entity_save($entity_type, $entity);
  838. }
  839. else {
  840. entity_delete($entity_type, $name);
  841. }
  842. unset($entity->is_rebuild);
  843. }
  844. }
  845. // Load all existing entities.
  846. $existing_entities = entity_load_multiple_by_name($entity_type, array_keys($entities));
  847. foreach ($existing_entities as $name => $entity) {
  848. if (entity_has_status($entity_type, $entity, ENTITY_CUSTOM)) {
  849. // If the entity already exists but is not yet marked as overridden, we
  850. // have to update the status.
  851. if (!entity_has_status($entity_type, $entity, ENTITY_OVERRIDDEN)) {
  852. $entity->{$keys['status']} |= ENTITY_OVERRIDDEN;
  853. $entity->{$keys['module']} = $entities[$name]->{$keys['module']};
  854. $entity->is_rebuild = TRUE;
  855. entity_save($entity_type, $entity);
  856. unset($entity->is_rebuild);
  857. }
  858. // The entity is overridden, so we do not need to save the default.
  859. unset($entities[$name]);
  860. }
  861. }
  862. // Save defaults.
  863. $originals = array();
  864. foreach ($entities as $name => $entity) {
  865. if (!empty($existing_entities[$name])) {
  866. // Make sure we are updating the existing default.
  867. $entity->{$keys['id']} = $existing_entities[$name]->{$keys['id']};
  868. unset($entity->is_new);
  869. }
  870. // Pre-populate $entity->original as we already have it. So we avoid
  871. // loading it again.
  872. $entity->original = !empty($existing_entities[$name]) ? $existing_entities[$name] : FALSE;
  873. // Keep original entities for hook_{entity_type}_defaults_rebuild()
  874. // implementations.
  875. $originals[$name] = $entity->original;
  876. if (!isset($entity->{$keys['status']})) {
  877. $entity->{$keys['status']} = ENTITY_IN_CODE;
  878. }
  879. else {
  880. $entity->{$keys['status']} |= ENTITY_IN_CODE;
  881. }
  882. $entity->is_rebuild = TRUE;
  883. entity_save($entity_type, $entity);
  884. unset($entity->is_rebuild);
  885. }
  886. // Invoke an entity type-specific hook so modules may apply changes, e.g.
  887. // efficiently rebuild caches.
  888. module_invoke_all($entity_type . '_defaults_rebuild', $entities, $originals);
  889. lock_release('entity_rebuild_' . $entity_type);
  890. }
  891. }
  892. /**
  893. * Implements hook_modules_installed().
  894. */
  895. function entity_modules_installed($modules) {
  896. module_load_install('entity');
  897. entity_entitycache_installed_modules($modules);
  898. }
  899. /**
  900. * Implements hook_modules_uninstalled().
  901. */
  902. function entity_modules_uninstalled($modules) {
  903. module_load_install('entity');
  904. entity_entitycache_uninstalled_modules($modules);
  905. }
  906. /**
  907. * Implements hook_modules_enabled().
  908. */
  909. function entity_modules_enabled($modules) {
  910. foreach (_entity_modules_get_default_types($modules) as $type) {
  911. _entity_defaults_rebuild($type);
  912. }
  913. }
  914. /**
  915. * Implements hook_modules_disabled().
  916. */
  917. function entity_modules_disabled($modules) {
  918. foreach (_entity_modules_get_default_types($modules) as $entity_type) {
  919. $info = entity_get_info($entity_type);
  920. // Do nothing if the module providing the entity type has been disabled too.
  921. if (isset($info['module']) && in_array($info['module'], $modules)) {
  922. return;
  923. }
  924. $keys = $info['entity keys'] + array('module' => 'module', 'status' => 'status', 'name' => $info['entity keys']['id']);
  925. // Remove entities provided in code by one of the disabled modules.
  926. $query = new EntityFieldQuery();
  927. $query->entityCondition('entity_type', $entity_type, '=')
  928. ->propertyCondition($keys['module'], $modules, 'IN')
  929. ->propertyCondition($keys['status'], array(ENTITY_IN_CODE, ENTITY_FIXED), 'IN');
  930. $result = $query->execute();
  931. if (isset($result[$entity_type])) {
  932. $entities = entity_load($entity_type, array_keys($result[$entity_type]));
  933. entity_delete_multiple($entity_type, array_keys($entities));
  934. }
  935. // Update overridden entities to be now custom.
  936. $query = new EntityFieldQuery();
  937. $query->entityCondition('entity_type', $entity_type, '=')
  938. ->propertyCondition($keys['module'], $modules, 'IN')
  939. ->propertyCondition($keys['status'], ENTITY_OVERRIDDEN, '=');
  940. $result = $query->execute();
  941. if (isset($result[$entity_type])) {
  942. foreach (entity_load($entity_type, array_keys($result[$entity_type])) as $name => $entity) {
  943. $entity->{$keys['status']} = ENTITY_CUSTOM;
  944. $entity->{$keys['module']} = NULL;
  945. entity_save($entity_type, $entity);
  946. }
  947. }
  948. // Rebuild the remaining defaults so any alterations of the disabled modules
  949. // are gone.
  950. _entity_defaults_rebuild($entity_type);
  951. }
  952. }
  953. /**
  954. * Gets all entity types for which defaults are provided by the $modules.
  955. */
  956. function _entity_modules_get_default_types($modules) {
  957. $types = array();
  958. foreach (entity_crud_get_info() as $entity_type => $info) {
  959. if (!empty($info['exportable'])) {
  960. $hook = isset($info['export']['default hook']) ? $info['export']['default hook'] : 'default_' . $entity_type;
  961. foreach ($modules as $module) {
  962. if (module_hook($module, $hook) || module_hook($module, $hook . '_alter')) {
  963. $types[] = $entity_type;
  964. }
  965. }
  966. }
  967. }
  968. return $types;
  969. }
  970. /**
  971. * Defines schema fields required for exportable entities.
  972. *
  973. * Warning: Do not call this function in your module's hook_schema()
  974. * implementation or update functions. It is not safe to call functions of
  975. * dependencies at this point. Instead of calling the function, just copy over
  976. * the content.
  977. * For more details see the issue http://drupal.org/node/1122812.
  978. */
  979. function entity_exportable_schema_fields($module_col = 'module', $status_col = 'status') {
  980. return array(
  981. $status_col => array(
  982. 'type' => 'int',
  983. 'not null' => TRUE,
  984. // Set the default to ENTITY_CUSTOM without using the constant as it is
  985. // not safe to use it at this point.
  986. 'default' => 0x01,
  987. 'size' => 'tiny',
  988. 'description' => 'The exportable status of the entity.',
  989. ),
  990. $module_col => array(
  991. 'description' => 'The name of the providing module if the entity has been defined in code.',
  992. 'type' => 'varchar',
  993. 'length' => 255,
  994. 'not null' => FALSE,
  995. ),
  996. );
  997. }
  998. /**
  999. * Implements hook_flush_caches().
  1000. */
  1001. function entity_flush_caches() {
  1002. entity_property_info_cache_clear();
  1003. // Re-build defaults in code, however skip it on the admin modules page. In
  1004. // case of enabling or disabling modules we already rebuild defaults in
  1005. // entity_modules_enabled() and entity_modules_disabled(), so we do not need
  1006. // to do it again.
  1007. if (current_path() != 'admin/modules/list/confirm') {
  1008. entity_defaults_rebuild();
  1009. }
  1010. // Care about entitycache tables.
  1011. if (module_exists('entitycache')) {
  1012. $tables = array();
  1013. foreach (entity_crud_get_info() as $entity_type => $entity_info) {
  1014. if (isset($entity_info['module']) && !empty($entity_info['entity cache'])) {
  1015. $tables[] = 'cache_entity_' . $entity_type;
  1016. }
  1017. }
  1018. return $tables;
  1019. }
  1020. }
  1021. /**
  1022. * Implements hook_theme().
  1023. */
  1024. function entity_theme() {
  1025. // Build a pattern in the form of "(type1|type2|...)(\.|__)" such that all
  1026. // templates starting with an entity type or named like the entity type
  1027. // are found.
  1028. // This has to match the template suggestions provided in
  1029. // template_preprocess_entity().
  1030. $types = array_keys(entity_crud_get_info());
  1031. $pattern = '(' . implode('|', $types) . ')(\.|__)';
  1032. return array(
  1033. 'entity_status' => array(
  1034. 'variables' => array('status' => NULL, 'html' => TRUE),
  1035. 'file' => 'theme/entity.theme.inc',
  1036. ),
  1037. 'entity' => array(
  1038. 'render element' => 'elements',
  1039. 'template' => 'entity',
  1040. 'pattern' => $pattern,
  1041. 'path' => drupal_get_path('module', 'entity') . '/theme',
  1042. 'file' => 'entity.theme.inc',
  1043. ),
  1044. 'entity_property' => array(
  1045. 'render element' => 'elements',
  1046. 'file' => 'theme/entity.theme.inc',
  1047. ),
  1048. 'entity_ui_overview_item' => array(
  1049. 'variables' => array('label' => NULL, 'entity_type' => NULL, 'url' => FALSE, 'name' => FALSE),
  1050. 'file' => 'includes/entity.ui.inc'
  1051. ),
  1052. );
  1053. }
  1054. /**
  1055. * Label callback that refers to the entity classes label method.
  1056. */
  1057. function entity_class_label($entity) {
  1058. return $entity->label();
  1059. }
  1060. /**
  1061. * URI callback that refers to the entity classes uri method.
  1062. */
  1063. function entity_class_uri($entity) {
  1064. return $entity->uri();
  1065. }
  1066. /**
  1067. * Implements hook_file_download_access() for entity types provided by the CRUD API.
  1068. */
  1069. function entity_file_download_access($field, $entity_type, $entity) {
  1070. $info = entity_get_info($entity_type);
  1071. if (in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
  1072. return entity_access('view', $entity_type, $entity);
  1073. }
  1074. }
  1075. /**
  1076. * Determines the UI controller class for a given entity type.
  1077. *
  1078. * @return EntityDefaultUIController
  1079. * If a type is given, the controller for the given entity type. Else an array
  1080. * of all enabled UI controllers keyed by entity type is returned.
  1081. */
  1082. function entity_ui_controller($type = NULL) {
  1083. $static = &drupal_static(__FUNCTION__);
  1084. if (!isset($type)) {
  1085. // Invoke the function for each type to ensure we have fully populated the
  1086. // static variable.
  1087. foreach (entity_get_info() as $entity_type => $info) {
  1088. entity_ui_controller($entity_type);
  1089. }
  1090. return array_filter($static);
  1091. }
  1092. if (!isset($static[$type])) {
  1093. $info = entity_get_info($type);
  1094. $class = isset($info['admin ui']['controller class']) ? $info['admin ui']['controller class'] : 'EntityDefaultUIController';
  1095. $static[$type] = (isset($info['admin ui']['path']) && $class) ? new $class($type, $info) : FALSE;
  1096. }
  1097. return $static[$type];
  1098. }
  1099. /**
  1100. * Implements hook_menu().
  1101. *
  1102. * @see EntityDefaultUIController::hook_menu()
  1103. */
  1104. function entity_menu() {
  1105. $items = array();
  1106. foreach (entity_ui_controller() as $controller) {
  1107. $items += $controller->hook_menu();
  1108. }
  1109. return $items;
  1110. }
  1111. /**
  1112. * Implements hook_forms().
  1113. *
  1114. * @see EntityDefaultUIController::hook_forms()
  1115. * @see entity_ui_get_form()
  1116. */
  1117. function entity_forms($form_id, $args) {
  1118. // For efficiency only invoke an entity types controller, if a form of it is
  1119. // requested. Thus if the first (overview and operation form) or the third
  1120. // argument (edit form) is an entity type name, add in the types forms.
  1121. if (isset($args[0]) && is_string($args[0]) && entity_get_info($args[0])) {
  1122. $type = $args[0];
  1123. }
  1124. elseif (isset($args[2]) && is_string($args[2]) && entity_get_info($args[2])) {
  1125. $type = $args[2];
  1126. }
  1127. if (isset($type) && $controller = entity_ui_controller($type)) {
  1128. return $controller->hook_forms();
  1129. }
  1130. }
  1131. /**
  1132. * A wrapper around drupal_get_form() that helps building entity forms.
  1133. *
  1134. * This function may be used by entities to build their entity form. It has to
  1135. * be used instead of calling drupal_get_form().
  1136. * Entity forms built with this helper receive useful defaults suiting for
  1137. * editing a single entity, whereas the special cases of adding and cloning
  1138. * of entities are supported too.
  1139. *
  1140. * While this function is intended to be used to get entity forms for entities
  1141. * using the entity ui controller, it may be used for entity types not using
  1142. * the ui controller too.
  1143. *
  1144. * @param $entity_type
  1145. * The entity type for which to get the form.
  1146. * @param $entity
  1147. * The entity for which to return the form.
  1148. * If $op is 'add' the entity has to be either initialized before calling this
  1149. * function, or NULL may be passed. If NULL is passed, an entity will be
  1150. * initialized with empty values using entity_create(). Thus entities, for
  1151. * which this is problematic have to care to pass in an initialized entity.
  1152. * @param $op
  1153. * (optional) One of 'edit', 'add' or 'clone'. Defaults to edit.
  1154. * @param $form_state
  1155. * (optional) A pre-populated form state, e.g. to add in form include files.
  1156. * See entity_metadata_form_entity_ui().
  1157. *
  1158. * @return
  1159. * The fully built and processed form, ready to be rendered.
  1160. *
  1161. * @see EntityDefaultUIController::hook_forms()
  1162. * @see entity_ui_form_submit_build_entity()
  1163. */
  1164. function entity_ui_get_form($entity_type, $entity, $op = 'edit', $form_state = array()) {
  1165. if (isset($entity)) {
  1166. list(, , $bundle) = entity_extract_ids($entity_type, $entity);
  1167. }
  1168. $form_id = (!isset($bundle) || $bundle == $entity_type) ? $entity_type . '_form' : $entity_type . '_edit_' . $bundle . '_form';
  1169. if (!isset($entity) && $op == 'add') {
  1170. $entity = entity_create($entity_type, array());
  1171. }
  1172. // Do not use drupal_get_form(), but invoke drupal_build_form() ourself so
  1173. // we can prepulate the form state.
  1174. $form_state['wrapper_callback'] = 'entity_ui_main_form_defaults';
  1175. $form_state['entity_type'] = $entity_type;
  1176. form_load_include($form_state, 'inc', 'entity', 'includes/entity.ui');
  1177. // Handle cloning. We cannot do that in the wrapper callback as it is too late
  1178. // for changing arguments.
  1179. if ($op == 'clone') {
  1180. $entity = entity_ui_clone_entity($entity_type, $entity);
  1181. }
  1182. // We don't pass the entity type as first parameter, as the implementing
  1183. // module knows the type anyway. However, in order to allow for efficient
  1184. // hook_forms() implementiations we append the entity type as last argument,
  1185. // which the module implementing the form constructor may safely ignore.
  1186. // @see entity_forms()
  1187. $form_state['build_info']['args'] = array($entity, $op, $entity_type);
  1188. return drupal_build_form($form_id, $form_state);
  1189. }
  1190. /**
  1191. * Gets the page/menu title for local action operations.
  1192. *
  1193. * @param $op
  1194. * The current operation. One of 'add' or 'import'.
  1195. * @param $entity_type
  1196. * The entity type.
  1197. * @param $bundle_name
  1198. * (Optional) The name of the bundle. May be NULL if the bundle name is not
  1199. * relevant to the current page. If the entity type has only one bundle, or no
  1200. * bundles, this will be the same as the entity type.
  1201. */
  1202. function entity_ui_get_action_title($op, $entity_type, $bundle_name = NULL) {
  1203. $info = entity_get_info($entity_type);
  1204. switch ($op) {
  1205. case 'add':
  1206. if (isset($bundle_name) && $bundle_name != $entity_type) {
  1207. return t('Add @bundle_name @entity_type', array(
  1208. '@bundle_name' => drupal_strtolower($info['bundles'][$bundle_name]['label']),
  1209. '@entity_type' => drupal_strtolower($info['label']),
  1210. ));
  1211. }
  1212. else {
  1213. return t('Add @entity_type', array('@entity_type' => drupal_strtolower($info['label'])));
  1214. }
  1215. case 'import':
  1216. return t('Import @entity_type', array('@entity_type' => drupal_strtolower($info['label'])));
  1217. }
  1218. }
  1219. /**
  1220. * Helper for using i18n_string().
  1221. *
  1222. * @param $name
  1223. * Textgroup and context glued with ':'.
  1224. * @param $default
  1225. * String in default language. Default language may or may not be English.
  1226. * @param $langcode
  1227. * (optional) The code of a certain language to translate the string into.
  1228. * Defaults to the i18n_string() default, i.e. the current language.
  1229. *
  1230. * @see i18n_string()
  1231. */
  1232. function entity_i18n_string($name, $default, $langcode = NULL) {
  1233. return function_exists('i18n_string') ? i18n_string($name, $default, array('langcode' => $langcode)) : $default;
  1234. }
  1235. /**
  1236. * Implements hook_views_api().
  1237. */
  1238. function entity_views_api() {
  1239. return array(
  1240. 'api' => '3.0-alpha1',
  1241. 'path' => drupal_get_path('module', 'entity') . '/views',
  1242. );
  1243. }
  1244. /**
  1245. * Implements hook_field_extra_fields().
  1246. */
  1247. function entity_field_extra_fields() {
  1248. // Invoke specified controllers for entity types provided by the CRUD API.
  1249. $items = array();
  1250. foreach (entity_crud_get_info() as $type => $info) {
  1251. if (!empty($info['extra fields controller class'])) {
  1252. $items = array_merge_recursive($items, entity_get_extra_fields_controller($type)->fieldExtraFields());
  1253. }
  1254. }
  1255. return $items;
  1256. }
  1257. /**
  1258. * Gets the extra field controller class for a given entity type.
  1259. *
  1260. * @return EntityExtraFieldsControllerInterface|false
  1261. * The controller for the given entity type or FALSE if none is specified.
  1262. */
  1263. function entity_get_extra_fields_controller($type = NULL) {
  1264. $static = &drupal_static(__FUNCTION__);
  1265. if (!isset($static[$type])) {
  1266. $static[$type] = FALSE;
  1267. $info = entity_get_info($type);
  1268. if (!empty($info['extra fields controller class'])) {
  1269. $static[$type] = new $info['extra fields controller class']($type);
  1270. }
  1271. }
  1272. return $static[$type];
  1273. }
  1274. /**
  1275. * Returns a property wrapper for the given data.
  1276. *
  1277. * If an entity is wrapped, the wrapper can be used to retrieve further wrappers
  1278. * for the entitity properties. For that the wrapper support chaining, e.g. you
  1279. * can use a node wrapper to get the node authors mail address:
  1280. *
  1281. * @code
  1282. * echo $wrappedNode->author->mail->value();
  1283. * @endcode
  1284. *
  1285. * @param $type
  1286. * The type of the passed data.
  1287. * @param $data
  1288. * The data to wrap. It may be set to NULL, so the wrapper can be used
  1289. * without any data for getting information about properties.
  1290. * @param $info
  1291. * (optional) Specify additional information for the passed data:
  1292. * - langcode: (optional) If the data is language specific, its langauge
  1293. * code. Defaults to NULL, what means language neutral.
  1294. * - bundle: (optional) If an entity is wrapped but not passed, use this key
  1295. * to specify the bundle to return a wrapper for.
  1296. * - property info: (optional) May be used to use a wrapper with an arbitrary
  1297. * data structure (type 'struct'). Use this key for specifying info about
  1298. * properties in the same structure as used by hook_entity_property_info().
  1299. * - property info alter: (optional) A callback for altering the property
  1300. * info before it is utilized by the wrapper.
  1301. * - property defaults: (optional) An array of defaults for the info of
  1302. * each property of the wrapped data item.
  1303. * @return EntityMetadataWrapper
  1304. * Dependend on the passed data the right wrapper is returned.
  1305. */
  1306. function entity_metadata_wrapper($type, $data = NULL, array $info = array()) {
  1307. if ($type == 'entity' || (($entity_info = entity_get_info()) && isset($entity_info[$type]))) {
  1308. // If the passed entity is the global $user, we load the user object by only
  1309. // passing on the user id. The global user is not a fully loaded entity.
  1310. if ($type == 'user' && is_object($data) && $data == $GLOBALS['user']) {
  1311. $data = $data->uid;
  1312. }
  1313. return new EntityDrupalWrapper($type, $data, $info);
  1314. }
  1315. elseif ($type == 'list' || entity_property_list_extract_type($type)) {
  1316. return new EntityListWrapper($type, $data, $info);
  1317. }
  1318. elseif (isset($info['property info'])) {
  1319. return new EntityStructureWrapper($type, $data, $info);
  1320. }
  1321. else {
  1322. return new EntityValueWrapper($type, $data, $info);
  1323. }
  1324. }
  1325. /**
  1326. * Returns a metadata wrapper for accessing site-wide properties.
  1327. *
  1328. * Although there is no 'site' entity or such, modules may provide info about
  1329. * site-wide properties using hook_entity_property_info(). This function returns
  1330. * a wrapper for making use of this properties.
  1331. *
  1332. * @return EntityMetadataWrapper
  1333. * A wrapper for accessing site-wide properties.
  1334. *
  1335. * @see entity_metadata_system_entity_property_info()
  1336. */
  1337. function entity_metadata_site_wrapper() {
  1338. $site_info = entity_get_property_info('site');
  1339. $info['property info'] = $site_info['properties'];
  1340. return entity_metadata_wrapper('site', FALSE, $info);
  1341. }
  1342. /**
  1343. * Implements hook_module_implements_alter().
  1344. *
  1345. * Moves the hook_entity_info_alter() implementation to the bottom so it is
  1346. * invoked after all modules relying on the entity API.
  1347. * That way we ensure to run last and clear the field-info cache after the
  1348. * others added in their bundle information.
  1349. *
  1350. * @see entity_entity_info_alter()
  1351. */
  1352. function entity_module_implements_alter(&$implementations, $hook) {
  1353. if ($hook == 'entity_info_alter') {
  1354. // Move our hook implementation to the bottom.
  1355. $group = $implementations['entity'];
  1356. unset($implementations['entity']);
  1357. $implementations['entity'] = $group;
  1358. }
  1359. }
  1360. /**
  1361. * Implements hook_entity_info_alter().
  1362. *
  1363. * @see entity_module_implements_alter()
  1364. */
  1365. function entity_entity_info_alter(&$entity_info) {
  1366. _entity_info_add_metadata($entity_info);
  1367. // Populate a default value for the 'configuration' key of all entity types.
  1368. foreach ($entity_info as $type => $info) {
  1369. if (!isset($info['configuration'])) {
  1370. $entity_info[$type]['configuration'] = !empty($info['exportable']);
  1371. }
  1372. if (isset($info['controller class']) && in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
  1373. // Automatically disable field cache when entity cache is used.
  1374. if (!empty($info['entity cache']) && module_exists('entitycache')) {
  1375. $entity_info[$type]['field cache'] = FALSE;
  1376. }
  1377. }
  1378. }
  1379. }
  1380. /**
  1381. * Adds metadata and callbacks for core entities to the entity info.
  1382. */
  1383. function _entity_info_add_metadata(&$entity_info) {
  1384. // Set plural labels.
  1385. $entity_info['node']['plural label'] = t('Nodes');
  1386. $entity_info['user']['plural label'] = t('Users');
  1387. $entity_info['file']['plural label'] = t('Files');
  1388. // Set descriptions.
  1389. $entity_info['node']['description'] = t('Nodes represent the main site content items.');
  1390. $entity_info['user']['description'] = t('Users who have created accounts on your site.');
  1391. $entity_info['file']['description'] = t('Uploaded file.');
  1392. // Set access callbacks.
  1393. $entity_info['node']['access callback'] = 'entity_metadata_no_hook_node_access';
  1394. $entity_info['user']['access callback'] = 'entity_metadata_user_access';
  1395. // File entity has it's own entity_access function.
  1396. if (!module_exists('file_entity')) {
  1397. $entity_info['file']['access callback'] = 'entity_metadata_file_access';
  1398. }
  1399. // CRUD function callbacks.
  1400. $entity_info['node']['creation callback'] = 'entity_metadata_create_node';
  1401. $entity_info['node']['save callback'] = 'node_save';
  1402. $entity_info['node']['deletion callback'] = 'node_delete';
  1403. $entity_info['node']['revision deletion callback'] = 'node_revision_delete';
  1404. $entity_info['user']['creation callback'] = 'entity_metadata_create_object';
  1405. $entity_info['user']['save callback'] = 'entity_metadata_user_save';
  1406. $entity_info['user']['deletion callback'] = 'user_delete';
  1407. $entity_info['file']['save callback'] = 'file_save';
  1408. $entity_info['file']['deletion callback'] = 'entity_metadata_delete_file';
  1409. // Form callbacks.
  1410. $entity_info['node']['form callback'] = 'entity_metadata_form_node';
  1411. $entity_info['user']['form callback'] = 'entity_metadata_form_user';
  1412. // URI callbacks.
  1413. if (!isset($entity_info['file']['uri callback'])) {
  1414. $entity_info['file']['uri callback'] = 'entity_metadata_uri_file';
  1415. }
  1416. // View callbacks.
  1417. $entity_info['node']['view callback'] = 'entity_metadata_view_node';
  1418. $entity_info['user']['view callback'] = 'entity_metadata_view_single';
  1419. if (module_exists('comment')) {
  1420. $entity_info['comment']['plural label'] = t('Comments');
  1421. $entity_info['comment']['description'] = t('Remark or note that refers to a node.');
  1422. $entity_info['comment']['access callback'] = 'entity_metadata_comment_access';
  1423. $entity_info['comment']['creation callback'] = 'entity_metadata_create_comment';
  1424. $entity_info['comment']['save callback'] = 'comment_save';
  1425. $entity_info['comment']['deletion callback'] = 'comment_delete';
  1426. $entity_info['comment']['view callback'] = 'entity_metadata_view_comment';
  1427. $entity_info['comment']['form callback'] = 'entity_metadata_form_comment';
  1428. }
  1429. if (module_exists('taxonomy')) {
  1430. $entity_info['taxonomy_term']['plural label'] = t('Taxonomy terms');
  1431. $entity_info['taxonomy_term']['description'] = t('Taxonomy terms are used for classifying content.');
  1432. $entity_info['taxonomy_term']['access callback'] = 'entity_metadata_taxonomy_access';
  1433. $entity_info['taxonomy_term']['creation callback'] = 'entity_metadata_create_object';
  1434. $entity_info['taxonomy_term']['save callback'] = 'taxonomy_term_save';
  1435. $entity_info['taxonomy_term']['deletion callback'] = 'taxonomy_term_delete';
  1436. $entity_info['taxonomy_term']['view callback'] = 'entity_metadata_view_single';
  1437. $entity_info['taxonomy_term']['form callback'] = 'entity_metadata_form_taxonomy_term';
  1438. $entity_info['taxonomy_vocabulary']['plural label'] = t('Taxonomy vocabularies');
  1439. $entity_info['taxonomy_vocabulary']['description'] = t('Vocabularies contain related taxonomy terms, which are used for classifying content.');
  1440. $entity_info['taxonomy_vocabulary']['access callback'] = 'entity_metadata_taxonomy_access';
  1441. $entity_info['taxonomy_vocabulary']['creation callback'] = 'entity_metadata_create_object';
  1442. $entity_info['taxonomy_vocabulary']['save callback'] = 'taxonomy_vocabulary_save';
  1443. $entity_info['taxonomy_vocabulary']['deletion callback'] = 'taxonomy_vocabulary_delete';
  1444. $entity_info['taxonomy_vocabulary']['form callback'] = 'entity_metadata_form_taxonomy_vocabulary';
  1445. // Token type mapping.
  1446. $entity_info['taxonomy_term']['token type'] = 'term';
  1447. $entity_info['taxonomy_vocabulary']['token type'] = 'vocabulary';
  1448. }
  1449. }
  1450. /**
  1451. * Implements hook_ctools_plugin_directory().
  1452. */
  1453. function entity_ctools_plugin_directory($module, $plugin) {
  1454. if ($module == 'ctools' && $plugin == 'content_types') {
  1455. return 'ctools/content_types';
  1456. }
  1457. }