entity.module 55 KB

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