entity.module 49 KB

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