entity.module 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574
  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. foreach (entity_crud_get_info() as $entity_type => $entity_info) {
  1017. if (isset($entity_info['module']) && !empty($entity_info['entity cache'])) {
  1018. $tables[] = 'cache_entity_' . $entity_type;
  1019. }
  1020. }
  1021. return $tables;
  1022. }
  1023. }
  1024. /**
  1025. * Implements hook_theme().
  1026. */
  1027. function entity_theme() {
  1028. // Build a pattern in the form of "(type1|type2|...)(\.|__)" such that all
  1029. // templates starting with an entity type or named like the entity type
  1030. // are found.
  1031. // This has to match the template suggestions provided in
  1032. // template_preprocess_entity().
  1033. $types = array_keys(entity_crud_get_info());
  1034. $pattern = '(' . implode('|', $types) . ')(\.|__)';
  1035. return array(
  1036. 'entity_status' => array(
  1037. 'variables' => array('status' => NULL, 'html' => TRUE),
  1038. 'file' => 'theme/entity.theme.inc',
  1039. ),
  1040. 'entity' => array(
  1041. 'render element' => 'elements',
  1042. 'template' => 'entity',
  1043. 'pattern' => $pattern,
  1044. 'path' => drupal_get_path('module', 'entity') . '/theme',
  1045. 'file' => 'entity.theme.inc',
  1046. ),
  1047. 'entity_property' => array(
  1048. 'render element' => 'elements',
  1049. 'file' => 'theme/entity.theme.inc',
  1050. ),
  1051. 'entity_ui_overview_item' => array(
  1052. 'variables' => array('label' => NULL, 'entity_type' => NULL, 'url' => FALSE, 'name' => FALSE),
  1053. 'file' => 'includes/entity.ui.inc'
  1054. ),
  1055. );
  1056. }
  1057. /**
  1058. * Label callback that refers to the entity classes label method.
  1059. */
  1060. function entity_class_label($entity) {
  1061. return $entity->label();
  1062. }
  1063. /**
  1064. * URI callback that refers to the entity classes uri method.
  1065. */
  1066. function entity_class_uri($entity) {
  1067. return $entity->uri();
  1068. }
  1069. /**
  1070. * Implements hook_file_download_access() for entity types provided by the CRUD API.
  1071. */
  1072. function entity_file_download_access($field, $entity_type, $entity) {
  1073. $info = entity_get_info($entity_type);
  1074. if (in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
  1075. return entity_access('view', $entity_type, $entity);
  1076. }
  1077. }
  1078. /**
  1079. * Determines the UI controller class for a given entity type.
  1080. *
  1081. * @return EntityDefaultUIController
  1082. * If a type is given, the controller for the given entity type. Else an array
  1083. * of all enabled UI controllers keyed by entity type is returned.
  1084. */
  1085. function entity_ui_controller($type = NULL) {
  1086. $static = &drupal_static(__FUNCTION__);
  1087. if (!isset($type)) {
  1088. // Invoke the function for each type to ensure we have fully populated the
  1089. // static variable.
  1090. foreach (entity_get_info() as $entity_type => $info) {
  1091. entity_ui_controller($entity_type);
  1092. }
  1093. return array_filter($static);
  1094. }
  1095. if (!isset($static[$type])) {
  1096. $info = entity_get_info($type);
  1097. $class = isset($info['admin ui']['controller class']) ? $info['admin ui']['controller class'] : 'EntityDefaultUIController';
  1098. $static[$type] = (isset($info['admin ui']['path']) && $class) ? new $class($type, $info) : FALSE;
  1099. }
  1100. return $static[$type];
  1101. }
  1102. /**
  1103. * Implements hook_menu().
  1104. *
  1105. * @see EntityDefaultUIController::hook_menu()
  1106. */
  1107. function entity_menu() {
  1108. $items = array();
  1109. foreach (entity_ui_controller() as $controller) {
  1110. $items += $controller->hook_menu();
  1111. }
  1112. return $items;
  1113. }
  1114. /**
  1115. * Implements hook_forms().
  1116. *
  1117. * @see EntityDefaultUIController::hook_forms()
  1118. * @see entity_ui_get_form()
  1119. */
  1120. function entity_forms($form_id, $args) {
  1121. // For efficiency only invoke an entity types controller, if a form of it is
  1122. // requested. Thus if the first (overview and operation form) or the third
  1123. // argument (edit form) is an entity type name, add in the types forms.
  1124. if (isset($args[0]) && is_string($args[0]) && entity_get_info($args[0])) {
  1125. $type = $args[0];
  1126. }
  1127. elseif (isset($args[2]) && is_string($args[2]) && entity_get_info($args[2])) {
  1128. $type = $args[2];
  1129. }
  1130. if (isset($type) && $controller = entity_ui_controller($type)) {
  1131. return $controller->hook_forms();
  1132. }
  1133. }
  1134. /**
  1135. * A wrapper around drupal_get_form() that helps building entity forms.
  1136. *
  1137. * This function may be used by entities to build their entity form. It has to
  1138. * be used instead of calling drupal_get_form().
  1139. * Entity forms built with this helper receive useful defaults suiting for
  1140. * editing a single entity, whereas the special cases of adding and cloning
  1141. * of entities are supported too.
  1142. *
  1143. * While this function is intended to be used to get entity forms for entities
  1144. * using the entity ui controller, it may be used for entity types not using
  1145. * the ui controller too.
  1146. *
  1147. * @param $entity_type
  1148. * The entity type for which to get the form.
  1149. * @param $entity
  1150. * The entity for which to return the form.
  1151. * If $op is 'add' the entity has to be either initialized before calling this
  1152. * function, or NULL may be passed. If NULL is passed, an entity will be
  1153. * initialized with empty values using entity_create(). Thus entities, for
  1154. * which this is problematic have to care to pass in an initialized entity.
  1155. * @param $op
  1156. * (optional) One of 'edit', 'add' or 'clone'. Defaults to edit.
  1157. * @param $form_state
  1158. * (optional) A pre-populated form state, e.g. to add in form include files.
  1159. * See entity_metadata_form_entity_ui().
  1160. *
  1161. * @return
  1162. * The fully built and processed form, ready to be rendered.
  1163. *
  1164. * @see EntityDefaultUIController::hook_forms()
  1165. * @see entity_ui_form_submit_build_entity()
  1166. */
  1167. function entity_ui_get_form($entity_type, $entity, $op = 'edit', $form_state = array()) {
  1168. if (isset($entity)) {
  1169. list(, , $bundle) = entity_extract_ids($entity_type, $entity);
  1170. }
  1171. $form_id = (!isset($bundle) || $bundle == $entity_type) ? $entity_type . '_form' : $entity_type . '_edit_' . $bundle . '_form';
  1172. if (!isset($entity) && $op == 'add') {
  1173. $entity = entity_create($entity_type, array());
  1174. }
  1175. // Do not use drupal_get_form(), but invoke drupal_build_form() ourself so
  1176. // we can prepulate the form state.
  1177. $form_state['wrapper_callback'] = 'entity_ui_main_form_defaults';
  1178. $form_state['entity_type'] = $entity_type;
  1179. form_load_include($form_state, 'inc', 'entity', 'includes/entity.ui');
  1180. // Handle cloning. We cannot do that in the wrapper callback as it is too late
  1181. // for changing arguments.
  1182. if ($op == 'clone') {
  1183. $entity = entity_ui_clone_entity($entity_type, $entity);
  1184. }
  1185. // We don't pass the entity type as first parameter, as the implementing
  1186. // module knows the type anyway. However, in order to allow for efficient
  1187. // hook_forms() implementiations we append the entity type as last argument,
  1188. // which the module implementing the form constructor may safely ignore.
  1189. // @see entity_forms()
  1190. $form_state['build_info']['args'] = array($entity, $op, $entity_type);
  1191. return drupal_build_form($form_id, $form_state);
  1192. }
  1193. /**
  1194. * Gets the page/menu title for local action operations.
  1195. *
  1196. * @param $op
  1197. * The current operation. One of 'add' or 'import'.
  1198. * @param $entity_type
  1199. * The entity type.
  1200. * @param $bundle_name
  1201. * (Optional) The name of the bundle. May be NULL if the bundle name is not
  1202. * relevant to the current page. If the entity type has only one bundle, or no
  1203. * bundles, this will be the same as the entity type.
  1204. */
  1205. function entity_ui_get_action_title($op, $entity_type, $bundle_name = NULL) {
  1206. $info = entity_get_info($entity_type);
  1207. switch ($op) {
  1208. case 'add':
  1209. if (isset($bundle_name) && $bundle_name != $entity_type) {
  1210. return t('Add @bundle_name @entity_type', array(
  1211. '@bundle_name' => drupal_strtolower($info['bundles'][$bundle_name]['label']),
  1212. '@entity_type' => drupal_strtolower($info['label']),
  1213. ));
  1214. }
  1215. else {
  1216. return t('Add @entity_type', array('@entity_type' => drupal_strtolower($info['label'])));
  1217. }
  1218. case 'import':
  1219. return t('Import @entity_type', array('@entity_type' => drupal_strtolower($info['label'])));
  1220. }
  1221. }
  1222. /**
  1223. * Helper for using i18n_string().
  1224. *
  1225. * @param $name
  1226. * Textgroup and context glued with ':'.
  1227. * @param $default
  1228. * String in default language. Default language may or may not be English.
  1229. * @param $langcode
  1230. * (optional) The code of a certain language to translate the string into.
  1231. * Defaults to the i18n_string() default, i.e. the current language.
  1232. *
  1233. * @see i18n_string()
  1234. */
  1235. function entity_i18n_string($name, $default, $langcode = NULL) {
  1236. return function_exists('i18n_string') ? i18n_string($name, $default, array('langcode' => $langcode)) : $default;
  1237. }
  1238. /**
  1239. * Implements hook_views_api().
  1240. */
  1241. function entity_views_api() {
  1242. return array(
  1243. 'api' => '3.0-alpha1',
  1244. 'path' => drupal_get_path('module', 'entity') . '/views',
  1245. );
  1246. }
  1247. /**
  1248. * Implements hook_field_extra_fields().
  1249. */
  1250. function entity_field_extra_fields() {
  1251. // Invoke specified controllers for entity types provided by the CRUD API.
  1252. $items = array();
  1253. foreach (entity_crud_get_info() as $type => $info) {
  1254. if (!empty($info['extra fields controller class'])) {
  1255. $items = array_merge_recursive($items, entity_get_extra_fields_controller($type)->fieldExtraFields());
  1256. }
  1257. }
  1258. return $items;
  1259. }
  1260. /**
  1261. * Gets the extra field controller class for a given entity type.
  1262. *
  1263. * @return EntityExtraFieldsControllerInterface|false
  1264. * The controller for the given entity type or FALSE if none is specified.
  1265. */
  1266. function entity_get_extra_fields_controller($type = NULL) {
  1267. $static = &drupal_static(__FUNCTION__);
  1268. if (!isset($static[$type])) {
  1269. $static[$type] = FALSE;
  1270. $info = entity_get_info($type);
  1271. if (!empty($info['extra fields controller class'])) {
  1272. $static[$type] = new $info['extra fields controller class']($type);
  1273. }
  1274. }
  1275. return $static[$type];
  1276. }
  1277. /**
  1278. * Returns a property wrapper for the given data.
  1279. *
  1280. * If an entity is wrapped, the wrapper can be used to retrieve further wrappers
  1281. * for the entity properties. For that the wrapper support chaining, e.g. you
  1282. * can use a node wrapper to get the node authors mail address:
  1283. *
  1284. * @code
  1285. * echo $wrappedNode->author->mail->value();
  1286. * @endcode
  1287. *
  1288. * @param $type
  1289. * The type of the passed data.
  1290. * @param $data
  1291. * The data to wrap. It may be set to NULL, so the wrapper can be used
  1292. * without any data for getting information about properties.
  1293. * @param $info
  1294. * (optional) Specify additional information for the passed data:
  1295. * - langcode: (optional) If the data is language specific, its langauge
  1296. * code. Defaults to NULL, what means language neutral.
  1297. * - bundle: (optional) If an entity is wrapped but not passed, use this key
  1298. * to specify the bundle to return a wrapper for.
  1299. * - property info: (optional) May be used to use a wrapper with an arbitrary
  1300. * data structure (type 'struct'). Use this key for specifying info about
  1301. * properties in the same structure as used by hook_entity_property_info().
  1302. * - property info alter: (optional) A callback for altering the property
  1303. * info before it is utilized by the wrapper.
  1304. * - property defaults: (optional) An array of defaults for the info of
  1305. * each property of the wrapped data item.
  1306. * @return EntityMetadataWrapper
  1307. * Dependend on the passed data the right wrapper is returned.
  1308. */
  1309. function entity_metadata_wrapper($type, $data = NULL, array $info = array()) {
  1310. if ($type == 'entity' || (($entity_info = entity_get_info()) && isset($entity_info[$type]))) {
  1311. // If the passed entity is the global $user, we load the user object by only
  1312. // passing on the user id. The global user is not a fully loaded entity.
  1313. if ($type == 'user' && is_object($data) && $data == $GLOBALS['user']) {
  1314. $data = $data->uid;
  1315. }
  1316. return new EntityDrupalWrapper($type, $data, $info);
  1317. }
  1318. elseif ($type == 'list' || entity_property_list_extract_type($type)) {
  1319. return new EntityListWrapper($type, $data, $info);
  1320. }
  1321. elseif (isset($info['property info'])) {
  1322. return new EntityStructureWrapper($type, $data, $info);
  1323. }
  1324. else {
  1325. return new EntityValueWrapper($type, $data, $info);
  1326. }
  1327. }
  1328. /**
  1329. * Returns a metadata wrapper for accessing site-wide properties.
  1330. *
  1331. * Although there is no 'site' entity or such, modules may provide info about
  1332. * site-wide properties using hook_entity_property_info(). This function returns
  1333. * a wrapper for making use of this properties.
  1334. *
  1335. * @return EntityMetadataWrapper
  1336. * A wrapper for accessing site-wide properties.
  1337. *
  1338. * @see entity_metadata_system_entity_property_info()
  1339. */
  1340. function entity_metadata_site_wrapper() {
  1341. $site_info = entity_get_property_info('site');
  1342. $info['property info'] = $site_info['properties'];
  1343. return entity_metadata_wrapper('site', FALSE, $info);
  1344. }
  1345. /**
  1346. * Implements hook_module_implements_alter().
  1347. *
  1348. * Moves the hook_entity_info_alter() implementation to the bottom so it is
  1349. * invoked after all modules relying on the entity API.
  1350. * That way we ensure to run last and clear the field-info cache after the
  1351. * others added in their bundle information.
  1352. *
  1353. * @see entity_entity_info_alter()
  1354. */
  1355. function entity_module_implements_alter(&$implementations, $hook) {
  1356. if ($hook == 'entity_info_alter') {
  1357. // Move our hook implementation to the bottom.
  1358. $group = $implementations['entity'];
  1359. unset($implementations['entity']);
  1360. $implementations['entity'] = $group;
  1361. }
  1362. }
  1363. /**
  1364. * Implements hook_entity_info_alter().
  1365. *
  1366. * @see entity_module_implements_alter()
  1367. */
  1368. function entity_entity_info_alter(&$entity_info) {
  1369. _entity_info_add_metadata($entity_info);
  1370. // Populate a default value for the 'configuration' key of all entity types.
  1371. foreach ($entity_info as $type => $info) {
  1372. if (!isset($info['configuration'])) {
  1373. $entity_info[$type]['configuration'] = !empty($info['exportable']);
  1374. }
  1375. if (isset($info['controller class']) && in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
  1376. // Automatically disable field cache when entity cache is used.
  1377. if (!empty($info['entity cache']) && module_exists('entitycache')) {
  1378. $entity_info[$type]['field cache'] = FALSE;
  1379. }
  1380. }
  1381. }
  1382. }
  1383. /**
  1384. * Adds metadata and callbacks for core entities to the entity info.
  1385. */
  1386. function _entity_info_add_metadata(&$entity_info) {
  1387. // Set plural labels.
  1388. $entity_info['node']['plural label'] = t('Nodes');
  1389. $entity_info['user']['plural label'] = t('Users');
  1390. $entity_info['file']['plural label'] = t('Files');
  1391. // Set descriptions.
  1392. $entity_info['node']['description'] = t('Nodes represent the main site content items.');
  1393. $entity_info['user']['description'] = t('Users who have created accounts on your site.');
  1394. $entity_info['file']['description'] = t('Uploaded file.');
  1395. // Set access callbacks.
  1396. $entity_info['node']['access callback'] = 'entity_metadata_no_hook_node_access';
  1397. $entity_info['user']['access callback'] = 'entity_metadata_user_access';
  1398. // File entity has it's own entity_access function.
  1399. if (!module_exists('file_entity')) {
  1400. $entity_info['file']['access callback'] = 'entity_metadata_file_access';
  1401. }
  1402. // CRUD function callbacks.
  1403. $entity_info['node']['creation callback'] = 'entity_metadata_create_node';
  1404. $entity_info['node']['save callback'] = 'node_save';
  1405. $entity_info['node']['deletion callback'] = 'node_delete';
  1406. $entity_info['node']['revision deletion callback'] = 'node_revision_delete';
  1407. $entity_info['user']['creation callback'] = 'entity_metadata_create_object';
  1408. $entity_info['user']['save callback'] = 'entity_metadata_user_save';
  1409. $entity_info['user']['deletion callback'] = 'user_delete';
  1410. $entity_info['file']['save callback'] = 'file_save';
  1411. $entity_info['file']['deletion callback'] = 'entity_metadata_delete_file';
  1412. // Form callbacks.
  1413. $entity_info['node']['form callback'] = 'entity_metadata_form_node';
  1414. $entity_info['user']['form callback'] = 'entity_metadata_form_user';
  1415. // URI callbacks.
  1416. if (!isset($entity_info['file']['uri callback'])) {
  1417. $entity_info['file']['uri callback'] = 'entity_metadata_uri_file';
  1418. }
  1419. // View callbacks.
  1420. $entity_info['node']['view callback'] = 'entity_metadata_view_node';
  1421. $entity_info['user']['view callback'] = 'entity_metadata_view_single';
  1422. if (module_exists('comment')) {
  1423. $entity_info['comment']['plural label'] = t('Comments');
  1424. $entity_info['comment']['description'] = t('Remark or note that refers to a node.');
  1425. $entity_info['comment']['access callback'] = 'entity_metadata_comment_access';
  1426. $entity_info['comment']['creation callback'] = 'entity_metadata_create_comment';
  1427. $entity_info['comment']['save callback'] = 'comment_save';
  1428. $entity_info['comment']['deletion callback'] = 'comment_delete';
  1429. $entity_info['comment']['view callback'] = 'entity_metadata_view_comment';
  1430. $entity_info['comment']['form callback'] = 'entity_metadata_form_comment';
  1431. }
  1432. if (module_exists('taxonomy')) {
  1433. $entity_info['taxonomy_term']['plural label'] = t('Taxonomy terms');
  1434. $entity_info['taxonomy_term']['description'] = t('Taxonomy terms are used for classifying content.');
  1435. $entity_info['taxonomy_term']['access callback'] = 'entity_metadata_taxonomy_access';
  1436. $entity_info['taxonomy_term']['creation callback'] = 'entity_metadata_create_object';
  1437. $entity_info['taxonomy_term']['save callback'] = 'taxonomy_term_save';
  1438. $entity_info['taxonomy_term']['deletion callback'] = 'taxonomy_term_delete';
  1439. $entity_info['taxonomy_term']['view callback'] = 'entity_metadata_view_single';
  1440. $entity_info['taxonomy_term']['form callback'] = 'entity_metadata_form_taxonomy_term';
  1441. $entity_info['taxonomy_vocabulary']['plural label'] = t('Taxonomy vocabularies');
  1442. $entity_info['taxonomy_vocabulary']['description'] = t('Vocabularies contain related taxonomy terms, which are used for classifying content.');
  1443. $entity_info['taxonomy_vocabulary']['access callback'] = 'entity_metadata_taxonomy_access';
  1444. $entity_info['taxonomy_vocabulary']['creation callback'] = 'entity_metadata_create_object';
  1445. $entity_info['taxonomy_vocabulary']['save callback'] = 'taxonomy_vocabulary_save';
  1446. $entity_info['taxonomy_vocabulary']['deletion callback'] = 'taxonomy_vocabulary_delete';
  1447. $entity_info['taxonomy_vocabulary']['form callback'] = 'entity_metadata_form_taxonomy_vocabulary';
  1448. // Token type mapping.
  1449. $entity_info['taxonomy_term']['token type'] = 'term';
  1450. $entity_info['taxonomy_vocabulary']['token type'] = 'vocabulary';
  1451. }
  1452. }
  1453. /**
  1454. * Implements hook_ctools_plugin_directory().
  1455. */
  1456. function entity_ctools_plugin_directory($module, $plugin) {
  1457. if ($module == 'ctools') {
  1458. return "ctools/$plugin";
  1459. }
  1460. }