entity.module 53 KB

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