translation.handler.inc 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783
  1. <?php
  2. /**
  3. * @file
  4. * Default translation handler for the translation module.
  5. */
  6. /**
  7. * Interface for enabling entity translation.
  8. *
  9. * Defines a set of methods to allow any entity to be processed by the entity
  10. * translation UI.
  11. */
  12. interface EntityTranslationHandlerInterface {
  13. /**
  14. * Injects the translation handler factory.
  15. */
  16. public function setFactory(EntityTranslationHandlerFactory $factory);
  17. /**
  18. * Registers a child translation handler for the given entity.
  19. */
  20. public function addChild($entity_type, $entity);
  21. /**
  22. * Removes a previously registered child translation handler.
  23. */
  24. public function removeChild($entity_type, $entity);
  25. /**
  26. * Loads the translation data into the wrapped entity.
  27. */
  28. public function loadTranslations();
  29. /**
  30. * Writes the translation status to the storage.
  31. */
  32. public function saveTranslations();
  33. /**
  34. * Returns the translation data for the current (wrapped) entity.
  35. */
  36. public function getTranslations();
  37. /**
  38. * Adds/updates an entity translation.
  39. *
  40. * @param $translation
  41. * A translation array as defined by the translation table's schema.
  42. * @param $values
  43. * (optional) the values that should be assigned to the field translations.
  44. */
  45. public function setTranslation($translation, $values = NULL);
  46. /**
  47. * Removes a translation from the translation set.
  48. *
  49. * @param $langcode
  50. * The language code of the translation to be removed.
  51. */
  52. public function removeTranslation($langcode);
  53. /**
  54. * Initializes the translation set by creating the original translation.
  55. */
  56. public function initTranslations();
  57. /**
  58. * Updates the translation set from the current entity status.
  59. */
  60. public function updateTranslations();
  61. /**
  62. * Removes all translations from the translation set.
  63. */
  64. public function removeTranslations();
  65. /**
  66. * Removes all translations from the current revision.
  67. */
  68. public function removeRevisionTranslations();
  69. /**
  70. * Initialize the language of the original field values.
  71. *
  72. * Ensure that the original translation language matches the language assigned
  73. * to the original field values.
  74. *
  75. * @return
  76. * TRUE if any initialization was necessary, FALSE otherwise.
  77. */
  78. public function initOriginalTranslation();
  79. /**
  80. * Returns the entity language.
  81. */
  82. public function getLanguage();
  83. /**
  84. * Sets the active language.
  85. *
  86. * This is the language that determines which translation should be considered
  87. * "active" for the wrapped entity. The "Entity Translation" module uses this
  88. * information to implement the UI-based translation workflow. Other modules
  89. * can rely on it to implement their own entity translation-related logic.
  90. *
  91. * This will affect which language is returned by the core "entity_language()"
  92. * function.
  93. *
  94. * @param string $langcode
  95. * The active language code.
  96. *
  97. * @see entity_language()
  98. * @see entity_translation_language()
  99. * @see ::getActiveLanguage()
  100. */
  101. public function setActiveLanguage($langcode);
  102. /**
  103. * Returns the active language.
  104. *
  105. * @return string
  106. * The active language for the wrapped entity.
  107. *
  108. * @see ::setActiveLanguage()
  109. */
  110. public function getActiveLanguage();
  111. /**
  112. * Sets the active form language.
  113. *
  114. * @param string $langcode
  115. * The active form language code.
  116. *
  117. * @deprecated in 7.x-1.0-beta6, will be removed before 7.x-1.0. Use
  118. * ::setActiveLanguage() instead.
  119. *
  120. * @see ::setActiveLanguage()
  121. */
  122. public function setFormLanguage($langcode);
  123. /**
  124. * Retrieves the active form language.
  125. *
  126. * @return string
  127. * The active form language code.
  128. *
  129. * @deprecated in 7.x-1.0-beta6, will be removed before 7.x-1.0. Use
  130. * ::getActiveLanguage() instead.
  131. *
  132. * @see ::getActiveLanguage()
  133. */
  134. public function getFormLanguage();
  135. /**
  136. * Returns the translation object key for the wrapped entity type.
  137. */
  138. public function getLanguageKey();
  139. /**
  140. * Returns the default language for the wrapped entity type and bundle.
  141. */
  142. public function getDefaultLanguage();
  143. /**
  144. * Sets the language of the original translation.
  145. *
  146. * @param $langcode
  147. * The language code of the original content values.
  148. */
  149. public function setOriginalLanguage($langcode);
  150. /**
  151. * Returns TRUE if the entity is currently being translated.
  152. *
  153. * @deprecated This is no longer used and will be removed before the first
  154. * stable release.
  155. */
  156. public function isTranslating();
  157. /**
  158. * Notifies the translation handler that its entity is being translated.
  159. *
  160. * @param $translating
  161. * A boolean value.
  162. *
  163. * @deprecated This is no longer used and will be removed before the first
  164. * stable release.
  165. */
  166. public function setTranslating($translating);
  167. /**
  168. * Return TRUE if a new revision of the entity has just been created.
  169. */
  170. public function isRevision();
  171. /**
  172. * Return TRUE if the entity type supports revisions.
  173. */
  174. public function isRevisionable();
  175. /**
  176. * Replaces the wrapped entity.
  177. *
  178. * @param $entity
  179. * The entity to be translated.
  180. */
  181. public function setEntity($entity);
  182. /**
  183. * Returns the wrapped entity.
  184. *
  185. * @param return
  186. * The wrapped entity.
  187. */
  188. public function getEntity();
  189. /**
  190. * Returns the wrapped entity type.
  191. *
  192. * @param return
  193. * The wrapped entity type.
  194. */
  195. public function getEntityType();
  196. /**
  197. * Checks that the wrapped entity matches the give entity
  198. *
  199. * @param $entity_type
  200. * The type of the entity to be matched.
  201. * @param $entity
  202. * The entity to be matched.
  203. */
  204. public function isWrappedEntity($entity_type, $entity);
  205. /**
  206. * Sets the translation update status.
  207. *
  208. * @param $outdated
  209. * A boolean value.
  210. */
  211. public function setOutdated($outdated);
  212. /**
  213. * Returns the base path for the current entity.
  214. *
  215. * This path will be prepended to the URL of any administration page.
  216. *
  217. * @return
  218. * A string to be used as a URL path prefix.
  219. */
  220. public function getBasePath();
  221. /**
  222. * Returns the path of the entity edit form.
  223. *
  224. * @param $langcode
  225. * (optional) The language the edit form should be presented in.
  226. */
  227. public function getEditPath($langcode = NULL);
  228. /**
  229. * Returns the path of the translation overview page.
  230. */
  231. public function getTranslatePath();
  232. /**
  233. * Returns the path of the entity view page.
  234. */
  235. public function getViewPath();
  236. /**
  237. * Returns the active path scheme.
  238. */
  239. public function getPathScheme();
  240. /**
  241. * Changes the active path scheme.
  242. *
  243. * @param $scheme
  244. * The new path scheme.
  245. */
  246. public function setPathScheme($scheme);
  247. /**
  248. * Initializes the most suited path scheme based on the given path.
  249. *
  250. * @param $path
  251. * (optional) The path to match the defined path schemes against. Defaults
  252. * to the current path.
  253. *
  254. * @return
  255. * The matched path scheme key.
  256. */
  257. public function initPathScheme($path = NULL);
  258. /**
  259. * A string allowing the user to identify the entity.
  260. */
  261. public function getLabel();
  262. /**
  263. * Checks if the user can perform the given operation on the wrapped entity.
  264. *
  265. * @param $op
  266. * The operation to be performed.
  267. *
  268. * @return
  269. * TRUE if the user is allowed to perform the given operation, FALSE
  270. * otherwise.
  271. */
  272. public function getAccess($op);
  273. /**
  274. * Checks if a user is allowed to edit the given translation.
  275. */
  276. public function getTranslationAccess($langcode);
  277. /**
  278. * Checks if a user is allowed to edit shared fields on the active form.
  279. */
  280. public function getSharedFieldsAccess();
  281. /**
  282. * Return TRUE if the entity supports URL aliasing.
  283. */
  284. public function isAliasEnabled();
  285. /**
  286. * Sets the source language for the translation being created.
  287. */
  288. public function setSourceLanguage($langcode);
  289. /**
  290. * Retrieves the source language for the translation being created.
  291. */
  292. public function getSourceLanguage();
  293. /**
  294. * Returns TRUE if a new entity is currently wrapped.
  295. */
  296. public function isNewEntity();
  297. /**
  298. * Returns TRUE whether we are displying an entity form.
  299. */
  300. public function isEntityForm();
  301. /**
  302. * Performs the needed alterations to the entity form.
  303. */
  304. public function entityForm(&$form, &$form_state);
  305. /**
  306. * Adds an language selection widget to the entity form.
  307. */
  308. public function entityFormLanguageWidget(&$form, &$form_state);
  309. /**
  310. * Performs submission tasks on the submitted entity language.
  311. */
  312. public function entityFormLanguageWidgetSubmit($form, &$form_state);
  313. /**
  314. * Handle shared form elements.
  315. */
  316. public function entityFormSharedElements(&$element);
  317. /**
  318. * Performs validation tasks on the submitted entity forms.
  319. */
  320. public function entityFormValidate($form, &$form_state);
  321. /**
  322. * Performs submission tasks on the submitted entity forms.
  323. */
  324. public function entityFormSubmit($form, &$form_state);
  325. /**
  326. * Alters the local tasks render array to populate the language tabs.
  327. */
  328. public function localTasksAlter(&$data, $router_item, $root_path);
  329. }
  330. /**
  331. * Class implementing the default entity translation behaviours.
  332. */
  333. class EntityTranslationDefaultHandler implements EntityTranslationHandlerInterface {
  334. protected $entityType;
  335. protected $entity;
  336. protected $entityInfo;
  337. protected $entityId;
  338. protected $bundle;
  339. protected $revisionable;
  340. /**
  341. * The translation handler factory.
  342. *
  343. * @var EntityTranslationHandlerFactory
  344. */
  345. protected $factory;
  346. /**
  347. * The translation handler hierarchy storage.
  348. *
  349. * @var array
  350. */
  351. protected $children = array();
  352. protected $entityForm;
  353. protected $translating;
  354. protected $outdated;
  355. protected $activeLanguage;
  356. protected $sourceLanguage;
  357. protected $pathScheme;
  358. protected $pathWildcard;
  359. protected $basePath;
  360. protected $editPath;
  361. protected $translatePath;
  362. protected $viewPath;
  363. protected $routerMap;
  364. /**
  365. * Initializes an instance of the translation handler.
  366. *
  367. * @param $entity_type
  368. * The type of the entity being wrapped.
  369. * @param $entity_info
  370. * The entity information for the entity being wrapped.
  371. * @param $entity
  372. * The entity being wrapped.
  373. */
  374. public function __construct($entity_type, $entity_info, $entity) {
  375. $this->entityType = $entity_type;
  376. $this->entityInfo = $entity_info;
  377. $this->setEntity($entity);
  378. $this->entityForm = FALSE;
  379. $this->translating = FALSE;
  380. $this->outdated = FALSE;
  381. $this->activeLanguage = FALSE;
  382. $this->sourceLanguage = FALSE;
  383. $this->pathScheme = 'default';
  384. $this->routerMap = array();
  385. if (entity_translation_enabled($entity_type)) {
  386. $this->initPathVariables();
  387. }
  388. }
  389. /**
  390. * Read the translation data from the storage.
  391. */
  392. public static function loadMultiple($entity_type, $entities) {
  393. $entity_info = entity_get_info($entity_type);
  394. if (isset($entity_info['entity keys']['translations'])){
  395. $translations_key = $entity_info['entity keys']['translations'];
  396. }
  397. else {
  398. // If no translations key is defined we cannot proceed.
  399. return;
  400. }
  401. $revisionable = self::isEntityTypeRevisionable($entity_type);
  402. $revisions_ids = array();
  403. foreach ($entities as $id => $entity) {
  404. $entities[$id]->{$translations_key} = self::emptyTranslations();
  405. if ($revisionable) {
  406. list(, $revisions_id,) = entity_extract_ids($entity_type, $entity);
  407. $revisions_ids[$id] = $revisions_id;
  408. }
  409. }
  410. $table = $revisionable ? 'entity_translation_revision' : 'entity_translation';
  411. $query = db_select($table, 'et')
  412. ->fields('et')
  413. ->condition('entity_type', $entity_type);
  414. if (!$revisionable) {
  415. $query->condition('entity_id', array_keys($entities), 'IN');
  416. }
  417. else {
  418. $query->condition('revision_id', $revisions_ids, 'IN');
  419. }
  420. $results = $query->execute();
  421. foreach ($results as $row) {
  422. $id = $row->entity_id;
  423. $entities[$id]->{$translations_key}->data[$row->language] = (array) $row;
  424. // Only the original translation has an empty source.
  425. if (empty($row->source)) {
  426. $entities[$id]->{$translations_key}->original = $row->language;
  427. }
  428. }
  429. }
  430. /**
  431. * Returns the localized links for the given path.
  432. */
  433. public static function languageSwitchLinks($path) {
  434. $links = language_negotiation_get_switch_links(LANGUAGE_TYPE_CONTENT, $path);
  435. if (empty($links)) {
  436. // If content language is set up to fall back to the interface language,
  437. // then there will be no switch links for LANGUAGE_TYPE_CONTENT, ergo we
  438. // also need to use interface switch links.
  439. $links = language_negotiation_get_switch_links(LANGUAGE_TYPE_INTERFACE, $path);
  440. }
  441. return $links;
  442. }
  443. /**
  444. * @see EntityTranslationHandlerInterface::setFactory()
  445. */
  446. public function setFactory(EntityTranslationHandlerFactory $factory) {
  447. $this->factory = $factory;
  448. }
  449. /**
  450. * @see EntityTranslationHandlerInterface::addChild()
  451. */
  452. public function addChild($entity_type, $entity) {
  453. if (!empty($this->factory)) {
  454. $handler = $this->factory->getHandler($entity_type, $entity);
  455. $handler->setActiveLanguage($this->getActiveLanguage());
  456. $handler->setSourceLanguage($this->getSourceLanguage());
  457. // Avoid registering more than one child handler for each entity.
  458. $hid = $this->factory->getHandlerId($entity_type, $entity);
  459. $this->children[$hid] = $handler;
  460. }
  461. }
  462. /**
  463. * @see EntityTranslationHandlerInterface::removeChild()
  464. */
  465. public function removeChild($entity_type, $entity) {
  466. if (!empty($this->factory)) {
  467. $hid = $this->factory->getHandlerId($entity_type, $entity);
  468. unset($this->children[$hid]);
  469. }
  470. }
  471. /**
  472. * Proxies the specified method invocation to a child translation handler.
  473. */
  474. protected function notifyChildren($method, $args) {
  475. foreach ($this->children as $handler) {
  476. call_user_func_array(array($handler, $method), $args);
  477. }
  478. }
  479. /**
  480. * @see EntityTranslationHandlerInterface::loadTranslations()
  481. */
  482. public function loadTranslations() {
  483. if (isset($this->entityId)) {
  484. $this->loadMultiple($this->entityType, array($this->entityId => $this->entity));
  485. }
  486. elseif ($translations_key = $this->getTranslationsKey()) {
  487. $this->entity->{$translations_key} = $this->emptyTranslations();
  488. }
  489. }
  490. /**
  491. * @see EntityTranslationHandlerInterface::saveTranslations()
  492. */
  493. public function saveTranslations() {
  494. $translations = $this->getTranslations();
  495. // Save current values.
  496. $this->doSaveTranslations($translations, 'entity_translation');
  497. // Save revision values.
  498. if ($this->isRevisionable()) {
  499. $this->doSaveTranslations($translations, 'entity_translation_revision', TRUE);
  500. }
  501. // The translation handler interface decouples operations on translations at
  502. // data structure level from CRUD operations. Hence hooks must be fired
  503. // after changes are actually persisted.
  504. if (!empty($translations->hook)) {
  505. // Hook info is keyed by language code so that subsequent operations at
  506. // data structure level do not cause multiple hooks for the same data to
  507. // be fired. For instance if a translation is first updated and then
  508. // deleted, only the 'delete' hook should be fired, because it is the only
  509. // change that has actually been persisted.
  510. foreach ($translations->hook as $langcode => $info) {
  511. $translation = isset($translations->data[$langcode]) ? $translations->data[$langcode] : $langcode;
  512. $data = isset($info['data']) ? $info['data'] : NULL;
  513. module_invoke_all('entity_translation_' . $info['hook'], $this->entityType, $this->entity, $translation, $data);
  514. // Provide Rules events integration if available.
  515. if (module_exists('rules')) {
  516. // Pass the entity as a wrapped one since rules can't do it for us
  517. // when using the variable type 'entity'.
  518. rules_invoke_event('entity_translation_' . $info['hook'], $this->entityType, entity_metadata_wrapper($this->entityType, $this->entity), $translation, $data);
  519. }
  520. }
  521. // Avoid firing hooks more than once for the same changes.
  522. $translations->hook = array();
  523. }
  524. }
  525. /**
  526. * Saves entity translation records to the storage.
  527. */
  528. protected function doSaveTranslations($translations, $table, $revision = FALSE) {
  529. // Delete and insert, rather than update, in case a value was added.
  530. $query = db_delete($table)
  531. ->condition('entity_type', $this->entityType)
  532. ->condition('entity_id', $this->entityId);
  533. // If we are storing translations for the current revision or we are
  534. // deleting the entity we should remove all translation data.
  535. $langcode = $translations->original;
  536. $hook = isset($translations->hook) ? $translations->hook : array();
  537. if ($revision && $this->isRevisionable() && (empty($hook[$langcode]['hook']) || $hook[$langcode]['hook'] != 'delete')) {
  538. $query->condition('revision_id', $this->revisionId);
  539. }
  540. $query->execute();
  541. if (count($translations->data)) {
  542. $columns = array('entity_type', 'entity_id', 'revision_id', 'language', 'source', 'uid', 'status', 'translate', 'created', 'changed');
  543. $query = db_insert($table)->fields($columns);
  544. // These values should override the translation ones as they are not
  545. // supposed to change.
  546. $overrides = array(
  547. 'entity_type' => $this->entityType,
  548. 'entity_id' => $this->entityId,
  549. 'revision_id' => $this->isRevisionable() ? $this->revisionId : $this->entityId,
  550. );
  551. // These instead are just defaults.
  552. $defaults = array(
  553. 'source' => '',
  554. 'uid' => $GLOBALS['user']->uid,
  555. 'translate' => 0,
  556. 'status' => 0,
  557. 'created' => REQUEST_TIME,
  558. 'changed' => REQUEST_TIME,
  559. );
  560. foreach ($translations->data as $translation) {
  561. $translation = $overrides + $translation + $defaults;
  562. $query->values($translation);
  563. }
  564. $query->execute();
  565. }
  566. }
  567. /**
  568. * @see EntityTranslationHandlerInterface::getTranslations()
  569. */
  570. public function getTranslations() {
  571. if ($translations_key = $this->getTranslationsKey()) {
  572. // Lazy load translations if for some reason the wrapped entity did not go
  573. // through hook_entity_load().
  574. if (!isset($this->entity->{$translations_key})) {
  575. $this->loadTranslations();
  576. }
  577. return $this->entity->{$translations_key};
  578. }
  579. return self::emptyTranslations();
  580. }
  581. /**
  582. * @see EntityTranslationHandlerInterface::setTranslation()
  583. */
  584. public function setTranslation($translation, $values = NULL) {
  585. if (isset($translation['source']) && $translation['language'] == $translation['source']) {
  586. throw new Exception('Invalid translation language');
  587. }
  588. // $args will be used later on in a call to notifyChildren(). We need
  589. // to call func_get_args() before any modifications to the function's
  590. // arguments take place. This is due to changes in PHP 7.0 and onwards.
  591. // @see http://php.net/manual/en/function.func-get-args.php#refsect1-function.func-get-args-notes
  592. $args = func_get_args();
  593. $translations = $this->getTranslations();
  594. $langcode = $translation['language'];
  595. $this->setTranslating(TRUE);
  596. if (isset($translations->data[$langcode])) {
  597. $translation = array_merge($translations->data[$langcode], $translation);
  598. $translation['changed'] = REQUEST_TIME;
  599. // If a newly inserted translation has not been stored yet do not fire an
  600. // update hook.
  601. $hook = empty($translations->hook[$langcode]['hook']) ? 'update' : $translations->hook[$langcode]['hook'];
  602. }
  603. else {
  604. $hook = 'insert';
  605. }
  606. // Store the translation data.
  607. $translations->data[$langcode] = $translation;
  608. // Keep track that the translation has been inserted or updated.
  609. $translations->hook[$langcode] = array('hook' => $hook, 'data' => $values);
  610. if (is_array($values)) {
  611. // Update field translations.
  612. foreach (field_info_instances($this->entityType, $this->bundle) as $instance) {
  613. $field_name = $instance['field_name'];
  614. $field = field_info_field($field_name);
  615. if ($field['translatable'] && isset($values[$field_name][$langcode])) {
  616. $this->entity->{$field_name}[$langcode] = $values[$field_name][$langcode];
  617. }
  618. }
  619. }
  620. $this->notifyChildren(__FUNCTION__, $args);
  621. }
  622. /**
  623. * @see EntityTranslationHandlerInterface::removeTranslation()
  624. */
  625. public function removeTranslation($langcode) {
  626. $translations_key = $this->getTranslationsKey();
  627. if (empty($translations_key)) {
  628. return;
  629. }
  630. $hook_info = array('hook' => 'delete');
  631. if (!empty($langcode)) {
  632. unset($this->entity->{$translations_key}->data[$langcode]);
  633. // Keep track that the current translation has been removed.
  634. $this->entity->{$translations_key}->hook[$langcode] = $hook_info;
  635. }
  636. elseif (!empty($this->entity->{$translations_key}->data)) {
  637. $keys = array_keys($this->entity->{$translations_key}->data);
  638. $values = array_fill(0, count($keys), $hook_info);
  639. // Keep track that the all translations have been removed.
  640. $this->entity->{$translations_key}->hook = array_combine($keys, $values);
  641. // Actually remove translations.
  642. $this->entity->{$translations_key}->data = array();
  643. }
  644. // Remove field translations.
  645. foreach (field_info_instances($this->entityType, $this->bundle) as $instance) {
  646. $field_name = $instance['field_name'];
  647. $field = field_info_field($field_name);
  648. if ($field['translatable']) {
  649. if (!empty($langcode)) {
  650. $this->entity->{$field_name}[$langcode] = array();
  651. }
  652. else {
  653. $this->entity->{$field_name} = array();
  654. }
  655. }
  656. }
  657. // Clear the cache for this entity.
  658. entity_get_controller($this->entityType)->resetCache(array($this->getEntityId()));
  659. }
  660. /**
  661. * @see EntityTranslationHandlerInterface::initTranslations()
  662. */
  663. public function initTranslations() {
  664. $langcode = $this->getLanguage();
  665. if (!empty($langcode)) {
  666. $translation = array('language' => $langcode, 'status' => 1);
  667. $this->setTranslation($translation);
  668. $this->setOriginalLanguage($langcode);
  669. }
  670. }
  671. /**
  672. * @see EntityTranslationHandlerInterface::updateTranslations()
  673. */
  674. public function updateTranslations() {
  675. $langcode = $this->getLanguage();
  676. // Only create a translation on edit if the translation set is empty:
  677. // the entity might have been created with language set to "language
  678. // neutral".
  679. if (empty($this->getTranslations()->data)) {
  680. $this->initTranslations();
  681. }
  682. elseif (!empty($langcode)) {
  683. $this->setOriginalLanguage($langcode);
  684. }
  685. }
  686. /**
  687. * @see EntityTranslationHandlerInterface::removeTranslations()
  688. */
  689. public function removeTranslations() {
  690. $this->removeTranslation(NULL);
  691. }
  692. /**
  693. * @see EntityTranslationHandlerInterface::removeRevisionTranslations()
  694. */
  695. public function removeRevisionTranslations() {
  696. $translations_key = $this->getTranslationsKey();
  697. $keys = array_keys($this->entity->{$translations_key}->data);
  698. $values = array_fill(0, count($keys), array('hook' => 'delete_revision'));
  699. $this->removeTranslation(NULL);
  700. $this->entity->{$translations_key}->hook = array_combine($keys, $values);
  701. }
  702. /**
  703. * @see EntityTranslationHandlerInterface::initOriginalTranslation()
  704. */
  705. public function initOriginalTranslation() {
  706. $fixed = FALSE;
  707. $translations = $this->getTranslations();
  708. foreach (field_info_instances($this->entityType, $this->bundle) as $instance) {
  709. $field_name = $instance['field_name'];
  710. $field = field_info_field($field_name);
  711. $langcode = count($this->entity->{$field_name}) == 1 ? key($this->entity->{$field_name}) : $translations->original;
  712. if ($langcode == LANGUAGE_NONE && $field['translatable']) {
  713. $this->entity->{$field_name}[$translations->original] = $this->entity->{$field_name}[$langcode];
  714. $this->entity->{$field_name}[$langcode] = array();
  715. $fixed = TRUE;
  716. }
  717. }
  718. return $fixed;
  719. }
  720. /**
  721. * @see EntityTranslationHandlerInterface::getLanguage()
  722. */
  723. public function getLanguage() {
  724. if (!empty($this->entityInfo['entity keys']['language'])) {
  725. $language_key = $this->entityInfo['entity keys']['language'];
  726. if (!empty($this->entity->{$language_key})) {
  727. return $this->entity->{$language_key};
  728. }
  729. }
  730. $translations = $this->getTranslations();
  731. if (!empty($translations->original)) {
  732. return $translations->original;
  733. }
  734. else {
  735. // When we are creating an entity and no language is specified fall back
  736. // to the default language for the current entity and bundle.
  737. return $this->getDefaultLanguage();
  738. }
  739. }
  740. /**
  741. * {@inheritdoc}
  742. */
  743. public function setActiveLanguage($langcode) {
  744. // @todo To fully preserve BC, we proxy the call to the deprecated
  745. // ::setFormLanguage method. This will keep things working even when it
  746. // has been overridden. Inline its implementation here upon removal.
  747. $this->setFormLanguage($langcode);
  748. }
  749. /**
  750. * {@inheritdoc}
  751. */
  752. public function getActiveLanguage() {
  753. // @todo To fully preserve BC, we proxy the call to the deprecated
  754. // ::getFormLanguage method. This will keep things working even when it
  755. // has been overridden. Inline its implementation here upon removal.
  756. return $this->getFormLanguage();
  757. }
  758. /**
  759. * {@inheritdoc}
  760. */
  761. public function setFormLanguage($langcode) {
  762. $this->activeLanguage = $langcode;
  763. $args = func_get_args();
  764. $this->notifyChildren(__FUNCTION__, $args);
  765. }
  766. /**
  767. * {@inheritdoc}
  768. */
  769. public function getFormLanguage() {
  770. if (!empty($this->activeLanguage)) {
  771. return $this->activeLanguage;
  772. }
  773. // For new entities the active language should match the default language.
  774. // The language stored with the entity itself (for example, $node->language)
  775. // may not be reliable since the function creating the entity object will
  776. // not know which language "Entity Translation" is configured to create the
  777. // entity in.
  778. elseif ($this->isNewEntity()) {
  779. return $this->getDefaultLanguage();
  780. }
  781. else {
  782. return $this->getLanguage();
  783. }
  784. }
  785. /**
  786. * @see EntityTranslationHandlerInterface::getLanguageKey()
  787. */
  788. public function getLanguageKey() {
  789. return !empty($this->entityInfo['entity keys']['language']) ? $this->entityInfo['entity keys']['language'] : 'language';
  790. }
  791. /**
  792. * @see EntityTranslationHandlerInterface::getDefaultLanguage()
  793. */
  794. public function getDefaultLanguage() {
  795. $settings = variable_get('entity_translation_settings_' . $this->entityType . '__' . $this->bundle, array());
  796. if (!empty($settings['default_language'])) {
  797. switch ($settings['default_language']) {
  798. case ENTITY_TRANSLATION_LANGUAGE_DEFAULT:
  799. $langcode = language_default()->language;
  800. break;
  801. case ENTITY_TRANSLATION_LANGUAGE_CURRENT:
  802. $langcode = $GLOBALS[LANGUAGE_TYPE_CONTENT]->language;
  803. break;
  804. case ENTITY_TRANSLATION_LANGUAGE_AUTHOR:
  805. $langcode = $GLOBALS['user']->language;
  806. break;
  807. default:
  808. // An actual language code has been explicitly configured.
  809. $langcode = $settings['default_language'];
  810. }
  811. }
  812. else {
  813. // Fall back to the default language to keep backward compatibility.
  814. $langcode = language_default()->language;
  815. }
  816. return $langcode;
  817. }
  818. /**
  819. * @see EntityTranslationHandlerInterface::setOriginalLanguage()
  820. */
  821. public function setOriginalLanguage($langcode) {
  822. $translations = $this->getTranslations();
  823. if (!isset($translations->original) || $translations->original != $langcode) {
  824. if (isset($translations->original)) {
  825. $translations->data[$langcode] = $translations->data[$translations->original];
  826. $translations->data[$langcode]['language'] = $langcode;
  827. unset($translations->data[$translations->original]);
  828. }
  829. $translations->original = $langcode;
  830. $args = func_get_args();
  831. $this->notifyChildren(__FUNCTION__, $args);
  832. }
  833. }
  834. /**
  835. * @see EntityTranslationHandlerInterface::isTranslating()
  836. */
  837. public function isTranslating() {
  838. return $this->translating;
  839. }
  840. /**
  841. * @see EntityTranslationHandlerInterface::setTranslating()
  842. */
  843. public function setTranslating($translating) {
  844. $this->translating = $translating;
  845. }
  846. /**
  847. * @see EntityTranslationHandlerInterface::isRevision()
  848. */
  849. public function isRevision() {
  850. return FALSE;
  851. }
  852. /**
  853. * @see EntityTranslationHandlerInterface::isRevisionable()
  854. */
  855. public function isRevisionable() {
  856. $result = FALSE;
  857. if (!isset($this->revisionable)) {
  858. $result = self::isEntityTypeRevisionable($this->entityType);
  859. }
  860. return $result;
  861. }
  862. /**
  863. * Returns whether the entity type is revisionable.
  864. */
  865. public static function isEntityTypeRevisionable($entity_type) {
  866. $entity_info = entity_get_info($entity_type);
  867. return variable_get('entity_translation_revision_enabled', FALSE) && !empty($entity_info['entity keys']['revision']);
  868. }
  869. /**
  870. * @see EntityTranslationHandlerInterface::setEntity()
  871. */
  872. public function setEntity($entity) {
  873. $this->entity = $entity;
  874. // Ensure translations data is populated.
  875. $translations_key = $this->getTranslationsKey();
  876. if ($translations_key && !isset($this->entity->{$translations_key})) {
  877. $this->entity->{$translations_key} = self::emptyTranslations();
  878. }
  879. // Update entity properties.
  880. list($this->entityId, $this->revisionId, $this->bundle) = entity_extract_ids($this->entityType, $this->entity);
  881. // Initialize the handler id if needed.
  882. if (!empty($this->factory)) {
  883. $this->factory->getHandlerId($this->entityType, $entity);
  884. }
  885. }
  886. /**
  887. * @see EntityTranslationHandlerInterface::getEntity()
  888. */
  889. public function getEntity() {
  890. return $this->entity;
  891. }
  892. /**
  893. * @see EntityTranslationHandlerInterface::getEntityType()
  894. */
  895. public function getEntityType() {
  896. return $this->entityType;
  897. }
  898. /**
  899. * @see EntityTranslationHandlerInterface::isWrappedEntity()
  900. */
  901. public function isWrappedEntity($entity_type, $entity) {
  902. list($id,,) = entity_extract_ids($entity_type, $entity);
  903. return $entity_type == $this->entityType && $id == $this->entityId;
  904. }
  905. /**
  906. * @see EntityTranslationHandlerInterface::setOutdated()
  907. */
  908. public function setOutdated($outdated) {
  909. if ($outdated) {
  910. $translations = $this->getTranslations();
  911. foreach ($translations->data as $langcode => &$translation) {
  912. if ($langcode != $this->getActiveLanguage()) {
  913. $translation['translate'] = 1;
  914. }
  915. }
  916. $args = func_get_args();
  917. $this->notifyChildren(__FUNCTION__, $args);
  918. }
  919. }
  920. /**
  921. * @see EntityTranslationHandlerInterface::getBasePath()
  922. */
  923. public function getBasePath() {
  924. return $this->basePath;
  925. }
  926. /**
  927. * @see EntityTranslationHandlerInterface::getEditPath()
  928. */
  929. public function getEditPath($langcode = NULL) {
  930. return empty($this->editPath) ? FALSE : (empty($langcode) ? $this->editPath : $this->editPath . '/' . $langcode);
  931. }
  932. /**
  933. * @see EntityTranslationHandlerInterface::getTranslatePath()
  934. */
  935. public function getTranslatePath() {
  936. return $this->translatePath;
  937. }
  938. /**
  939. * @see EntityTranslationHandlerInterface::getViewPath()
  940. */
  941. public function getViewPath() {
  942. return $this->viewPath;
  943. }
  944. /**
  945. * @see EntityTranslationHandlerInterface::getPathScheme()
  946. */
  947. public function getPathScheme() {
  948. return $this->pathScheme;
  949. }
  950. /**
  951. * @see EntityTranslationHandlerInterface::setPathScheme()
  952. */
  953. public function setPathScheme($scheme) {
  954. if ($scheme != $this->pathScheme) {
  955. $this->pathScheme = $scheme;
  956. $this->initPathVariables();
  957. }
  958. }
  959. /**
  960. * @see EntityTranslationHandlerInterface::initPathScheme()
  961. */
  962. public function initPathScheme($path = NULL) {
  963. $scheme = 'default';
  964. // If only one path scheme is defined no need to find one.
  965. if (count($this->entityInfo['translation']['entity_translation']['path schemes']) > 1) {
  966. $item = menu_get_item($path);
  967. if (!empty($item['path'])) {
  968. $current_path_scheme = $this->findMatchingPathScheme($item['path']);
  969. if ($current_path_scheme) {
  970. $scheme = $current_path_scheme;
  971. $this->routerMap = $item['original_map'];
  972. }
  973. }
  974. }
  975. $this->setPathScheme($scheme);
  976. return $scheme;
  977. }
  978. /**
  979. * Find a path scheme matching the given path.
  980. *
  981. * @param $router_path
  982. * The path to match against.
  983. *
  984. * @return
  985. * The key of the path scheme if found, FALSE otherwise.
  986. */
  987. protected function findMatchingPathScheme($router_path) {
  988. $path_keys = array_flip(array('base path', 'view path', 'edit path', 'translate path'));
  989. foreach ($this->entityInfo['translation']['entity_translation']['path schemes'] as $delta => $scheme) {
  990. // Construct regular expression pattern for determining whether any path
  991. // in the current scheme matches the current request path.
  992. $path_elements = array_intersect_key($scheme, $path_keys);
  993. // Add additional path elements which were added during
  994. // entity_translation_menu_alter().
  995. if (isset($path_elements['edit path'])) {
  996. $path_elements[] = $path_elements['edit path'] . '/%entity_translation_language';
  997. $path_elements[] = $path_elements['edit path'] . '/add/%entity_translation_language/%entity_translation_language';
  998. }
  999. if (isset($path_elements['translate path'])) {
  1000. $path_elements[] = $path_elements['translate path'] . '/delete/%entity_translation_language';
  1001. }
  1002. // Replace wildcards with % for matching parameters.
  1003. $path_elements = array_flip(preg_replace('|%[^/]+|', '%', $path_elements));
  1004. if (isset($path_elements[$router_path])) {
  1005. return $delta;
  1006. }
  1007. }
  1008. return FALSE;
  1009. }
  1010. /**
  1011. * @see EntityTranslationHandlerInterface::getLabel()
  1012. */
  1013. public function getLabel() {
  1014. if (($label = entity_label($this->entityType, $this->entity)) !== FALSE) {
  1015. return $label;
  1016. }
  1017. else {
  1018. return "{$this->entityType}:{$this->getEntityId()}" ;
  1019. }
  1020. }
  1021. /**
  1022. * @see EntityTranslationHandlerInterface::getAccess()
  1023. */
  1024. public function getAccess($op) {
  1025. return TRUE;
  1026. }
  1027. /**
  1028. * @see EntityTranslationHandlerInterface::getTranslationAccess()
  1029. */
  1030. public function getTranslationAccess($langcode) {
  1031. return !empty($this->entityInfo['translation']['entity_translation']['skip original values access']) || !entity_translation_workflow_enabled() || $langcode != $this->getLanguage() || user_access('edit original values') || user_access("edit {$this->entityType} original values");
  1032. }
  1033. /**
  1034. * @see EntityTranslationHandlerInterface::getSharedFieldsAccess()
  1035. */
  1036. public function getSharedFieldsAccess() {
  1037. $settings = entity_translation_settings($this->entityType, $this->bundle);
  1038. return ($settings['shared_fields_original_only'] == FALSE || $this->getLanguage() == $this->getActiveLanguage()) &&
  1039. (!entity_translation_workflow_enabled() || user_access('edit translation shared fields') || user_access("edit {$this->entityType} translation shared fields"));
  1040. }
  1041. /**
  1042. * @see EntityTranslationHandlerInterface::isAliasEnabled()
  1043. */
  1044. public function isAliasEnabled() {
  1045. return !empty($this->entityInfo['translation']['entity_translation']['alias']);
  1046. }
  1047. /**
  1048. * @see EntityTranslationHandlerInterface::setSourceLanguage()
  1049. */
  1050. public function setSourceLanguage($langcode) {
  1051. $this->sourceLanguage = $langcode;
  1052. $args = func_get_args();
  1053. $this->notifyChildren(__FUNCTION__, $args);
  1054. }
  1055. /**
  1056. * @see EntityTranslationHandlerInterface::getSourceLanguage()
  1057. */
  1058. public function getSourceLanguage() {
  1059. return $this->sourceLanguage;
  1060. }
  1061. /**
  1062. * @see EntityTranslationHandlerInterface::isNewEntity()
  1063. */
  1064. public function isNewEntity() {
  1065. $id = $this->getEntityId();
  1066. return empty($id);
  1067. }
  1068. /**
  1069. * @see EntityTranslationHandlerInterface::isEntityForm()
  1070. */
  1071. public function isEntityForm() {
  1072. return $this->entityForm;
  1073. }
  1074. /**
  1075. * @see EntityTranslationHandlerInterface::entityForm()
  1076. */
  1077. public function entityForm(&$form, &$form_state) {
  1078. $this->entityForm = TRUE;
  1079. $translations = $this->getTranslations();
  1080. $form_langcode = $this->getActiveLanguage();
  1081. $langcode = $this->getLanguage();
  1082. $is_translation = $this->isTranslationForm();
  1083. $new_translation = !isset($translations->data[$form_langcode]);
  1084. $no_translations = count($translations->data) < 2;
  1085. $languages = language_list();
  1086. $access = user_access('translate any entity') || user_access("translate $this->entityType entities");
  1087. // Store contextual information in the form state.
  1088. $form_state['entity_translation']['form_langcode'] = $form_langcode;
  1089. $form_state['entity_translation']['source_langcode'] = $this->getSourceLanguage();
  1090. // The only way to determine whether we are editing the original values is
  1091. // comparing form language and entity language. Since a language change
  1092. // might render impossible to make this check after form submission, we
  1093. // store the related information here.
  1094. $form_state['entity_translation']['is_translation'] = $is_translation;
  1095. // Adjust page title to specify the current language being edited, if we
  1096. // have at least one translation.
  1097. if ($form_langcode != LANGUAGE_NONE && (!$no_translations || $new_translation)) {
  1098. drupal_set_title($this->entityFormTitle() . ' [' . t($languages[$form_langcode]->name) . ']', PASS_THROUGH);
  1099. }
  1100. // Display source language selector only if we are creating a new
  1101. // translation and there are at least two translations available.
  1102. if (!$no_translations && $new_translation) {
  1103. $form['source_language'] = array(
  1104. '#type' => 'fieldset',
  1105. '#title' => t('Source language'),
  1106. '#collapsible' => TRUE,
  1107. '#collapsed' => TRUE,
  1108. '#tree' => TRUE,
  1109. '#weight' => -100,
  1110. '#access' => $access,
  1111. '#multilingual' => TRUE,
  1112. 'language' => array(
  1113. '#type' => 'select',
  1114. '#default_value' => $this->getSourceLanguage(),
  1115. '#options' => array(),
  1116. ),
  1117. 'submit' => array(
  1118. '#type' => 'submit',
  1119. '#value' => t('Change'),
  1120. '#submit' => array('entity_translation_entity_form_source_language_submit'),
  1121. ),
  1122. );
  1123. foreach (language_list() as $language) {
  1124. if (isset($translations->data[$language->language])) {
  1125. $form['source_language']['language']['#options'][$language->language] = t($language->name);
  1126. }
  1127. }
  1128. }
  1129. // Add the entity language switcher.
  1130. $this->entityFormLanguageWidget($form, $form_state);
  1131. if ($is_translation && isset($form['actions']['delete'])) {
  1132. // Replace the delete button with the delete translation one.
  1133. if (!$new_translation) {
  1134. $weight = 100;
  1135. foreach (array('delete', 'submit') as $key) {
  1136. if (isset($form['actions'][$key]['weight'])) {
  1137. $weight = $form['actions'][$key]['weight'];
  1138. break;
  1139. }
  1140. }
  1141. $form['actions']['delete_translation'] = array(
  1142. '#type' => 'submit',
  1143. '#value' => t('Delete translation'),
  1144. '#weight' => $weight,
  1145. '#submit' => array('entity_translation_entity_form_delete_translation_submit'),
  1146. );
  1147. }
  1148. // Always remove the delete button on translation forms.
  1149. unset($form['actions']['delete']);
  1150. }
  1151. // We need to display the translation tab only when there is at least one
  1152. // translation available or a new one is about to be created.
  1153. if ($new_translation || count($translations->data) > 1) {
  1154. $form['translation'] = array(
  1155. '#type' => 'fieldset',
  1156. '#title' => t('Translation'),
  1157. '#collapsible' => TRUE,
  1158. '#collapsed' => TRUE,
  1159. '#tree' => TRUE,
  1160. '#weight' => 10,
  1161. '#access' => $access,
  1162. '#multilingual' => TRUE,
  1163. );
  1164. // A new translation is enabled by default.
  1165. $status = $new_translation || $translations->data[$form_langcode]['status'];
  1166. // If there is only one published translation we cannot unpublish it,
  1167. // since there would be no content left to display. The whole entity
  1168. // should be unpublished instead, where possible.
  1169. $enabled = !$status;
  1170. if (!empty($status)) {
  1171. // A new translation is not available in the translation data hence it
  1172. // should count as one more.
  1173. $published = $new_translation;
  1174. foreach ($translations->data as $langcode => $translation) {
  1175. $published += $translation['status'];
  1176. }
  1177. $enabled = $published > 1;
  1178. }
  1179. $description = $enabled ?
  1180. t('An unpublished translation will not be visible for non-administrators.') :
  1181. t('Only this translation is published. You must publish at least one more translation to unpublish this one.');
  1182. $form['translation']['status'] = array(
  1183. '#type' => 'checkbox',
  1184. '#title' => t('This translation is published'),
  1185. '#default_value' => $status,
  1186. '#description' => $description,
  1187. '#disabled' => !$enabled,
  1188. );
  1189. $translate = !$new_translation && !empty($translations->data[$form_langcode]['translate']);
  1190. if (!$translate) {
  1191. $form['translation']['retranslate'] = array(
  1192. '#type' => 'checkbox',
  1193. '#title' => t('Flag translations as outdated'),
  1194. '#default_value' => 0,
  1195. '#description' => t('If you made a significant change, which means translations should be updated, you can flag all translations of this post as outdated. This will not change any other property of those posts, like whether they are published or not.'),
  1196. );
  1197. }
  1198. else {
  1199. $form['translation']['translate'] = array(
  1200. '#type' => 'checkbox',
  1201. '#title' => t('This translation needs to be updated'),
  1202. '#default_value' => $translate,
  1203. '#description' => t('When this option is checked, this translation needs to be updated because the source post has changed. Uncheck when the translation is up to date again.'),
  1204. '#disabled' => !$translate,
  1205. );
  1206. }
  1207. $translation_author = $new_translation ? $GLOBALS['user'] : user_load($translations->data[$form_langcode]['uid']);
  1208. $name = isset($translation_author->name) ? $translation_author->name : '';
  1209. $form['translation']['name'] = array(
  1210. '#type' => 'textfield',
  1211. '#title' => t('Authored by'),
  1212. '#maxlength' => 60,
  1213. '#autocomplete_path' => 'user/autocomplete',
  1214. '#default_value' => $name,
  1215. '#description' => t('Leave blank for %anonymous.', array('%anonymous' => variable_get('anonymous', t('Anonymous')))),
  1216. );
  1217. $date = $new_translation ? REQUEST_TIME : $translations->data[$form_langcode]['created'];
  1218. $form['translation']['created'] = array(
  1219. '#type' => 'textfield',
  1220. '#title' => t('Authored on'),
  1221. '#maxlength' => 25,
  1222. '#description' => t('Format: %time. The date format is YYYY-MM-DD and %timezone is the time zone offset from UTC. Leave blank to use the time of form submission.', array('%time' => format_date($date, 'custom', 'Y-m-d H:i:s O'), '%timezone' => format_date($date, 'custom', 'O'))),
  1223. '#default_value' => $new_translation ? '' : format_date($date, 'custom', 'Y-m-d H:i:s O'),
  1224. );
  1225. }
  1226. // If Menu translation is available translate the menu strings.
  1227. if (module_exists('entity_translation_i18n_menu')) {
  1228. $this->menuForm($form, $form_state);
  1229. }
  1230. // Process entity form submission.
  1231. $form['#submit'][] = 'entity_translation_entity_form_submit';
  1232. // This allows to intercept deletions. The check is needed because
  1233. // action-specific submit handlers prevent global ones from being called.
  1234. if (!empty($form['actions']['delete']['#submit'])) {
  1235. $form['actions']['delete']['#submit'][] = 'entity_translation_entity_form_submit';
  1236. }
  1237. }
  1238. /**
  1239. * @see EntityTranslationHandlerInterface::entityFormSharedElements()
  1240. *
  1241. * Either remove access or add a translatability clue depending on the current
  1242. * user's "edit translation shared fields" permissions.
  1243. */
  1244. public function entityFormSharedElements(&$element, $access = NULL) {
  1245. static $ignored_types, $shared_labels;
  1246. if (!isset($ignored_types)) {
  1247. $ignored_types = array_flip(array('actions', 'value', 'hidden', 'vertical_tabs', 'token'));
  1248. }
  1249. if (!isset($shared_labels)) {
  1250. $shared_labels = variable_get('entity_translation_shared_labels', TRUE);
  1251. }
  1252. if (!isset($access)) {
  1253. $access = $this->getSharedFieldsAccess();
  1254. }
  1255. foreach (element_children($element) as $key) {
  1256. if (!isset($element[$key]['#type'])) {
  1257. $this->entityFormSharedElements($element[$key], $access);
  1258. }
  1259. else {
  1260. // Ignore non-widget form elements.
  1261. if (isset($ignored_types[$element[$key]['#type']])) {
  1262. continue;
  1263. }
  1264. // Elements are considered to be non multilingual by default.
  1265. // Update #access only if it has not been set already or if we have
  1266. // explicit mlutilingual support.
  1267. if (!isset($element[$key]['#access']) || isset($element[$key]['#multilingual'])) {
  1268. $element[$key]['#access'] = (!isset($element[$key]['#access']) || $element[$key]['#access']) && ($access || !empty($element[$key]['#multilingual']));
  1269. }
  1270. // Add translatability clue for visible elements.
  1271. if ($access && $shared_labels) {
  1272. _entity_translation_element_add_callback($element[$key], '#process', 'entity_translation_element_translatability_clue');
  1273. }
  1274. }
  1275. }
  1276. }
  1277. /**
  1278. * @see EntityTranslationHandlerInterface::entityFormLanguageWidget()
  1279. */
  1280. public function entityFormLanguageWidget(&$form, &$form_state) {
  1281. if (entity_translation_enabled($this->entityType, $this->bundle)) {
  1282. $is_new = $this->isNewEntity();
  1283. $is_translation = !empty($form_state['entity_translation']['is_translation']);
  1284. $translations = $this->getTranslations();
  1285. $settings = entity_translation_settings($this->entityType, $this->bundle);
  1286. $languages = entity_translation_languages($this->entityType, $this->entity);
  1287. $options = count($translations->data) > 1 || !empty($settings['exclude_language_none']) ? array() : array(LANGUAGE_NONE => t('Language neutral'));
  1288. foreach ($languages as $langcode => $language) {
  1289. // Disable languages for existing translations, so it is not possible to
  1290. // switch this entity to some language which is already in the
  1291. // translation set.
  1292. if (!isset($translations->data[$langcode]) || empty($translations->data[$langcode]['source'])) {
  1293. $options[$langcode] = t($language->name);
  1294. }
  1295. }
  1296. $langcode = $is_new ? $this->getDefaultLanguage() : $this->getLanguage();
  1297. $language_key = $this->getLanguageKey();
  1298. $form[$language_key] = array(
  1299. '#type' => 'select',
  1300. '#title' => t('Language'),
  1301. '#default_value' => $langcode,
  1302. '#options' => $options,
  1303. '#access' => empty($settings['hide_language_selector']),
  1304. '#disabled' => $is_translation || (!$is_new && !empty($settings['lock_language'])),
  1305. '#multilingual' => TRUE,
  1306. );
  1307. if ($is_translation) {
  1308. // @todo Consider supporting the ability to change translation language.
  1309. $form[$language_key]['#title'] = t('Original language');
  1310. }
  1311. }
  1312. // Prepend an empty form element to the form array so that we can update the
  1313. // form language before any other form handler has been called.
  1314. $form = array(
  1315. 'entity_translation_entity_form_language_update' => array(
  1316. '#element_validate' => array('entity_translation_entity_form_language_update'),
  1317. '#entity_type' => $this->entityType,
  1318. ),
  1319. ) + $form;
  1320. }
  1321. /**
  1322. * Performs alterations to the menu widget if available.
  1323. */
  1324. protected function menuForm(&$form, &$form_state) {
  1325. // By default do nothing: only nodes are currently supported.
  1326. }
  1327. /**
  1328. * @see EntityTranslationHandlerInterface::entityFormValidate()
  1329. */
  1330. public function entityFormValidate($form, &$form_state) {
  1331. if (!empty($form_state['values']['translation'])) {
  1332. $values = $form_state['values']['translation'];
  1333. // Validate the "authored by" field.
  1334. if (!empty($values['name']) && !($account = user_load_by_name($values['name']))) {
  1335. form_set_error('translation][name', t('The translation authoring username %name does not exist.', array('%name' => $values['name'])));
  1336. }
  1337. // Validate the "authored on" field.
  1338. if (!empty($values['created']) && strtotime($values['created']) === FALSE) {
  1339. form_set_error('translation][created', t('You have to specify a valid translation authoring date.'));
  1340. }
  1341. }
  1342. }
  1343. /**
  1344. * Update the current form language based on the submitted value.
  1345. */
  1346. protected function updateFormLanguage($form_state) {
  1347. // Update the form language as it might have changed. We exploit the
  1348. // validation phase to be sure to act as early as possible.
  1349. $language_key = $this->getLanguageKey();
  1350. if (isset($form_state['values'][$language_key]) && !$this->isTranslationForm()) {
  1351. $langcode = $form_state['values'][$language_key];
  1352. $this->setActiveLanguage($langcode);
  1353. }
  1354. }
  1355. /**
  1356. * @see EntityTranslationHandlerInterface::entityFormLanguageWidgetSubmit()
  1357. */
  1358. public function entityFormLanguageWidgetSubmit($form, &$form_state) {
  1359. if (!entity_translation_enabled($this->entityType, $this->bundle)) {
  1360. return;
  1361. }
  1362. $this->updateFormLanguage($form_state);
  1363. $form_langcode = $this->getActiveLanguage();
  1364. foreach (field_info_instances($this->entityType, $this->bundle) as $instance) {
  1365. $field_name = $instance['field_name'];
  1366. if (isset($form[$field_name]['#language'])) {
  1367. $field = field_info_field($field_name);
  1368. $previous_langcode = $form[$field_name]['#language'];
  1369. // Handle a possible language change: new language values are inserted,
  1370. // previous ones are deleted.
  1371. if ($field['translatable'] && $previous_langcode != $form_langcode && isset($form_state['values'][$field_name][$previous_langcode])) {
  1372. $form_state['values'][$field_name][$form_langcode] = $form_state['values'][$field_name][$previous_langcode];
  1373. $form_state['values'][$field_name][$previous_langcode] = array();
  1374. }
  1375. }
  1376. }
  1377. }
  1378. /**
  1379. * @see EntityTranslationHandlerInterface::entityFormSubmit()
  1380. */
  1381. public function entityFormSubmit($form, &$form_state) {
  1382. $form_langcode = $this->getActiveLanguage();
  1383. $translations = $this->getTranslations();
  1384. $is_translation = !empty($form_state['entity_translation']['is_translation']);
  1385. $new_translation = !isset($translations->data[$form_langcode]);
  1386. $values = isset($form_state['values']['translation']) ? $form_state['values']['translation'] : array();
  1387. // Ensure every key has at least a default value. Subclasses may provide use
  1388. // entity-specific values to alter them.
  1389. $values += array(
  1390. 'status' => TRUE,
  1391. 'retranslate' => 0,
  1392. 'name' => isset($GLOBALS['user']->name) ? $GLOBALS['user']->name : '',
  1393. );
  1394. if (!isset($translations->data[$form_langcode])) {
  1395. // If we have a new translation the language is the original entity
  1396. // language.
  1397. $translation = $is_translation ? array('language' => $form_langcode, 'source' => $this->getSourceLanguage()) : array('language' => $form_langcode, 'source' => '');
  1398. }
  1399. else {
  1400. $translation = $translations->data[$form_langcode];
  1401. }
  1402. if (isset($values['translate'])) {
  1403. $translation['translate'] = intval($values['translate']);
  1404. }
  1405. else {
  1406. $this->setOutdated($values['retranslate']);
  1407. }
  1408. // Handle possible language changes for the original values.
  1409. if (!$is_translation) {
  1410. $this->setOriginalLanguage($form_langcode);
  1411. }
  1412. $translation['status'] = intval($values['status']);
  1413. $translation['uid'] = $values['name'] ? user_load_by_name($values['name'])->uid : 0;
  1414. $translation['created'] = empty($values['created']) ? REQUEST_TIME : strtotime($values['created']);
  1415. $this->setTranslation($translation);
  1416. // If no redirect has been explicitly set, go to the edit form for the
  1417. // current form language.
  1418. if ($new_translation && empty($form_state['redirect']) && !$this->isNewEntity()) {
  1419. $form_state['redirect'] = $this->getEditPath($form_langcode);
  1420. }
  1421. }
  1422. /**
  1423. * @see EntityTranslationHandlerInterface::localTasksAlter()
  1424. */
  1425. public function localTasksAlter(&$data, $router_item, $root_path) {
  1426. $translations = $this->getTranslations();
  1427. if (count($translations->data) > 0) {
  1428. $languages = language_list();
  1429. $form_langcode = $this->getActiveLanguage();
  1430. $language_tabs = array();
  1431. if ($this->getSourceLanguage()) {
  1432. foreach ($data['tabs'][1]['output'] as $index => &$add_tab) {
  1433. if ($add_tab['#link']['path'] == $root_path) {
  1434. $add_tab['#link']['title'] = $languages[$form_langcode]->name;
  1435. $add_tab['#link']['weight'] = $languages[$form_langcode]->weight;
  1436. $add_tab['#active'] = TRUE;
  1437. $add_tab['#language_tab'] = TRUE;
  1438. $language_tabs[] = $add_tab;
  1439. unset($data['tabs'][1]['output'][$index]);
  1440. break;
  1441. }
  1442. }
  1443. }
  1444. foreach ($translations->data as $langcode => $translation) {
  1445. if ($this->getTranslationAccess($langcode)) {
  1446. $links = $this->languageSwitchLinks($this->getEditPath($langcode));
  1447. $link = !empty($links->links[$langcode]) ? $links->links[$langcode] : array();
  1448. if (isset($link['href'])) {
  1449. $tab = array();
  1450. $tab['#theme'] = 'menu_local_task';
  1451. $tab['#active'] = $langcode == $form_langcode;
  1452. $tab['#language_tab'] = TRUE;
  1453. $tab['#link'] = array(
  1454. 'href' => $link['href'],
  1455. 'title' => t($languages[$langcode]->name),
  1456. 'weight' => $languages[$langcode]->weight,
  1457. 'localized_options' => $link,
  1458. ) + $router_item;
  1459. $language_tabs[] = $tab;
  1460. }
  1461. }
  1462. }
  1463. // Reorder tabs to make the add tab respect language weights.
  1464. usort($language_tabs, array($this, 'translationTabSort'));
  1465. // Merge the reordered language tabs into the second level tabs.
  1466. if (count($language_tabs) > 1) {
  1467. if (empty($data['tabs'][1])) {
  1468. $data['tabs'][1] = array('output' => array());
  1469. }
  1470. $data['tabs'][1]['output'] = array_merge($data['tabs'][1]['output'], $language_tabs);
  1471. $data['tabs'][1]['count'] = count($data['tabs'][1]['output']);
  1472. }
  1473. }
  1474. }
  1475. /**
  1476. * Helper callback. Sorts language tabs by weight.
  1477. */
  1478. protected function translationTabSort($a, $b) {
  1479. return $a['#link']['weight'] > $b['#link']['weight'];
  1480. }
  1481. /**
  1482. * Returns the title to be used for the entity form page.
  1483. *
  1484. * This may contain HTML markup and thus needs to be sanitized, since it will
  1485. * be used as page title as-is.
  1486. */
  1487. protected function entityFormTitle() {
  1488. return check_plain($this->getLabel());
  1489. }
  1490. /**
  1491. * Returns TRUE if an entity translation is being edited.
  1492. */
  1493. protected function isTranslationForm() {
  1494. return !$this->isNewEntity() && $this->getActiveLanguage() != $this->getLanguage();
  1495. }
  1496. /**
  1497. * Returns the translation object key for the wrapped entity type.
  1498. */
  1499. protected function getTranslationsKey() {
  1500. return isset($this->entityInfo['entity keys']['translations']) ? $this->entityInfo['entity keys']['translations'] : FALSE;
  1501. }
  1502. /**
  1503. * Returns the entity accessibility.
  1504. */
  1505. protected function getStatus() {
  1506. return TRUE;
  1507. }
  1508. /**
  1509. * Returns the entity identifier.
  1510. */
  1511. protected function getEntityId() {
  1512. return $this->entityId;
  1513. }
  1514. /**
  1515. * Initializes handler path variables based on the active path scheme.
  1516. *
  1517. * @throws Exception
  1518. */
  1519. protected function initPathVariables() {
  1520. if (empty($this->pathScheme) || !isset($this->entityInfo['translation']['entity_translation']['path schemes'][$this->pathScheme])) {
  1521. throw new Exception("Cannot initialize entity translation path variables (invalid path scheme).");
  1522. }
  1523. $path_scheme = $this->entityInfo['translation']['entity_translation']['path schemes'][$this->pathScheme];
  1524. $this->pathWildcard = $path_scheme['path wildcard'];
  1525. $this->basePath = isset($path_scheme['base path']) ? $this->getPathInstance($path_scheme['base path']) : FALSE;
  1526. $this->editPath = isset($path_scheme['edit path']) ? $this->getPathInstance($path_scheme['edit path']) : FALSE;
  1527. $this->translatePath = isset($path_scheme['translate path']) ? $this->getPathInstance($path_scheme['translate path']) : FALSE;
  1528. $this->viewPath = isset($path_scheme['view path']) ? $this->getPathInstance($path_scheme['view path']) : FALSE;
  1529. }
  1530. /**
  1531. * Returns an instance of the given path.
  1532. *
  1533. * @param $path
  1534. * An internal path containing the entity id wildcard.
  1535. *
  1536. * @return
  1537. * The instantiated path.
  1538. */
  1539. protected function getPathInstance($path) {
  1540. $path_segments = explode('/', $path);
  1541. foreach ($path_segments as $index => $segment) {
  1542. if ($segment == $this->pathWildcard) {
  1543. $path_segments[$index] = $this->getEntityId();
  1544. }
  1545. elseif ($segment{0} == '%' && isset($this->routerMap[$index])) {
  1546. $path_segments[$index] = $this->routerMap[$index];
  1547. }
  1548. }
  1549. return implode('/', $path_segments);
  1550. }
  1551. /**
  1552. * Returns an empty translations data structure.
  1553. */
  1554. protected static function emptyTranslations() {
  1555. return (object) array('original' => NULL, 'data' => array());
  1556. }
  1557. }