entity.module 49 KB

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