field_collection.entity.inc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. <?php
  2. /**
  3. * Class for field_collection_item entities.
  4. */
  5. class FieldCollectionItemEntity extends Entity {
  6. /**
  7. * Field collection field info.
  8. *
  9. * @var array
  10. */
  11. protected $fieldInfo;
  12. /**
  13. * The host entity object.
  14. *
  15. * @var object
  16. */
  17. protected $hostEntity;
  18. /**
  19. * The host entity ID.
  20. *
  21. * @var integer
  22. */
  23. protected $hostEntityId;
  24. /**
  25. * The host entity revision ID if this is not the default revision.
  26. *
  27. * @var integer
  28. */
  29. protected $hostEntityRevisionId;
  30. /**
  31. * The host entity type.
  32. *
  33. * @var string
  34. */
  35. protected $hostEntityType;
  36. /**
  37. * The language under which the field collection item is stored.
  38. *
  39. * @var string
  40. */
  41. protected $langcode = LANGUAGE_NONE;
  42. /**
  43. * Entity ID.
  44. *
  45. * @var integer
  46. */
  47. public $item_id;
  48. /**
  49. * Field collection revision ID.
  50. *
  51. * @var integer
  52. */
  53. public $revision_id;
  54. /**
  55. * The name of the field-collection field this item is associated with.
  56. *
  57. * @var string
  58. */
  59. public $field_name;
  60. /**
  61. * Whether this revision is the default revision.
  62. *
  63. * @var bool
  64. */
  65. public $default_revision = TRUE;
  66. /**
  67. * Whether the field collection item is archived, i.e. not in use.
  68. *
  69. * @see FieldCollectionItemEntity::isInUse()
  70. * @var bool
  71. */
  72. public $archived = FALSE;
  73. /**
  74. * Constructs the entity object.
  75. */
  76. public function __construct(array $values = array(), $entityType = NULL) {
  77. parent::__construct($values, 'field_collection_item');
  78. // Workaround issues http://drupal.org/node/1084268 and
  79. // http://drupal.org/node/1264440:
  80. // Check if the required property is set before checking for the field's
  81. // type. If the property is not set, we are hitting a PDO or a core's bug.
  82. // FIXME: Remove when #1264440 is fixed and the required PHP version is
  83. // properly identified and documented in the module documentation.
  84. if (isset($this->field_name)) {
  85. // Ok, we have the field name property, we can proceed and check the field's type
  86. $field_info = $this->fieldInfo();
  87. if (!$field_info || $field_info['type'] != 'field_collection') {
  88. throw new Exception("Invalid field name given: {$this->field_name} is not a Field Collection field.");
  89. }
  90. }
  91. }
  92. /**
  93. * Provides info about the field on the host entity, which embeds this
  94. * field collection item.
  95. */
  96. public function fieldInfo() {
  97. return field_info_field($this->field_name);
  98. }
  99. /**
  100. * Provides info of the field instance containing the reference to this
  101. * field collection item.
  102. */
  103. public function instanceInfo() {
  104. if ($this->fetchHostDetails()) {
  105. return field_info_instance($this->hostEntityType(), $this->field_name, $this->hostEntityBundle());
  106. }
  107. }
  108. /**
  109. * Returns the field instance label translated to interface language.
  110. */
  111. public function translatedInstanceLabel($langcode = NULL) {
  112. if ($info = $this->instanceInfo()) {
  113. if (module_exists('i18n_field')) {
  114. return i18n_string("field:{$this->field_name}:{$info['bundle']}:label", $info['label'], array('langcode' => $langcode));
  115. }
  116. return $info['label'];
  117. }
  118. }
  119. /**
  120. * Specifies the default label, which is picked up by label() by default.
  121. */
  122. public function defaultLabel() {
  123. if ($this->fetchHostDetails()) {
  124. $field = $this->fieldInfo();
  125. $label = $this->translatedInstanceLabel();
  126. $host = $this->hostEntity();
  127. if ($new_label = module_invoke_all('field_collection_item_label', $this, $host, $field, $label)) {
  128. return array_pop($new_label);
  129. }
  130. elseif ($field['cardinality'] == 1) {
  131. return $label;
  132. }
  133. elseif ($this->item_id) {
  134. return t('!instance_label @count', array('!instance_label' => $label, '@count' => $this->delta() + 1));
  135. }
  136. else {
  137. return t('New !instance_label', array('!instance_label' => $label));
  138. }
  139. }
  140. return t('Unconnected field collection item');
  141. }
  142. /**
  143. * Returns the path used to view the entity.
  144. */
  145. public function path() {
  146. if ($this->item_id) {
  147. return field_collection_field_get_path($this->fieldInfo()) . '/' . $this->item_id;
  148. }
  149. }
  150. /**
  151. * Returns the URI as returned by entity_uri().
  152. */
  153. public function defaultUri() {
  154. return array(
  155. 'path' => $this->path(),
  156. );
  157. }
  158. /**
  159. * Sets the host entity. Only possible during creation of a item.
  160. *
  161. * @param $create_link
  162. * (optional) Whether a field-item linking the host entity to the field
  163. * collection item should be created.
  164. */
  165. public function setHostEntity($entity_type, $entity, $langcode = LANGUAGE_NONE, $create_link = TRUE) {
  166. if (!empty($this->is_new)) {
  167. $this->hostEntityType = $entity_type;
  168. $this->hostEntity = $entity;
  169. $this->langcode = $langcode;
  170. list($this->hostEntityId, $this->hostEntityRevisionId) = entity_extract_ids($this->hostEntityType, $this->hostEntity);
  171. // If the host entity is not saved yet, set the id to FALSE. So
  172. // fetchHostDetails() does not try to load the host entity details.
  173. if (!isset($this->hostEntityId)) {
  174. $this->hostEntityId = FALSE;
  175. }
  176. // We are create a new field collection for a non-default entity, thus
  177. // set archived to TRUE.
  178. if (!entity_revision_is_default($entity_type, $entity)) {
  179. $this->hostEntityId = FALSE;
  180. $this->archived = TRUE;
  181. }
  182. if ($create_link) {
  183. $entity->{$this->field_name}[$this->langcode][] = array('entity' => $this);
  184. }
  185. }
  186. else {
  187. throw new Exception('The host entity may be set only during creation of a field collection item.');
  188. }
  189. }
  190. /**
  191. * Updates the wrapped host entity object.
  192. *
  193. * @param object $entity
  194. * Host entity.
  195. * @param string $host_entity_type
  196. * The entity type of the entity the field collection is attached to.
  197. */
  198. public function updateHostEntity($entity, $host_entity_type = NULL) {
  199. $this->fetchHostDetails();
  200. // If it isn't possible to retrieve hostEntityType due to the fact that it's
  201. // not saved in the DB yet then fill in info about the hostEntity manually.
  202. // This happens when creating a new revision of a field collection entity
  203. // and it needs to relate to the new revision of the host entity.
  204. if (!$this->hostEntityType) {
  205. $this->hostEntityType = $host_entity_type;
  206. $this->hostEntity = $entity;
  207. list($this->hostEntityId, $this->hostEntityRevisionId) = entity_extract_ids($this->hostEntityType, $this->hostEntity);
  208. }
  209. list($recieved_id) = entity_extract_ids($this->hostEntityType, $entity);
  210. if ($this->isInUse()) {
  211. $current_id = $this->hostEntityId;
  212. }
  213. else {
  214. $current_host = entity_revision_load($this->hostEntityType, $this->hostEntityRevisionId);
  215. list($current_id) = entity_extract_ids($this->hostEntityType, $current_host);
  216. }
  217. if ($current_id == $recieved_id) {
  218. $this->hostEntity = $entity;
  219. $delta = $this->delta();
  220. if (isset($entity->{$this->field_name}[$this->langcode()][$delta]['entity'])) {
  221. $entity->{$this->field_name}[$this->langcode()][$delta]['entity'] = $this;
  222. }
  223. }
  224. else {
  225. throw new Exception('The host entity cannot be changed.');
  226. }
  227. }
  228. /**
  229. * Returns the host entity, which embeds this field collection item.
  230. */
  231. public function hostEntity() {
  232. if ($this->fetchHostDetails()) {
  233. if (!isset($this->hostEntity) && $this->isInUse()) {
  234. $this->hostEntity = entity_load_single($this->hostEntityType, $this->hostEntityId);
  235. }
  236. elseif (!isset($this->hostEntity) && $this->hostEntityRevisionId) {
  237. $this->hostEntity = entity_revision_load($this->hostEntityType, $this->hostEntityRevisionId);
  238. }
  239. return $this->hostEntity;
  240. }
  241. }
  242. /**
  243. * Returns the entity type of the host entity, which embeds this
  244. * field collection item.
  245. */
  246. public function hostEntityType() {
  247. if ($this->fetchHostDetails()) {
  248. return $this->hostEntityType;
  249. }
  250. }
  251. /**
  252. * Returns the id of the host entity, which embeds this field collection item.
  253. */
  254. public function hostEntityId() {
  255. if ($this->fetchHostDetails()) {
  256. if (!$this->hostEntityId && $this->hostEntityRevisionId) {
  257. $this->hostEntityId = entity_id($this->hostEntityType, $this->hostEntity());
  258. }
  259. return $this->hostEntityId;
  260. }
  261. }
  262. /**
  263. * Returns the bundle of the host entity, which embeds this field collection
  264. * item.
  265. */
  266. public function hostEntityBundle() {
  267. if ($entity = $this->hostEntity()) {
  268. list($id, $rev_id, $bundle) = entity_extract_ids($this->hostEntityType, $entity);
  269. return $bundle;
  270. }
  271. }
  272. protected function fetchHostDetails() {
  273. if (!isset($this->hostEntityId)) {
  274. if ($this->item_id) {
  275. // For saved field collections, query the field data to determine the
  276. // right host entity.
  277. $query = new EntityFieldQuery();
  278. $query->fieldCondition($this->fieldInfo(), 'revision_id', $this->revision_id);
  279. if (!$this->isInUse()) {
  280. $query->age(FIELD_LOAD_REVISION);
  281. }
  282. $result = $query->execute();
  283. list($this->hostEntityType, $data) = each($result);
  284. if ($this->isInUse()) {
  285. $this->hostEntityId = $data ? key($data) : FALSE;
  286. $this->hostEntityRevisionId = FALSE;
  287. }
  288. // If we are querying for revisions, we get the revision ID.
  289. else {
  290. $this->hostEntityId = FALSE;
  291. $this->hostEntityRevisionId = $data ? key($data) : FALSE;
  292. }
  293. }
  294. else {
  295. // No host entity available yet.
  296. $this->hostEntityId = FALSE;
  297. }
  298. }
  299. return !empty($this->hostEntityId) || !empty($this->hostEntity) || !empty($this->hostEntityRevisionId);
  300. }
  301. /**
  302. * Determines the $delta of the reference pointing to this field collection
  303. * item.
  304. */
  305. public function delta() {
  306. if (($entity = $this->hostEntity()) && isset($entity->{$this->field_name})) {
  307. foreach ($entity->{$this->field_name} as $langcode => &$data) {
  308. if (!empty($data)) {
  309. foreach ($data as $delta => $item) {
  310. if (isset($item['value']) && $item['value'] == $this->item_id) {
  311. $this->langcode = $langcode;
  312. return $delta;
  313. }
  314. elseif (isset($item['entity']) && $item['entity'] === $this) {
  315. $this->langcode = $langcode;
  316. return $delta;
  317. }
  318. }
  319. }
  320. }
  321. // If we don't find the delta in the current values (cause the item
  322. // is being deleted, for example), we search the delta in the originalcontent.
  323. if (!empty($entity->original)) {
  324. foreach ($entity->original->{$this->field_name} as $langcode => &$data) {
  325. if (!empty($data)) {
  326. foreach ($data as $delta => $item) {
  327. if (isset($item['value']) && $item['value'] == $this->item_id) {
  328. $this->langcode = $langcode;
  329. return $delta;
  330. }
  331. elseif (isset($item['entity']) && $item['entity'] === $this) {
  332. $this->langcode = $langcode;
  333. return $delta;
  334. }
  335. }
  336. }
  337. }
  338. }
  339. }
  340. }
  341. /**
  342. * Determines the language code under which the item is stored.
  343. */
  344. public function langcode() {
  345. if ($this->delta() === NULL || empty($this->langcode)) {
  346. $this->langcode = field_collection_entity_language('field_collection_item', $this);
  347. }
  348. if (empty($this->langcode) || ($this->langcode != LANGUAGE_NONE && (!module_exists('entity_translation') || !entity_translation_enabled('field_collection_item')))) {
  349. $this->langcode = LANGUAGE_NONE;
  350. }
  351. return $this->langcode;
  352. }
  353. /**
  354. * Determines whether this field collection item revision is in use.
  355. *
  356. * Field collection items may be contained in from non-default host entity
  357. * revisions. If the field collection item does not appear in the default
  358. * host entity revision, the item is actually not used by default and so
  359. * marked as 'archived'.
  360. * If the field collection item appears in the default revision of the host
  361. * entity, the default revision of the field collection item is in use there
  362. * and the collection is not marked as archived.
  363. */
  364. public function isInUse() {
  365. return $this->default_revision && !$this->archived;
  366. }
  367. /**
  368. * Save the field collection item.
  369. *
  370. * By default, always save the host entity, so modules are able to react
  371. * upon changes to the content of the host and any 'last updated' dates of
  372. * entities get updated.
  373. *
  374. * For creating an item a host entity has to be specified via setHostEntity()
  375. * before this function is invoked. For the link between the entities to be
  376. * fully established, the host entity object has to be updated to include a
  377. * reference on this field collection item during saving. So do not skip
  378. * saving the host for creating items.
  379. *
  380. * @param $skip_host_save
  381. * (internal) If TRUE is passed, the host entity is not saved automatically
  382. * and therefore no link is created between the host and the item or
  383. * revision updates might be skipped. Use with care.
  384. */
  385. public function save($skip_host_save = FALSE) {
  386. // Make sure we have a host entity during creation.
  387. if (!empty($this->is_new) && !(isset($this->hostEntityId) || isset($this->hostEntity) || isset($this->hostEntityRevisionId))) {
  388. throw new Exception("Unable to create a field collection item without a given host entity.");
  389. }
  390. // Copy the values of translatable fields for a new field collection item.
  391. if (field_collection_item_is_translatable() && !empty($this->is_new) && $this->langcode() == LANGUAGE_NONE) {
  392. $this->copyTranslations();
  393. }
  394. // Only save directly if we are told to skip saving the host entity. Else,
  395. // we always save via the host as saving the host might trigger saving
  396. // field collection items anyway (e.g. if a new revision is created).
  397. if ($skip_host_save) {
  398. return entity_get_controller($this->entityType)->save($this);
  399. }
  400. else {
  401. $host_entity = $this->hostEntity();
  402. if (!$host_entity) {
  403. throw new Exception("Unable to save a field collection item without a valid reference to a host entity.");
  404. }
  405. // If this is creating a new revision, also do so for the host entity.
  406. if (!empty($this->revision) || !empty($this->is_new_revision)) {
  407. $host_entity->revision = TRUE;
  408. if (!empty($this->default_revision)) {
  409. entity_revision_set_default($this->hostEntityType, $host_entity);
  410. }
  411. }
  412. // Set the host entity reference, so the item will be saved with the host.
  413. // @see field_collection_field_presave()
  414. $delta = $this->delta();
  415. if (isset($delta)) {
  416. $host_entity->{$this->field_name}[$this->langcode()][$delta] = array('entity' => $this);
  417. }
  418. else {
  419. $host_entity->{$this->field_name}[$this->langcode()][] = array('entity' => $this);
  420. }
  421. return entity_save($this->hostEntityType, $host_entity);
  422. }
  423. }
  424. /**
  425. * Deletes the field collection item and the reference in the host entity.
  426. */
  427. public function delete() {
  428. parent::delete();
  429. $this->deleteHostEntityReference();
  430. }
  431. /**
  432. * Copies text to all languages the collection item has a translation for.
  433. *
  434. * @param $source_language
  435. * Language code to copy the text from.
  436. */
  437. public function copyTranslations($source_language = NULL) {
  438. // Get a handler for Entity Translation if there is one.
  439. $host_et_handler = NULL;
  440. if (module_exists('entity_translation')) {
  441. $host_et_handler = entity_translation_get_handler($this->hostEntityType(), $this->hostEntity());
  442. }
  443. if (is_null($host_et_handler)) {
  444. return;
  445. }
  446. $host_languages = array_keys($host_et_handler->getTranslations()->data);
  447. if (empty($host_languages)) {
  448. $host_languages = array(entity_language($this->hostEntityType(), $this->hostEntity()));
  449. }
  450. $source_language = isset($source_language) ? $source_language : $host_et_handler->getLanguage();
  451. $target_languages = array_diff($host_languages, array($source_language));
  452. $fields_instances = array_keys(field_info_instances('field_collection_item', $this->field_name));
  453. $fields = field_info_fields();
  454. foreach ($fields_instances as $translatable_field) {
  455. if ($fields[$translatable_field]['translatable'] == 1) {
  456. foreach ($target_languages as $langcode) {
  457. if (isset($this->{$translatable_field}[$source_language])) {
  458. //Source (translatable_field) is set, therefore continue processing.
  459. if(!isset($this->{$translatable_field}[$langcode])) {
  460. //Destination (translatable_field) is not set, therefore safe to copy the translation.
  461. $this->{$translatable_field}[$langcode] = $this->{$translatable_field}[$source_language];
  462. }
  463. }
  464. }
  465. if ($source_language == LANGUAGE_NONE && count($this->{$translatable_field}) > 1) {
  466. $this->{$translatable_field}[$source_language] = NULL;
  467. }
  468. }
  469. }
  470. }
  471. /**
  472. * Deletes the host entity's reference of the field collection item.
  473. */
  474. protected function deleteHostEntityReference() {
  475. $delta = $this->delta();
  476. if ($this->item_id && isset($delta)) {
  477. unset($this->hostEntity->{$this->field_name}[$this->langcode()][$delta]);
  478. // Do not save when the host entity is being deleted. See
  479. // field_collection_field_delete().
  480. if (empty($this->hostEntity->field_collection_deleting)) {
  481. entity_save($this->hostEntityType(), $this->hostEntity());
  482. }
  483. }
  484. }
  485. /**
  486. * Intelligently delete a field collection item revision.
  487. *
  488. * If a host entity is revisioned with its field collection items, deleting
  489. * a field collection item on the default revision of the host should not
  490. * delete the collection item from archived revisions too. Instead, we delete
  491. * the current default revision and archive the field collection.
  492. */
  493. public function deleteRevision($skip_host_update = FALSE) {
  494. if (!$this->revision_id) {
  495. return;
  496. }
  497. if (!$skip_host_update) {
  498. // Just remove the item from the host, which cares about deleting the
  499. // item (depending on whether the update creates a new revision).
  500. $this->deleteHostEntityReference();
  501. }
  502. if (!$this->isDefaultRevision()) {
  503. entity_revision_delete('field_collection_item', $this->revision_id);
  504. }
  505. // If deleting the default revision, take care!
  506. else {
  507. $row = db_select('field_collection_item_revision', 'r')
  508. ->fields('r')
  509. ->condition('item_id', $this->item_id)
  510. ->condition('revision_id', $this->revision_id, '<>')
  511. ->execute()
  512. ->fetchAssoc();
  513. if ($row) {
  514. // Make the other revision the default revision and archive the item.
  515. db_update('field_collection_item')
  516. ->fields(array('archived' => 1, 'revision_id' => $row['revision_id']))
  517. ->condition('item_id', $this->item_id)
  518. ->execute();
  519. entity_get_controller('field_collection_item')->resetCache(array($this->item_id));
  520. entity_revision_delete('field_collection_item', $this->revision_id);
  521. }
  522. if (!$row && !isset($this->hostEntity()->{$this->field_name}[$this->langcode()][$this->delta()])) {
  523. // Delete if there is no existing revision or translation to be saved.
  524. $this->delete();
  525. }
  526. }
  527. }
  528. /**
  529. * Export the field collection item.
  530. *
  531. * Since field collection entities are not directly exportable (i.e., do not
  532. * have 'exportable' set to TRUE in hook_entity_info()) and since Features
  533. * calls this method when exporting the field collection as a field attached
  534. * to another entity, we return the export in the format expected by
  535. * Features, rather than in the normal Entity::export() format.
  536. */
  537. public function export($prefix = '') {
  538. // Based on code in EntityDefaultFeaturesController::export_render().
  539. $export = "entity_import('" . $this->entityType() . "', '";
  540. $export .= addcslashes(parent::export(), '\\\'');
  541. $export .= "')";
  542. return $export;
  543. }
  544. /**
  545. * Generate an array for rendering the field collection item.
  546. */
  547. public function view($view_mode = 'full', $langcode = NULL, $page = NULL) {
  548. // Allow modules to change the view mode.
  549. $view_mode = key(entity_view_mode_prepare($this->entityType, array($this->item_id => $this), $view_mode, $langcode));
  550. return parent::view($view_mode, $langcode, $page);
  551. }
  552. /**
  553. * Magic method to only serialize what's necessary.
  554. */
  555. public function __sleep() {
  556. $vars = get_object_vars($this);
  557. unset($vars['entityInfo'], $vars['idKey'], $vars['nameKey'], $vars['statusKey']);
  558. unset($vars['fieldInfo']);
  559. // Also do not serialize the host entity, but only if it has already an id.
  560. if ($this->hostEntity && ($this->hostEntityId || $this->hostEntityRevisionId)) {
  561. unset($vars['hostEntity']);
  562. }
  563. // Also key the returned array with the variable names so the method may
  564. // be easily overridden and customized.
  565. return drupal_map_assoc(array_keys($vars));
  566. }
  567. /**
  568. * Magic method to invoke setUp() on unserialization.
  569. *
  570. * @todo: Remove this once it appears in a released entity API module version.
  571. */
  572. public function __wakeup() {
  573. $this->setUp();
  574. }
  575. }