entity_translation.module 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021
  1. <?php
  2. /**
  3. * @file
  4. * Allows entities to be translated into different languages.
  5. */
  6. module_load_include('inc', 'entity_translation', 'entity_translation.node');
  7. /**
  8. * Language code identifying the site default language.
  9. */
  10. define('ENTITY_TRANSLATION_LANGUAGE_DEFAULT', 'xx-et-default');
  11. /**
  12. * Language code identifying the current content language.
  13. */
  14. define('ENTITY_TRANSLATION_LANGUAGE_CURRENT', 'xx-et-current');
  15. /**
  16. * Language code identifying the author's preferred language.
  17. */
  18. define('ENTITY_TRANSLATION_LANGUAGE_AUTHOR', 'xx-et-author');
  19. /**
  20. * Implements hook_hook_info().
  21. */
  22. function entity_translation_hook_info() {
  23. $hooks['entity_translation_insert'] = array(
  24. 'group' => 'entity_translation',
  25. );
  26. $hooks['entity_translation_update'] = array(
  27. 'group' => 'entity_translation',
  28. );
  29. $hooks['entity_translation_delete'] = array(
  30. 'group' => 'entity_translation',
  31. );
  32. return $hooks;
  33. }
  34. /**
  35. * Implements hook_module_implements_alter().
  36. */
  37. function entity_translation_module_implements_alter(&$implementations, $hook) {
  38. switch ($hook) {
  39. case 'menu_alter':
  40. case 'entity_info_alter':
  41. // Move some of our hook implementations to the end of the list.
  42. $group = $implementations['entity_translation'];
  43. unset($implementations['entity_translation']);
  44. $implementations['entity_translation'] = $group;
  45. break;
  46. }
  47. }
  48. /**
  49. * Implements hook_language_type_info_alter().
  50. */
  51. function entity_translation_language_types_info_alter(array &$language_types) {
  52. unset($language_types[LANGUAGE_TYPE_CONTENT]['fixed']);
  53. }
  54. /**
  55. * Implements hook_entity_info().
  56. */
  57. function entity_translation_entity_info() {
  58. $info = array();
  59. $info['node'] = array(
  60. 'translation' => array(
  61. 'entity_translation' => array(
  62. 'class' => 'EntityTranslationNodeHandler',
  63. 'access callback' => 'entity_translation_node_tab_access',
  64. 'access arguments' => array(1),
  65. 'admin theme' => variable_get('node_admin_theme'),
  66. 'bundle callback' => 'entity_translation_node_supported_type',
  67. 'default settings' => array(
  68. 'default_language' => LANGUAGE_NONE,
  69. 'hide_language_selector' => FALSE,
  70. ),
  71. ),
  72. ),
  73. );
  74. if (module_exists('comment')) {
  75. $info['comment'] = array(
  76. 'translation' => array(
  77. 'entity_translation' => array(
  78. 'class' => 'EntityTranslationCommentHandler',
  79. 'admin theme' => FALSE,
  80. 'bundle callback' => 'entity_translation_comment_supported_type',
  81. 'default settings' => array(
  82. 'default_language' => ENTITY_TRANSLATION_LANGUAGE_CURRENT,
  83. 'hide_language_selector' => TRUE,
  84. ),
  85. ),
  86. ),
  87. );
  88. }
  89. if (module_exists('taxonomy')) {
  90. $info['taxonomy_term'] = array(
  91. 'translation' => array(
  92. 'entity_translation' => array(
  93. 'class' => 'EntityTranslationTaxonomyTermHandler',
  94. 'base path' => 'taxonomy/term/%taxonomy_term',
  95. 'edit form' => 'term',
  96. ),
  97. ),
  98. );
  99. }
  100. $info['user'] = array(
  101. 'translation' => array(
  102. 'entity_translation' => array(
  103. 'class' => 'EntityTranslationUserHandler',
  104. 'skip original values access' => TRUE,
  105. 'skip shared fields access' => TRUE,
  106. ),
  107. ),
  108. );
  109. return $info;
  110. }
  111. /**
  112. * Processes the given path schemes and fill-in default values.
  113. */
  114. function _entity_translation_process_path_schemes($entity_type, &$et_info) {
  115. $path_scheme_keys = array_flip(array('base path', 'view path', 'edit path', 'translate path', 'path wildcard', 'admin theme', 'edit tabs'));
  116. // Insert the default path scheme into the 'path schemes' array and remove
  117. // respective elements from the entity_translation info array.
  118. $default_scheme = array_intersect_key($et_info, $path_scheme_keys);
  119. if (!empty($default_scheme)) {
  120. $et_info['path schemes']['default'] = $default_scheme;
  121. $et_info = array_diff_key($et_info, $path_scheme_keys);
  122. }
  123. // If no base path is provided we default to the common "node/%node"
  124. // pattern.
  125. if (empty($et_info['path schemes']['default']['base path'])) {
  126. $et_info['path schemes']['default']['base path'] = "$entity_type/%$entity_type";
  127. }
  128. foreach ($et_info['path schemes'] as $delta => $scheme) {
  129. // If there is a base path, then we automatically create the other path
  130. // elements based on the base path.
  131. if (!empty($scheme['base path'])) {
  132. $view_path = $scheme['base path'];
  133. $edit_path = $scheme['base path'] . '/edit';
  134. $translate_path = $scheme['base path'] . '/translate';
  135. $et_info['path schemes'][$delta] += array(
  136. 'view path' => $view_path,
  137. 'edit path' => $edit_path,
  138. 'translate path' => $translate_path,
  139. );
  140. }
  141. // Merge in default values for other scheme elements.
  142. $et_info['path schemes'][$delta] += array(
  143. 'admin theme' => TRUE,
  144. 'path wildcard' => "%$entity_type",
  145. 'edit tabs' => TRUE,
  146. );
  147. }
  148. }
  149. /**
  150. * Implements hook_entity_info_alter().
  151. */
  152. function entity_translation_entity_info_alter(&$entity_info) {
  153. // Provide defaults for translation info.
  154. foreach ($entity_info as $entity_type => $info) {
  155. if (!isset($entity_info[$entity_type]['translation']['entity_translation'])) {
  156. $entity_info[$entity_type]['translation']['entity_translation'] = array();
  157. }
  158. $et_info = &$entity_info[$entity_type]['translation']['entity_translation'];
  159. // Every fieldable entity type must have a translation handler class and
  160. // translation keys defined, no matter if it is enabled for translation or
  161. // not. As a matter of fact we might need them to correctly switch field
  162. // translatability when a field is shared across different entity types.
  163. $et_info += array('class' => 'EntityTranslationDefaultHandler');
  164. if (!isset($entity_info[$entity_type]['entity keys'])) {
  165. $entity_info[$entity_type]['entity keys'] = array();
  166. }
  167. $entity_info[$entity_type]['entity keys'] += array('translations' => 'translations');
  168. if (entity_translation_enabled($entity_type, NULL, TRUE)) {
  169. $entity_info[$entity_type]['language callback'] = 'entity_translation_language';
  170. // Process path schemes and fill-in defaults.
  171. _entity_translation_process_path_schemes($entity_type, $et_info);
  172. // Merge in default values for remaining keys.
  173. $et_info += array(
  174. 'access callback' => 'entity_translation_tab_access',
  175. 'access arguments' => array($entity_type),
  176. );
  177. // Interpret a TRUE value for the 'edit form' key as the default value.
  178. if (!isset($et_info['edit form']) || $et_info['edit form'] === TRUE) {
  179. $et_info['edit form'] = $entity_type;
  180. }
  181. }
  182. }
  183. }
  184. /**
  185. * Implements hook_menu().
  186. */
  187. function entity_translation_menu() {
  188. $items = array();
  189. $items['admin/config/regional/entity_translation'] = array(
  190. 'title' => 'Entity translation',
  191. 'description' => 'Configure which entities can be translated and enable or disable language fallback.',
  192. 'page callback' => 'drupal_get_form',
  193. 'page arguments' => array('entity_translation_admin_form'),
  194. 'access arguments' => array('administer entity translation'),
  195. 'file' => 'entity_translation.admin.inc',
  196. 'module' => 'entity_translation',
  197. );
  198. $items['admin/config/regional/entity_translation/translatable/%'] = array(
  199. 'title' => 'Confirm change in translatability.',
  200. 'description' => 'Confirmation page for changing field translatability.',
  201. 'page callback' => 'drupal_get_form',
  202. 'page arguments' => array('entity_translation_translatable_form', 5),
  203. 'access arguments' => array('toggle field translatability'),
  204. 'file' => 'entity_translation.admin.inc',
  205. );
  206. return $items;
  207. }
  208. /**
  209. * Validate the given set of path schemes and remove invalid elements.
  210. *
  211. * Each path scheme needs to fulfill the following requirements:
  212. * - The 'path wildcard' key needs to be specified.
  213. * - Every path (base/view/edit/translate) needs to contain the path wildcard.
  214. * - The following path definitions (if specified) need to match existing menu
  215. * items: 'base path', 'view path', 'edit path'.
  216. * - The 'translate path' definition needs to have an existing parent menu item.
  217. *
  218. * This function needs to be called once with a list of menu items passed as the
  219. * last parameter, before it can be used for validation.
  220. *
  221. * @param $schemes
  222. * The array of path schemes.
  223. * @param $entity_type_label
  224. * The label of the current entity type. This is used in error messages.
  225. * @param $items
  226. * A list of menu items.
  227. * @param $warnings
  228. * (optional) Displays warnings when a path scheme does not validate.
  229. */
  230. function _entity_translation_validate_path_schemes(&$schemes, $entity_type_label, $items = FALSE, $warnings = FALSE) {
  231. $paths = &drupal_static(__FUNCTION__);
  232. static $regex = '|%[^/]+|';
  233. if (!empty($items)) {
  234. // Some menu loaders in the item paths might have been altered: we need to
  235. // replace any menu loader with a plain % to check if base paths are still
  236. // compatible.
  237. $paths = array();
  238. foreach ($items as $path => $item) {
  239. $stripped_path = preg_replace($regex, '%', $path);
  240. $paths[$stripped_path] = $path;
  241. }
  242. }
  243. if (empty($schemes)) {
  244. return;
  245. }
  246. // Make sure we have a set of paths to validate the scheme against.
  247. if (empty($paths)) {
  248. // This should never happen.
  249. throw new Exception('The Entity Translation path scheme validation function has not been initialized properly.');
  250. }
  251. foreach ($schemes as $delta => &$scheme) {
  252. // Every path scheme needs to declare a path wildcard for the entity id.
  253. if (empty($scheme['path wildcard'])) {
  254. if ($warnings) {
  255. $t_args = array('%scheme' => $delta, '%entity_type' => $entity_type_label);
  256. drupal_set_message(t('Entity Translation path scheme %scheme for entities of type %entity_type does not declare a path wildcard.', $t_args), 'warning');
  257. }
  258. unset($schemes[$delta]);
  259. continue;
  260. }
  261. $wildcard = $scheme['path wildcard'];
  262. $validate_keys = array('base path' => FALSE, 'view path' => FALSE, 'edit path' => FALSE, 'translate path' => TRUE);
  263. foreach ($validate_keys as $key => $check_parent) {
  264. if (isset($scheme[$key])) {
  265. $path = $scheme[$key];
  266. $parts = explode('/', $path);
  267. $scheme[$key . ' parts'] = $parts;
  268. // Check that the path contains the path wildcard. Required for
  269. // determining the position of the entity id in the path (see
  270. // entity_translation_menu_alter()).
  271. if (!in_array($wildcard, $parts)) {
  272. if ($warnings) {
  273. $t_args = array('%path_key' => $key, '%entity_type' => $entity_type_label, '%wildcard' => $wildcard, '%path' => $path);
  274. drupal_set_message(t('Invalid %path_key defined for entities of type %entity_type: entity wildcard %wildcard not found in %path.', $t_args), 'warning');
  275. }
  276. unset($scheme[$key]);
  277. continue;
  278. }
  279. // Remove the trailing path element for paths requiring an existing
  280. // parent menu item (i.e. the "translate path").
  281. $trailing_path_element = FALSE;
  282. if ($check_parent) {
  283. $trailing_path_element = array_pop($parts);
  284. $path = implode('/', $parts);
  285. }
  286. $stripped_path = preg_replace($regex, '%', $path);
  287. if (!isset($paths[$stripped_path])) {
  288. if ($warnings) {
  289. $t_args = array('%path_key' => $key, '%entity_type' => $entity_type_label, '%path' => $path);
  290. $msg = $check_parent ?
  291. t('Invalid %path_key defined for entities of type %entity_type: parent menu item not found for %path', $t_args) :
  292. t('Invalid %path_key defined for entities of type %entity_type: matching menu item not found for %path', $t_args);
  293. drupal_set_message($msg, 'warning');
  294. }
  295. unset($scheme[$key]);
  296. }
  297. // If there is a matching menu item for the current scheme key, save
  298. // the real path, i.e. the path of the matching menu item.
  299. else {
  300. $real_path = $paths[$stripped_path];
  301. $real_parts = explode('/', $real_path);
  302. // Restore previously removed trailing path element.
  303. if ($trailing_path_element) {
  304. $real_path .= '/' . $trailing_path_element;
  305. $real_parts[] = $trailing_path_element;
  306. }
  307. $scheme['real ' . $key] = $real_path;
  308. $scheme['real ' . $key . ' parts'] = $real_parts;
  309. }
  310. }
  311. }
  312. }
  313. }
  314. /**
  315. * Implements hook_menu_alter().
  316. */
  317. function entity_translation_menu_alter(&$items) {
  318. $backup = array();
  319. // Initialize path schemes validation function with set of current menu items.
  320. $_null = NULL;
  321. _entity_translation_validate_path_schemes($_null, FALSE, $items);
  322. // Create tabs for all possible entity types.
  323. foreach (entity_get_info() as $entity_type => $info) {
  324. // Menu is rebuilt while determining entity translation base paths and
  325. // callbacks so we might not have them available yet.
  326. if (entity_translation_enabled($entity_type)) {
  327. $et_info = $info['translation']['entity_translation'];
  328. // Flag for tracking whether we have managed to attach the translate UI
  329. // successfully at least once.
  330. $translate_ui_attached = FALSE;
  331. // Validate path schemes for current entity type. Also removes invalid
  332. // ones and adds '... path parts' elements.
  333. _entity_translation_validate_path_schemes($et_info['path schemes'], $info['label'], FALSE, TRUE);
  334. foreach ($et_info['path schemes'] as $scheme) {
  335. $translate_item = NULL;
  336. $edit_item = NULL;
  337. // If we have a translate path then attach the translation UI, and
  338. // register the callback for deleting a translation.
  339. if (isset($scheme['translate path'])) {
  340. $translate_path = $scheme['translate path'];
  341. $keys = array('theme callback', 'theme arguments', 'access callback', 'access arguments', 'load arguments');
  342. $item = array_intersect_key($info['translation']['entity_translation'], drupal_map_assoc($keys));
  343. $item += array(
  344. 'file' => 'entity_translation.admin.inc',
  345. 'module' => 'entity_translation',
  346. );
  347. $entity_position = array_search($scheme['path wildcard'], $scheme['translate path parts']);
  348. if ($item['access callback'] == 'entity_translation_tab_access') {
  349. $item['access arguments'][] = $entity_position;
  350. }
  351. // Backup existing values for the translate overview page.
  352. if (isset($items[$translate_path])) {
  353. $backup[$entity_type] = $items[$translate_path];
  354. }
  355. $items[$translate_path] = array(
  356. 'title' => 'Translate',
  357. 'page callback' => 'entity_translation_overview',
  358. 'page arguments' => array($entity_type, $entity_position),
  359. 'type' => MENU_LOCAL_TASK,
  360. 'weight' => 2,
  361. 'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
  362. ) + $item;
  363. // Delete translation callback.
  364. $language_position = count($scheme['translate path parts']) + 1;
  365. $items["$translate_path/delete/%entity_translation_language"] = array(
  366. 'title' => 'Delete',
  367. 'page callback' => 'drupal_get_form',
  368. 'page arguments' => array('entity_translation_delete_confirm', $entity_type, $entity_position, $language_position),
  369. ) + $item;
  370. $translate_item = &$items[$translate_path];
  371. }
  372. // If we have an edit path, then replace the menu edit form with our
  373. // proxy implementation, and register new callbacks for adding and
  374. // editing a translation.
  375. if (isset($scheme['edit path'])) {
  376. // Find the edit item. If the edit path is a default local task we
  377. // need to find the parent item.
  378. $real_edit_path_parts = $scheme['real edit path parts'];
  379. do {
  380. $edit_item = &$items[implode('/', $real_edit_path_parts)];
  381. array_pop($real_edit_path_parts);
  382. }
  383. while (!empty($edit_item['type']) && $edit_item['type'] == MENU_DEFAULT_LOCAL_TASK);
  384. $edit_path = $scheme['edit path'];
  385. $edit_path_parts = $scheme['edit path parts'];
  386. // Replace the main edit callback with our proxy implementation to set
  387. // form language to the current language and check access.
  388. $entity_position = array_search($scheme['path wildcard'], $edit_path_parts);
  389. $original_item = $edit_item;
  390. $args = array($entity_type, $entity_position, FALSE, $original_item);
  391. $edit_item['page callback'] = 'entity_translation_edit_page';
  392. $edit_item['page arguments'] = array_merge($args, $original_item['page arguments']);
  393. $edit_item['access callback'] = 'entity_translation_edit_access';
  394. $edit_item['access arguments'] = array_merge($args, $original_item['access arguments']);
  395. // Edit translation callback.
  396. if ($scheme['edit tabs'] !== FALSE) {
  397. $translation_position = count($edit_path_parts);
  398. $args = array($entity_type, $entity_position, $translation_position, $original_item);
  399. $items["$edit_path/%entity_translation_language"] = array(
  400. 'type' => MENU_DEFAULT_LOCAL_TASK,
  401. 'title callback' => 'entity_translation_edit_title',
  402. 'title arguments' => array($translation_position),
  403. 'page callback' => 'entity_translation_edit_page',
  404. 'page arguments' => array_merge($args, $original_item['page arguments']),
  405. 'access callback' => 'entity_translation_edit_access',
  406. 'access arguments' => array_merge($args, $original_item['access arguments']),
  407. )
  408. // We need to inherit the remaining menu item keys, mostly 'module'
  409. // and 'file' to keep ajax callbacks working (see form_get_cache() and
  410. // drupal_retrieve_form()).
  411. + $original_item;
  412. }
  413. // Add translation callback.
  414. $add_path = "$edit_path/add/%entity_translation_language/%entity_translation_language";
  415. $source_position = count($edit_path_parts) + 1;
  416. $target_position = count($edit_path_parts) + 2;
  417. $args = array($entity_type, $entity_position, $source_position, $target_position, $original_item);
  418. $items[$add_path] = array(
  419. 'title callback' => 'Add translation',
  420. 'page callback' => 'entity_translation_add_page',
  421. 'page arguments' => array_merge($args, $original_item['page arguments']),
  422. 'type' => MENU_LOCAL_TASK,
  423. 'access callback' => 'entity_translation_add_access',
  424. 'access arguments' => array_merge($args, $original_item['access arguments']),
  425. ) + $original_item;
  426. }
  427. // Make the "Translate" tab follow the "Edit" tab if possible.
  428. if ($translate_item && $edit_item && isset($edit_item['weight'])) {
  429. $translate_item['weight'] = $edit_item['weight'] + 1;
  430. }
  431. // If we have both an edit item and a translate item, then we know that
  432. // the translate UI has been attached properly (at least once).
  433. $translate_ui_attached = $translate_ui_attached || ($translate_item && $edit_item);
  434. // Cleanup reference variables, so we don't accidentially overwrite
  435. // something in a later iteration.
  436. unset($translate_item, $edit_item);
  437. }
  438. if ($translate_ui_attached == FALSE) {
  439. drupal_set_message(t('The entities of type %entity_type do not define a valid path scheme: it will not be possible to translate them.', array('%entity_type' => $info['label'])), 'warning');
  440. }
  441. // Node-specific menu alterations.
  442. if ($entity_type == 'node') {
  443. entity_translation_node_menu_alter($items, $backup);
  444. }
  445. }
  446. }
  447. // Avoid bloating memory with unused data.
  448. drupal_static_reset('_entity_translation_validate_path_schemes');
  449. }
  450. /**
  451. * Title callback.
  452. */
  453. function entity_translation_edit_title($langcode) {
  454. $languages = entity_translation_languages();
  455. return isset($languages[$langcode]) ? t($languages[$langcode]->name) : '';
  456. }
  457. /**
  458. * Page callback.
  459. */
  460. function entity_translation_edit_page() {
  461. $args = func_get_args();
  462. $entity_type = array_shift($args);
  463. $entity = array_shift($args);
  464. $langcode = array_shift($args);
  465. $edit_form_item = array_shift($args);
  466. // Set the current form language.
  467. $handler = entity_translation_get_handler($entity_type, $entity);
  468. $handler->initPathScheme();
  469. $langcode = entity_translation_get_existing_language($entity_type, $entity, $langcode);
  470. $handler->setFormLanguage($langcode);
  471. // Display the entity edit form.
  472. return _entity_translation_callback($edit_form_item['page callback'], $args, $edit_form_item);
  473. }
  474. /**
  475. * Access callback.
  476. */
  477. function entity_translation_edit_access() {
  478. $args = func_get_args();
  479. $entity_type = array_shift($args);
  480. $entity = array_shift($args);
  481. $langcode = array_shift($args);
  482. $edit_form_item = array_shift($args);
  483. $access_callback = isset($edit_form_item['access callback']) ? $edit_form_item['access callback'] : 'user_access';
  484. $handler = entity_translation_get_handler($entity_type, $entity);
  485. // First, check a handler has been loaded. This could be empty if a
  486. // non-existent entity edit path has been requested, for example. Delegate
  487. // directly to the edit form item access callback in this case.
  488. if (empty($handler)) {
  489. return _entity_translation_callback($access_callback, $args, $edit_form_item);
  490. }
  491. $translations = $handler->getTranslations();
  492. $langcode = $langcode = entity_translation_get_existing_language($entity_type, $entity, $langcode);
  493. // The user must be explicitly allowed to access the original values if
  494. // workflow permissions are enabled.
  495. if (!$handler->getTranslationAccess($langcode)) {
  496. return FALSE;
  497. }
  498. // If the translation exists or no translation was specified, we can show the
  499. // corresponding local task. If translations have not been initialized yet, we
  500. // need to grant access to the user.
  501. if (empty($translations->data) || isset($translations->data[$langcode])) {
  502. // Check that the requested language is actually accessible. If the entity
  503. // is language neutral we need to let editors access it.
  504. $enabled_languages = entity_translation_languages($entity_type, $entity);
  505. if (isset($enabled_languages[$langcode]) || $langcode == LANGUAGE_NONE) {
  506. return _entity_translation_callback($access_callback, $args, $edit_form_item);
  507. }
  508. }
  509. return FALSE;
  510. }
  511. /**
  512. * Determines the current form language.
  513. *
  514. * @param $langcode
  515. * The requested language code.
  516. * @param EntityTranslationHandlerInterface $handler
  517. * A translation handler instance.
  518. *
  519. * @return
  520. * A valid language code.
  521. *
  522. * @deprecated This is no longer used and will be removed in the first stable
  523. * release.
  524. */
  525. function entity_translation_form_language($langcode, $handler) {
  526. return entity_translation_get_existing_language($handler->getEntity(), $handler->getEntityType(), $langcode);
  527. }
  528. /**
  529. * Determines an existing translation language.
  530. *
  531. * Based on the requested language and the translations available for the given
  532. * entity, determines an existing translation language. This takes into account
  533. * language fallback rules.
  534. *
  535. * @param $entity_type
  536. * The type of the entity.
  537. * @param $entity
  538. * The entity whose existing translation language has to be returned.
  539. * @param $langcode
  540. * (optional) The requested language code. Defaults to the current content
  541. * language.
  542. *
  543. * @return
  544. * A valid language code.
  545. */
  546. function entity_translation_get_existing_language($entity_type, $entity, $langcode = NULL) {
  547. $handler = entity_translation_get_handler($entity_type, $entity);
  548. if (empty($langcode)) {
  549. $langcode = $GLOBALS['language_content']->language;
  550. }
  551. $translations = $handler->getTranslations();
  552. $fallback = drupal_multilingual() ? language_fallback_get_candidates() : array(LANGUAGE_NONE);
  553. while (!empty($langcode) && !isset($translations->data[$langcode])) {
  554. $langcode = array_shift($fallback);
  555. }
  556. // If no translation is available fall back to the entity language.
  557. return !empty($langcode) ? $langcode : $handler->getLanguage();
  558. }
  559. /**
  560. * Access callback.
  561. */
  562. function entity_translation_add_access() {
  563. $args = func_get_args();
  564. $entity_type = array_shift($args);
  565. $entity = array_shift($args);
  566. $source = array_shift($args);
  567. $langcode = array_shift($args);
  568. $handler = entity_translation_get_handler($entity_type, $entity);
  569. $translations = $handler->getTranslations();
  570. // If the translation does not exist we can show the tab.
  571. if (!isset($translations->data[$langcode]) && $langcode != $source) {
  572. // Check that the requested language is actually accessible.
  573. $enabled_languages = entity_translation_languages($entity_type, $entity);
  574. if (isset($enabled_languages[$langcode])) {
  575. $edit_form_item = array_shift($args);
  576. $access_callback = isset($edit_form_item['access callback']) ? $edit_form_item['access callback'] : 'user_access';
  577. return _entity_translation_callback($access_callback, $args, $edit_form_item);
  578. }
  579. }
  580. return FALSE;
  581. }
  582. /**
  583. * Page callback.
  584. */
  585. function entity_translation_add_page() {
  586. $args = func_get_args();
  587. $entity_type = array_shift($args);
  588. $entity = array_shift($args);
  589. $source = array_shift($args);
  590. $langcode = array_shift($args);
  591. $edit_form_item = array_shift($args);
  592. $handler = entity_translation_get_handler($entity_type, $entity);
  593. $handler->initPathScheme();
  594. $handler->setFormLanguage($langcode);
  595. $handler->setSourceLanguage($source);
  596. // Display the entity edit form.
  597. return _entity_translation_callback($edit_form_item['page callback'], $args, $edit_form_item);
  598. }
  599. /**
  600. * Helper function. Proxies a callback call including any needed file.
  601. */
  602. function _entity_translation_callback($callback, $args, $info = array()) {
  603. if (isset($info['file'])) {
  604. $path = isset($info['file path']) ? $info['file path'] : drupal_get_path('module', $info['module']);
  605. include_once DRUPAL_ROOT . '/' . $path . '/' . $info['file'];
  606. }
  607. return call_user_func_array($callback, $args);
  608. }
  609. /**
  610. * Implements hook_admin_paths().
  611. */
  612. function entity_translation_admin_paths() {
  613. $paths = array();
  614. foreach (entity_get_info() as $entity_type => $info) {
  615. if (isset($info['translation']['entity_translation']['path schemes']) && entity_translation_enabled($entity_type, NULL, TRUE)) {
  616. foreach ($info['translation']['entity_translation']['path schemes'] as $scheme) {
  617. if (!empty($scheme['admin theme'])) {
  618. if (isset($scheme['translate path'])) {
  619. $translate_path = preg_replace('|%[^/]*|', '*', $scheme['translate path']);
  620. $paths[$translate_path] = TRUE;
  621. $paths["$translate_path/*"] = TRUE;
  622. }
  623. if (isset($scheme['edit path'])) {
  624. $edit_path = preg_replace('|%[^/]*|', '*', $scheme['edit path']);
  625. $paths["$edit_path/*"] = TRUE;
  626. }
  627. }
  628. }
  629. }
  630. }
  631. return $paths;
  632. }
  633. /**
  634. * Access callback.
  635. */
  636. function entity_translation_tab_access($entity_type, $entity) {
  637. if (drupal_multilingual() && (user_access('translate any entity') || user_access("translate $entity_type entities"))) {
  638. $handler = entity_translation_get_handler($entity_type, $entity);
  639. // Ensure $entity holds an entity object and not an id.
  640. $entity = $handler->getEntity();
  641. $enabled = entity_translation_enabled($entity_type, $entity);
  642. return $enabled && $handler->getLanguage() != LANGUAGE_NONE;
  643. }
  644. return FALSE;
  645. }
  646. /**
  647. * Menu loader callback.
  648. */
  649. function entity_translation_language_load($langcode, $entity_type = NULL, $entity = NULL) {
  650. $enabled_languages = entity_translation_languages($entity_type, $entity);
  651. return isset($enabled_languages[$langcode]) ? $langcode : FALSE;
  652. }
  653. /**
  654. * Menu loader callback.
  655. */
  656. function entity_translation_menu_entity_load($entity_id, $entity_type) {
  657. $entities = entity_load($entity_type, array($entity_id));
  658. return $entities[$entity_id];
  659. }
  660. /**
  661. * Implements hook_permission().
  662. */
  663. function entity_translation_permission() {
  664. $permission = array(
  665. 'administer entity translation' => array(
  666. 'title' => t('Administer entity translation'),
  667. 'description' => t('Select which entities can be translated.'),
  668. ),
  669. 'toggle field translatability' => array(
  670. 'title' => t('Toggle field translatability'),
  671. 'description' => t('Toggle translatability of fields performing a bulk update.'),
  672. ),
  673. 'translate any entity' => array(
  674. 'title' => t('Translate any entity'),
  675. 'description' => t('Translate field content for any fieldable entity.'),
  676. ),
  677. );
  678. $workflow = entity_translation_workflow_enabled();
  679. if ($workflow) {
  680. $permission += array(
  681. 'edit translation shared fields' => array(
  682. 'title' => t('Edit shared values'),
  683. 'description' => t('Edit values shared between translations on the entity form.'),
  684. ),
  685. 'edit original values' => array(
  686. 'title' => t('Edit original values'),
  687. 'description' => t('Access any entity form in the original language.'),
  688. ),
  689. );
  690. }
  691. foreach (entity_get_info() as $entity_type => $info) {
  692. if ($info['fieldable'] && entity_translation_enabled($entity_type)) {
  693. $label = !empty($info['label']) ? t($info['label']) : $entity_type;
  694. $permission["translate $entity_type entities"] = array(
  695. 'title' => t('Translate entities of type @type', array('@type' => $label)),
  696. 'description' => t('Translate field content for entities of type @type.', array('@type' => $label)),
  697. );
  698. if ($workflow) {
  699. // Avoid access control for original values on the current entity.
  700. if (empty($info['translation']['entity_translation']['skip original values access'])) {
  701. $permission["edit $entity_type original values"] = array(
  702. 'title' => t('Edit original values on entities of type @type', array('@type' => $label)),
  703. 'description' => t('Access the entity form in the original language for entities of type @type.', array('@type' => $label)),
  704. );
  705. }
  706. // Avoid access control for shared fields on the current entity.
  707. if (empty($info['translation']['entity_translation']['skip shared fields access'])) {
  708. $permission["edit $entity_type translation shared fields"] = array(
  709. 'title' => t('Edit @type shared values.', array('@type' => $label)),
  710. 'description' => t('Edit values shared between translations on @type forms.', array('@type' => $label)),
  711. );
  712. }
  713. }
  714. }
  715. }
  716. return $permission;
  717. }
  718. /**
  719. * Returns TRUE if the translation workflow is enabled.
  720. */
  721. function entity_translation_workflow_enabled() {
  722. return variable_get('entity_translation_workflow_enabled', FALSE);
  723. }
  724. /**
  725. * Implements hook_theme().
  726. */
  727. function entity_translation_theme() {
  728. return array(
  729. 'entity_translation_unavailable' => array(
  730. 'variables' => array('element' => NULL),
  731. ),
  732. 'entity_translation_language_tabs' => array(
  733. 'render element' => 'element',
  734. ),
  735. 'entity_translation_overview' => array(
  736. 'variables' => array('rows' => NULL, 'header' => NULL),
  737. 'file' => 'entity_translation.admin.inc'
  738. ),
  739. 'entity_translation_overview_outdated' => array(
  740. 'variables' => array('message' => NULL),
  741. 'file' => 'entity_translation.admin.inc'
  742. ),
  743. );
  744. }
  745. /**
  746. * Implements hook_entity_load().
  747. */
  748. function entity_translation_entity_load($entities, $entity_type) {
  749. if (entity_translation_enabled($entity_type)) {
  750. EntityTranslationDefaultHandler::loadMultiple($entity_type, $entities);
  751. }
  752. }
  753. /**
  754. * Implements hook_field_extra_fields().
  755. */
  756. function entity_translation_field_extra_fields() {
  757. $extra = array();
  758. $enabled = variable_get('entity_translation_entity_types', array());
  759. $info = entity_get_info();
  760. foreach ($enabled as $entity_type) {
  761. if (entity_translation_enabled($entity_type)) {
  762. $bundles = !empty($info[$entity_type]['bundles']) ? array_keys($info[$entity_type]['bundles']) : array($entity_type);
  763. foreach ($bundles as $bundle) {
  764. // @todo Clean this up in https://www.drupal.org/node/1661348.
  765. if ($entity_type == 'taxonomy_term') {
  766. $vocabulary = taxonomy_vocabulary_machine_name_load($bundle);
  767. if ($vocabulary && module_invoke('i18n_taxonomy', 'vocabulary_mode', $vocabulary, 4)) {
  768. continue;
  769. }
  770. }
  771. $settings = entity_translation_settings($entity_type, $bundle);
  772. if (empty($settings['hide_language_selector']) && entity_translation_enabled_bundle($entity_type, $bundle) && ($handler = entity_translation_get_handler($entity_type, $bundle))) {
  773. $language_key = $handler->getLanguageKey();
  774. $extra[$entity_type][$bundle] = array(
  775. 'form' => array(
  776. $language_key => array(
  777. 'label' => t('Language'),
  778. 'description' => t('Language selection'),
  779. 'weight' => 5,
  780. ),
  781. ),
  782. );
  783. }
  784. }
  785. }
  786. }
  787. return $extra;
  788. }
  789. /**
  790. * Implements hook_field_language_alter().
  791. *
  792. * Performs language fallback for unaccessible translations.
  793. */
  794. function entity_translation_field_language_alter(&$display_language, $context) {
  795. if (variable_get('locale_field_language_fallback', TRUE) && entity_translation_enabled($context['entity_type'])) {
  796. $entity = $context['entity'];
  797. $entity_type = $context['entity_type'];
  798. $handler = entity_translation_get_handler($entity_type, $entity);
  799. $translations = $handler->getTranslations();
  800. // Apply fallback only on unpublished translations as missing translations
  801. // are already handled in locale_field_language_alter().
  802. if (isset($translations->data[$context['language']]) && !entity_translation_access($entity_type, $translations->data[$context['language']])) {
  803. list(, , $bundle) = entity_extract_ids($entity_type, $entity);
  804. $instances = field_info_instances($entity_type, $bundle);
  805. $entity = clone($entity);
  806. foreach ($translations->data as $langcode => $translation) {
  807. if ($langcode == $context['language'] || !entity_translation_access($entity_type, $translations->data[$langcode])) {
  808. // Unset unaccessible field translations: if the field is
  809. // untranslatable unsetting a language different from LANGUAGE_NONE
  810. // has no effect.
  811. foreach ($instances as $instance) {
  812. unset($entity->{$instance['field_name']}[$langcode]);
  813. }
  814. }
  815. }
  816. // Find the new fallback values.
  817. locale_field_language_fallback($display_language, $entity, $context['language']);
  818. }
  819. elseif (!field_has_translation_handler($entity_type, 'locale')) {
  820. // If not handled by the Locale translation handler trigger fallback too.
  821. locale_field_language_fallback($display_language, $entity, $context['language']);
  822. }
  823. }
  824. }
  825. /**
  826. * Implements hook_field_attach_view_alter().
  827. *
  828. * Hide the entity if no translation is available for the current language and
  829. * language fallback is disabled.
  830. */
  831. function entity_translation_field_attach_view_alter(&$output, $context) {
  832. if (!variable_get('locale_field_language_fallback', TRUE) && entity_translation_enabled($context['entity_type'])) {
  833. $handler = entity_translation_get_handler($context['entity_type'], $context['entity']);
  834. $translations = $handler->getTranslations();
  835. $langcode = !empty($context['language']) ? $context['language'] : $GLOBALS['language_content']->language;
  836. // If fallback is disabled we need to notify the user that the translation
  837. // is unavailable (missing or unpublished).
  838. if (!empty($translations->data) && ((!isset($translations->data[$langcode]) && !isset($translations->data[LANGUAGE_NONE])) || ((isset($translations->data[$langcode]) && !entity_translation_access($context['entity_type'], $translations->data[$langcode]))))) {
  839. // Provide context for rendering.
  840. $output['#entity'] = $context['entity'];
  841. $output['#entity_type'] = $context['entity_type'];
  842. $output['#view_mode'] = $context['view_mode'];
  843. // We perform theming here because the theming function might need to set
  844. // system messages. It would be too late in the #post_render callback.
  845. $output['#entity_translation_unavailable'] = theme('entity_translation_unavailable', array('element' => $output));
  846. // As we used a string key, other modules implementing
  847. // hook_field_attach_view_alter() may unset/override this.
  848. $output['#post_render']['entity_translation'] = 'entity_translation_unavailable';
  849. }
  850. }
  851. }
  852. /**
  853. * Override the entity output with the unavailable translation one.
  854. */
  855. function entity_translation_unavailable($children, $element) {
  856. return $element['#entity_translation_unavailable'];
  857. }
  858. /**
  859. * Theme an unvailable translation.
  860. */
  861. function theme_entity_translation_unavailable($variables) {
  862. $element = $variables['element'];
  863. $handler = entity_translation_get_handler($element['#entity_type'], $element['#entity']);
  864. $args = array('%language' => t($GLOBALS['language_content']->name), '%label' => $handler->getLabel());
  865. $message = t('%language translation unavailable for %label.', $args);
  866. $classes = $element['#entity_type'] . ' ' . $element['#entity_type'] . '-' . $element['#view_mode'];
  867. return "<div class=\"$classes\"><div class=\"messages warning\">$message</div></div>";
  868. }
  869. /**
  870. * Implements hook_field_info_alter().
  871. */
  872. function entity_translation_field_info_alter(&$info) {
  873. $columns = array('fid');
  874. $supported_types = array('file' => $columns, 'image' => $columns);
  875. foreach ($info as $field_type => &$field_type_info) {
  876. // Store columns to be synchronized.
  877. if (!isset($field_type_info['settings'])) {
  878. $field_type_info['settings'] = array();
  879. }
  880. $field_type_info['settings'] += array(
  881. 'entity_translation_sync' => isset($supported_types[$field_type]) ? $supported_types[$field_type] : FALSE,
  882. );
  883. // Synchronization can be enabled per instance.
  884. if (!isset($field_type_info['instance_settings'])) {
  885. $field_type_info['instance_settings'] = array();
  886. }
  887. $field_type_info['instance_settings'] += array(
  888. 'entity_translation_sync' => FALSE,
  889. );
  890. }
  891. }
  892. /**
  893. * Implements hook_field_attach_presave().
  894. */
  895. function entity_translation_field_attach_presave($entity_type, $entity) {
  896. if (entity_translation_enabled($entity_type, $entity)) {
  897. entity_translation_sync($entity_type, $entity);
  898. }
  899. }
  900. /**
  901. * Performs field column synchronization.
  902. */
  903. function entity_translation_sync($entity_type, $entity) {
  904. // If we are creating a new entity or if we have no translations for the
  905. // current entity, there is nothing to synchronize.
  906. $handler = entity_translation_get_handler($entity_type, $entity, TRUE);
  907. $translations = $handler->getTranslations();
  908. $original_langcode = $handler->getSourceLanguage();
  909. if ($handler->isNewEntity() || (count($translations->data) < 2 && !$original_langcode)) {
  910. return;
  911. }
  912. list($id, , $bundle) = entity_extract_ids($entity_type, $entity);
  913. $instances = field_info_instances($entity_type, $bundle);
  914. $entity_unchanged = isset($entity->original) ? $entity->original : entity_load_unchanged($entity_type, $id);
  915. // If the entity language is being changed there is nothing to synchronize.
  916. $langcode = $handler->getLanguage();
  917. $handler->setEntity($entity_unchanged);
  918. if ($langcode != $handler->getLanguage()) {
  919. return;
  920. }
  921. foreach ($instances as $field_name => $instance) {
  922. $field = field_info_field($field_name);
  923. // If the field is empty there is nothing to synchronize. Synchronization
  924. // makes sense only for translatable fields.
  925. if (!empty($entity->{$field_name}) && !empty($instance['settings']['entity_translation_sync']) && field_is_translatable($entity_type, $field)) {
  926. $columns = $field['settings']['entity_translation_sync'];
  927. $change_map = array();
  928. $source_langcode = entity_language($entity_type, $entity);
  929. $source_items = $entity->{$field_name}[$source_langcode];
  930. // If a translation is being created, the original values should be used
  931. // as the unchanged items. In fact there are no unchanged items to check
  932. // against.
  933. $langcode = $original_langcode ? $original_langcode : $source_langcode;
  934. $unchanged_items = !empty($entity_unchanged->{$field_name}[$langcode]) ? $entity_unchanged->{$field_name}[$langcode] : array();
  935. // By picking the maximum size between updated and unchanged items, we
  936. // make sure to process also removed items.
  937. $total = max(array(count($source_items), count($unchanged_items)));
  938. // Make sure we can detect any change in the source items.
  939. for ($delta = 0; $delta < $total; $delta++) {
  940. foreach ($columns as $column) {
  941. // Store the delta for the unchanged column value.
  942. if (isset($unchanged_items[$delta][$column])) {
  943. $value = $unchanged_items[$delta][$column];
  944. $change_map[$column][$value]['old'] = $delta;
  945. }
  946. // Store the delta for the new column value.
  947. if (isset($source_items[$delta][$column])) {
  948. $value = $source_items[$delta][$column];
  949. $change_map[$column][$value]['new'] = $delta;
  950. }
  951. }
  952. }
  953. // Backup field values.
  954. $field_values = $entity->{$field_name};
  955. // Reset field values so that no spurious translation value is stored.
  956. // Source values and anything else must be preserved in any case.
  957. $entity->{$field_name} = array($source_langcode => $source_items) + array_diff_key($entity->{$field_name}, $translations->data);
  958. // Update translations.
  959. foreach ($translations->data as $langcode => $translation) {
  960. // We need to synchronize only values different from the source ones.
  961. if ($langcode != $source_langcode) {
  962. // Process even removed items.
  963. for ($delta = 0; $delta < $total; $delta++) {
  964. $created = TRUE;
  965. $removed = TRUE;
  966. foreach ($columns as $column) {
  967. if (isset($source_items[$delta][$column])) {
  968. $value = $source_items[$delta][$column];
  969. $created = $created && !isset($change_map[$column][$value]['old']);
  970. $removed = $removed && !isset($change_map[$column][$value]['new']);
  971. }
  972. }
  973. // If an item has been removed we do not store its translations.
  974. if ($removed) {
  975. // Ensure items are actually removed.
  976. if (!isset($entity->{$field_name}[$langcode])) {
  977. $entity->{$field_name}[$langcode] = array();
  978. }
  979. continue;
  980. }
  981. // If a synchronized column has changed we need to override the full
  982. // items array for all languages.
  983. elseif ($created) {
  984. $entity->{$field_name}[$langcode][$delta] = $source_items[$delta];
  985. }
  986. // The current item might have been reordered.
  987. elseif (!empty($change_map[$column][$value])) {
  988. $old_delta = $change_map[$column][$value]['old'];
  989. $new_delta = $change_map[$column][$value]['new'];
  990. // If for nay reason the old value is not defined for the current
  991. // we language we fall back to the new source value.
  992. $items = isset($field_values[$langcode][$old_delta]) ? $field_values[$langcode][$old_delta] : $source_items[$new_delta];
  993. $entity->{$field_name}[$langcode][$new_delta] = $items;
  994. }
  995. }
  996. }
  997. }
  998. }
  999. }
  1000. }
  1001. /**
  1002. * Implements hook_field_attach_insert().
  1003. */
  1004. function entity_translation_field_attach_insert($entity_type, $entity) {
  1005. // Store entity translation metadata only if the entity bundle is
  1006. // translatable.
  1007. if (entity_translation_enabled($entity_type, $entity)) {
  1008. $handler = entity_translation_get_handler($entity_type, $entity);
  1009. $handler->initTranslations();
  1010. $handler->saveTranslations();
  1011. }
  1012. }
  1013. /**
  1014. * Implements hook_field_attach_update().
  1015. */
  1016. function entity_translation_field_attach_update($entity_type, $entity) {
  1017. // Store entity translation metadata only if the entity bundle is
  1018. // translatable.
  1019. if (entity_translation_enabled($entity_type, $entity)) {
  1020. $handler = entity_translation_get_handler($entity_type, $entity, TRUE);
  1021. $handler->updateTranslations();
  1022. $handler->saveTranslations();
  1023. }
  1024. }
  1025. /**
  1026. * Implements hook_field_attach_delete().
  1027. */
  1028. function entity_translation_field_attach_delete($entity_type, $entity) {
  1029. if (entity_translation_enabled($entity_type, $entity)) {
  1030. $handler = entity_translation_get_handler($entity_type, $entity);
  1031. $handler->removeTranslations();
  1032. $handler->saveTranslations();
  1033. }
  1034. }
  1035. /**
  1036. * Implements hook_field_attach_delete_revision().
  1037. */
  1038. function entity_translation_field_attach_delete_revision($entity_type, $entity) {
  1039. if (entity_translation_enabled($entity_type, $entity)) {
  1040. $handler = entity_translation_get_handler($entity_type, $entity);
  1041. $handler->removeRevisionTranslations();
  1042. $handler->saveTranslations();
  1043. }
  1044. }
  1045. /**
  1046. * Implementation of hook_field_attach_form().
  1047. */
  1048. function entity_translation_field_attach_form($entity_type, $entity, &$form, &$form_state, $langcode) {
  1049. // Avoid recursing into the source form.
  1050. list($id, , $bundle) = entity_extract_ids($entity_type, $entity);
  1051. if (empty($form['#entity_translation_source_form']) && entity_translation_enabled($entity_type, $bundle)) {
  1052. $handler = entity_translation_get_handler($entity_type, $entity);
  1053. $langcode = !empty($langcode) ? $langcode : $handler->getLanguage();
  1054. $form_langcode = $handler->getFormLanguage();
  1055. $translations = $handler->getTranslations();
  1056. $update_langcode = $form_langcode && ($form_langcode != $langcode);
  1057. $source = $handler->getSourceLanguage();
  1058. $new_translation = !isset($translations->data[$form_langcode]);
  1059. // If we are creating a new translation we need to retrieve form elements
  1060. // populated with the source language values, but only if form is not being
  1061. // rebuilt. In this case source values have already been populated, so we
  1062. // need to preserve possible changes. There might be situations, e.g. ajax
  1063. // calls, where the form language has not been properly initialized before
  1064. // calling field_attach_form(). In this case we need to rebuild the form
  1065. // with the correct form language and replace the field elements with the
  1066. // correct ones.
  1067. if ($update_langcode || ($source && !isset($translations->data[$form_langcode]) && isset($translations->data[$source]) && empty($form_state['rebuild']))) {
  1068. foreach (field_info_instances($entity_type, $bundle) as $instance) {
  1069. $field_name = $instance['field_name'];
  1070. $field = field_info_field($field_name);
  1071. // If we are creating a new translation we have to change the form item
  1072. // language information from source to target language, this way the
  1073. // user can find the form items already populated with the source values
  1074. // while the field form element holds the correct language information.
  1075. if ($field['translatable']) {
  1076. $element = &$form[$field_name];
  1077. $element['#entity_type'] = $entity_type;
  1078. $element['#entity'] = $entity;
  1079. $element['#entity_id'] = $id;
  1080. $element['#field_name'] = $field_name;
  1081. $element['#source'] = $update_langcode ? $form_langcode : $source;
  1082. $element['#previous'] = NULL;
  1083. $element['#form_parents'] = $form['#parents'];
  1084. // If we are updating the form language we need to make sure that the
  1085. // wrong language is unset and the right one is stored in the field
  1086. // element (see entity_translation_prepare_element()).
  1087. if ($update_langcode) {
  1088. $element['#previous'] = $element['#language'];
  1089. $element['#language'] = $form_langcode;
  1090. }
  1091. // Swap default values during form processing to avoid recursion. We
  1092. // try to act before any other callback so that the correct values are
  1093. // already in place for them.
  1094. if (!isset($element['#process'])) {
  1095. $element['#process'] = array();
  1096. }
  1097. array_unshift($element['#process'], 'entity_translation_prepare_element');
  1098. }
  1099. }
  1100. }
  1101. // Handle fields shared between translations when there is at least one
  1102. // translation available or a new one is being created.
  1103. if (!$handler->isNewEntity() && ($new_translation || count($translations->data) > 1)) {
  1104. $shared_access = $handler->getSharedFieldsAccess();
  1105. list(, , $bundle) = entity_extract_ids($entity_type, $entity);
  1106. foreach (field_info_instances($entity_type, $bundle) as $instance) {
  1107. $field_name = $instance['field_name'];
  1108. $field = field_info_field($field_name);
  1109. // If access is not set or is granted we check whether the user has
  1110. // access to shared fields.
  1111. $form[$field_name]['#access'] = (!isset($form[$field_name]['#access']) || $form[$field_name]['#access']) && ($field['translatable'] || $shared_access);
  1112. $form[$field_name]['#multilingual'] = (boolean) $field['translatable'];
  1113. }
  1114. }
  1115. // If a translation is being created and no path alias exists for its
  1116. // language, by default an alias needs to be generated. The standard
  1117. // behavior is defaulting to FALSE when an entity already exists, hence we
  1118. // need to override it here.
  1119. if (module_exists('pathauto') && $handler->getSourceLanguage()) {
  1120. $entity->path['pathauto'] = TRUE;
  1121. }
  1122. }
  1123. }
  1124. /**
  1125. * Form element process callback.
  1126. */
  1127. function entity_translation_prepare_element($element, &$form_state) {
  1128. static $drupal_static_fast;
  1129. if (!isset($drupal_static_fast)) {
  1130. $drupal_static_fast['source_forms'] = &drupal_static(__FUNCTION__, array());
  1131. }
  1132. $source_forms = &$drupal_static_fast['source_forms'];
  1133. $form = $form_state['complete form'];
  1134. $build_id = $form['#build_id'];
  1135. $source = $element['#source'];
  1136. $entity_type = $element['#entity_type'];
  1137. $id = $element['#entity_id'];
  1138. // Key the source form cache per entity type and entity id to allow for
  1139. // multiple entities on the same entity form.
  1140. if (!isset($source_forms[$build_id][$source][$entity_type][$id])) {
  1141. $source_form = array(
  1142. '#entity_translation_source_form' => TRUE,
  1143. '#parents' => $element['#form_parents'],
  1144. );
  1145. $source_form_state = $form_state;
  1146. field_attach_form($entity_type, $element['#entity'], $source_form, $source_form_state, $source);
  1147. $source_forms[$build_id][$source][$entity_type][$id] = &$source_form;
  1148. }
  1149. $source_form = &$source_forms[$build_id][$source][$entity_type][$id];
  1150. $langcode = $element['#language'];
  1151. $field_name = $element['#field_name'];
  1152. // If we are creating a new translation we have to change the form item
  1153. // language information from source to target language, this way the user can
  1154. // find the form items already populated with the source values while the
  1155. // field form element holds the correct language information.
  1156. if (isset($source_form[$field_name][$source])) {
  1157. $element[$langcode] = $source_form[$field_name][$source];
  1158. entity_translation_form_element_language_replace($element, $source, $langcode);
  1159. unset($element[$element['#previous']]);
  1160. }
  1161. return $element;
  1162. }
  1163. /**
  1164. * Helper function. Recursively replaces the source language with the given one.
  1165. */
  1166. function entity_translation_form_element_language_replace(&$element, $source, $langcode) {
  1167. // Iterate through the form structure recursively.
  1168. foreach (element_children($element) as $key) {
  1169. entity_translation_form_element_language_replace($element[$key], $source, $langcode);
  1170. }
  1171. // Replace specific occurrences of the source language with the target
  1172. // language.
  1173. foreach (element_properties($element) as $key) {
  1174. if ($key === '#language' && $element[$key] != LANGUAGE_NONE) {
  1175. $element[$key] = $langcode;
  1176. }
  1177. elseif ($key === '#parents' || $key === '#field_parents') {
  1178. foreach ($element[$key] as $delta => $value) {
  1179. if ($value === $source) {
  1180. $element[$key][$delta] = $langcode;
  1181. }
  1182. }
  1183. }
  1184. elseif ($key === '#limit_validation_errors') {
  1185. foreach ($element[$key] as $section => $section_value) {
  1186. foreach ($element[$key][$section] as $delta => $value) {
  1187. if ($value === $source) {
  1188. $element[$key][$section][$delta] = $langcode;
  1189. }
  1190. }
  1191. }
  1192. }
  1193. }
  1194. }
  1195. /**
  1196. * Adds visual clues about the translatability of a field to the given element.
  1197. *
  1198. * Field titles are appended with the string "Shared" for fields which are
  1199. * shared between different translations. Moreover fields receive a CSS class to
  1200. * distinguish between translatable and shared fields.
  1201. */
  1202. function entity_translation_element_translatability_clue($element) {
  1203. // Append language to element title.
  1204. if (empty($element['#multilingual'])) {
  1205. _entity_translation_element_title_append($element, ' (' . t('all languages') . ')');
  1206. }
  1207. // Add CSS class names.
  1208. if (!isset($element['#attributes'])) {
  1209. $element['#attributes'] = array();
  1210. }
  1211. if (!isset($element['#attributes']['class'])) {
  1212. $element['#attributes']['class'] = array();
  1213. }
  1214. $element['#attributes']['class'][] = 'entity-translation-' . (!empty($element['#multilingual']) ? 'field-translatable' : 'field-shared');
  1215. return $element;
  1216. }
  1217. /**
  1218. * Adds a callback function to the given FAPI element.
  1219. *
  1220. * Drupal core only adds default element callbacks if the respective handler
  1221. * type is not defined yet. This function ensures that our callback is only
  1222. * prepended/appended to the default set of callbacks instead of replacing it.
  1223. *
  1224. * @param $element
  1225. * The FAPI element.
  1226. * @param $type
  1227. * The callback type, e.g. '#pre_render' or '#process'.
  1228. * @param $function
  1229. * The name of the callback to add.
  1230. * @param $prepend
  1231. * Set to TRUE to add the new callback to the beginning of the existing set of
  1232. * callbacks, and set it to FALSE to append it at the end.
  1233. */
  1234. function _entity_translation_element_add_callback(&$element, $type, $function, $prepend = TRUE) {
  1235. // If handler type has not been set, add defaults from element_info().
  1236. if (!isset($element[$type])) {
  1237. $element_type = isset($element['#type']) ? $element['#type'] : 'markup';
  1238. $element_info = element_info($element_type);
  1239. $element[$type] = isset($element_info[$type]) ? $element_info[$type] : array();
  1240. }
  1241. if ($prepend) {
  1242. array_unshift($element[$type], $function);
  1243. }
  1244. else {
  1245. $element[$type][] = $function;
  1246. }
  1247. }
  1248. /**
  1249. * Appends the given $suffix string to the title of the given form element.
  1250. *
  1251. * If the given element does not have a #title attribute, the function is
  1252. * recursively applied to child elements.
  1253. */
  1254. function _entity_translation_element_title_append(&$element, $suffix) {
  1255. static $fapi_title_elements;
  1256. // Elements which can have a #title attribute according to FAPI Reference.
  1257. if (!isset($fapi_title_elements)) {
  1258. $fapi_title_elements = array_flip(array('checkbox', 'checkboxes', 'date', 'fieldset', 'file', 'item', 'password', 'password_confirm', 'radio', 'radios', 'select', 'text_format', 'textarea', 'textfield', 'weight'));
  1259. }
  1260. // Update #title attribute for all elements that are allowed to have a #title
  1261. // attribute according to the Form API Reference. The reason for this check
  1262. // is because some elements have a #title attribute even though it is not
  1263. // rendered, e.g. field containers.
  1264. if (isset($element['#type']) && isset($fapi_title_elements[$element['#type']]) && isset($element['#title'])) {
  1265. $element['#title'] .= $suffix;
  1266. }
  1267. // If the current element does not have a (valid) title, try child elements.
  1268. elseif ($children = element_children($element)) {
  1269. foreach ($children as $delta) {
  1270. _entity_translation_element_title_append($element[$delta], $suffix);
  1271. }
  1272. }
  1273. // If there are no children, fall back to the current #title attribute if it
  1274. // exists.
  1275. elseif (isset($element['#title'])) {
  1276. $element['#title'] .= $suffix;
  1277. }
  1278. }
  1279. /**
  1280. * Implements hook_form_alter().
  1281. */
  1282. function entity_translation_form_alter(&$form, &$form_state) {
  1283. if ($info = entity_translation_edit_form_info($form, $form_state)) {
  1284. $handler = entity_translation_get_handler($info['entity type'], $info['entity']);
  1285. if (entity_translation_enabled($info['entity type'], $info['entity'])) {
  1286. if (!$handler->isNewEntity()) {
  1287. $handler->entityForm($form, $form_state);
  1288. $translations = $handler->getTranslations();
  1289. $form_langcode = $handler->getFormLanguage();
  1290. if (!isset($translations->data[$form_langcode]) || count($translations->data) > 1) {
  1291. // Hide shared form elements if the user is not allowed to edit them.
  1292. $handler->entityFormSharedElements($form);
  1293. }
  1294. }
  1295. else {
  1296. $handler->entityFormLanguageWidget($form, $form_state);
  1297. }
  1298. // We need to process the posted form as early as possible to update the
  1299. // form language value.
  1300. array_unshift($form['#validate'], 'entity_translation_entity_form_validate');
  1301. }
  1302. // We might have an entity form for an entity or a bundle not enabled for
  1303. // translation. In this case we might need to deal with entity and field
  1304. // languages anyway, since fields may be shared among different bundles and
  1305. // entity types.
  1306. else {
  1307. $handler->entityFormLanguageWidget($form, $form_state);
  1308. }
  1309. }
  1310. }
  1311. /**
  1312. * Submit handler for the source language selector.
  1313. */
  1314. function entity_translation_entity_form_source_language_submit($form, &$form_state) {
  1315. $handler = entity_translation_entity_form_get_handler($form, $form_state);
  1316. $langcode = $form_state['values']['source_language']['language'];
  1317. $path = "{$handler->getEditPath()}/add/$langcode/{$handler->getFormLanguage()}";
  1318. $options = array();
  1319. if (isset($_GET['destination'])) {
  1320. $options['query'] = drupal_get_destination();
  1321. unset($_GET['destination']);
  1322. }
  1323. $form_state['redirect'] = array($path, $options);
  1324. $languages = language_list();
  1325. drupal_set_message(t('Source translation set to: %language', array('%language' => t($languages[$langcode]->name))));
  1326. }
  1327. /**
  1328. * Submit handler for the translation deletion.
  1329. */
  1330. function entity_translation_entity_form_delete_translation_submit($form, &$form_state) {
  1331. $handler = entity_translation_entity_form_get_handler($form, $form_state);
  1332. $path = "{$handler->getTranslatePath()}/delete/{$handler->getFormLanguage()}";
  1333. $options = array();
  1334. if (isset($_GET['destination'])) {
  1335. $options['query'] = drupal_get_destination();
  1336. unset($_GET['destination']);
  1337. }
  1338. $form_state['redirect'] = array($path, $options);
  1339. }
  1340. /**
  1341. * Validation handler for the entity edit form.
  1342. */
  1343. function entity_translation_entity_form_validate($form, &$form_state) {
  1344. $handler = entity_translation_entity_form_get_handler($form, $form_state);
  1345. if (!empty($handler)) {
  1346. $handler->entityFormValidate($form, $form_state);
  1347. }
  1348. }
  1349. /**
  1350. * Validation handler for the entity language widget.
  1351. */
  1352. function entity_translation_entity_form_language_update($element, &$form_state, $form) {
  1353. $handler = entity_translation_entity_form_get_handler($form, $form_state);
  1354. // Ensure the handler form language match the actual one. This is mainly
  1355. // needed when responding to an AJAX request where the languages cannot be set
  1356. // from the usual page callback.
  1357. if (!empty($form_state['entity_translation']['form_langcode'])) {
  1358. $handler->setFormLanguage($form_state['entity_translation']['form_langcode']);
  1359. }
  1360. // When responding to an AJAX request we should ignore any change in the
  1361. // language widget as it may alter the field language expected by the AJAX
  1362. // callback.
  1363. if (empty($form_state['triggering_element']['#ajax'])) {
  1364. $handler->entityFormLanguageWidgetSubmit($form, $form_state);
  1365. }
  1366. }
  1367. /**
  1368. * Submit handler for the entity deletion.
  1369. */
  1370. function entity_translation_entity_form_submit($form, &$form_state) {
  1371. if ($form_state['clicked_button']['#value'] == t('Delete')) {
  1372. $handler = entity_translation_entity_form_get_handler($form, $form_state);
  1373. if (count($handler->getTranslations()->data) > 1) {
  1374. $info = entity_get_info($form['#entity_type']);
  1375. drupal_set_message(t('This will delete all the @entity_type translations.', array('@entity_type' => drupal_strtolower($info['label']))), 'warning');
  1376. }
  1377. }
  1378. }
  1379. /**
  1380. * Implementation of hook_field_attach_submit().
  1381. *
  1382. * Mark translations as outdated if the submitted value is true.
  1383. */
  1384. function entity_translation_field_attach_submit($entity_type, $entity, $form, &$form_state) {
  1385. if (($handler = entity_translation_entity_form_get_handler($form, $form_state)) && entity_translation_enabled($entity_type, $entity)) {
  1386. // Update the wrapped entity with the submitted values.
  1387. $handler->setEntity($entity);
  1388. $handler->entityFormSubmit($form, $form_state);
  1389. }
  1390. }
  1391. /**
  1392. * Implements hook_menu_local_tasks_alter().
  1393. */
  1394. function entity_translation_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  1395. // When displaying the main edit form, we need to craft an additional level of
  1396. // local tasks for each available translation.
  1397. $handler = entity_translation_get_handler();
  1398. if (!empty($handler) && $handler->isEntityForm() && $handler->getLanguage() != LANGUAGE_NONE && drupal_multilingual()) {
  1399. $handler->localTasksAlter($data, $router_item, $root_path);
  1400. }
  1401. }
  1402. /**
  1403. * Preprocess variables for 'page.tpl.php'.
  1404. */
  1405. function entity_translation_preprocess_page(&$variables) {
  1406. if (!empty($variables['tabs']['#secondary'])) {
  1407. $language_tabs = array();
  1408. foreach ($variables['tabs']['#secondary'] as $index => $tab) {
  1409. if (!empty($tab['#language_tab'])) {
  1410. $language_tabs[] = $tab;
  1411. unset($variables['tabs']['#secondary'][$index]);
  1412. }
  1413. }
  1414. if (!empty($language_tabs)) {
  1415. if (count($variables['tabs']['#secondary']) <= 1) {
  1416. $variables['tabs']['#secondary'] = $language_tabs;
  1417. }
  1418. else {
  1419. // If secondary tabs are already defined we need to add another level
  1420. // and wrap it so that it will be positioned on its own row.
  1421. $variables['tabs']['#secondary']['#language_tabs'] = $language_tabs;
  1422. $variables['tabs']['#secondary']['#pre_render']['entity_translation'] = 'entity_translation_language_tabs_render';
  1423. }
  1424. }
  1425. }
  1426. }
  1427. /**
  1428. * Pre render callback.
  1429. *
  1430. * Appends the language tabs to the current local tasks area.
  1431. */
  1432. function entity_translation_language_tabs_render($element) {
  1433. $build = array(
  1434. '#theme' => 'menu_local_tasks',
  1435. '#theme_wrappers' => array('entity_translation_language_tabs'),
  1436. '#secondary' => $element['#language_tabs'],
  1437. '#attached' => array(
  1438. 'css' => array(drupal_get_path('module', 'entity_translation') . '/entity-translation.css'),
  1439. ),
  1440. );
  1441. $element['#suffix'] .= drupal_render($build);
  1442. return $element;
  1443. }
  1444. /**
  1445. * Theme wrapper for the entity translation language tabs.
  1446. */
  1447. function theme_entity_translation_language_tabs($variables) {
  1448. return '<div class="entity-translation-language-tabs">' . $variables['element']['#children'] . '</div>';
  1449. }
  1450. /**
  1451. * Implements hook_form_FORM_ID_alter().
  1452. *
  1453. * Adds an option to enable field synchronization.
  1454. * Enable a selector to choose whether a field is translatable.
  1455. */
  1456. function entity_translation_form_field_ui_field_edit_form_alter(&$form, $form_state) {
  1457. $instance = $form['#instance'];
  1458. $entity_type = $instance['entity_type'];
  1459. $field_name = $instance['field_name'];
  1460. $field = field_info_field($field_name);
  1461. if (!empty($field['settings']['entity_translation_sync']) && field_is_translatable($entity_type, $field)) {
  1462. $form['instance']['settings']['entity_translation_sync'] = array(
  1463. '#prefix' => '<label>' . t('Field synchronization') . '</label>',
  1464. '#type' => 'checkbox',
  1465. '#title' => t('Enable field synchronization'),
  1466. '#description' => t('Check this option if you wish to synchronize the value of this field across its translations.'),
  1467. '#default_value' => !empty($instance['settings']['entity_translation_sync']),
  1468. );
  1469. }
  1470. $translatable = $field['translatable'];
  1471. $label = t('Field translation');
  1472. $title = t('Users may translate all occurrences of this field:') . _entity_translation_field_desc($field);
  1473. if (field_has_data($field)) {
  1474. $path = "admin/config/regional/entity_translation/translatable/$field_name";
  1475. $status = $translatable ? $title : (t('All occurrences of this field are untranslatable:') . _entity_translation_field_desc($field));
  1476. $link_title = !$translatable ? t('Enable translation') : t('Disable translation');
  1477. $form['field']['translatable'] = array(
  1478. '#prefix' => '<div class="translatable"><label>' . $label . '</label>',
  1479. '#suffix' => '</div>',
  1480. 'message' => array(
  1481. '#markup' => $status . ' ',
  1482. ),
  1483. 'link' => array(
  1484. '#type' => 'link',
  1485. '#title' => $link_title,
  1486. '#href' => $path,
  1487. '#options' => array('query' => drupal_get_destination()),
  1488. '#access' => user_access('toggle field translatability'),
  1489. ),
  1490. );
  1491. }
  1492. else {
  1493. $form['field']['translatable'] = array(
  1494. '#prefix' => '<label>' . $label . '</label>',
  1495. '#type' => 'checkbox',
  1496. '#title' => $title,
  1497. '#default_value' => $translatable,
  1498. );
  1499. }
  1500. }
  1501. /**
  1502. * Returns a human-readable, localized, bullet list of instances of a field.
  1503. *
  1504. * @param field
  1505. * A field data structure.
  1506. *
  1507. * @return
  1508. * A themed list of field instances with the bundle they are attached to.
  1509. */
  1510. function _entity_translation_field_desc($field) {
  1511. $instances = array();
  1512. foreach ($field['bundles'] as $entity_type => $bundle_names) {
  1513. $entity_type_info = entity_get_info($entity_type);
  1514. foreach ($bundle_names as $bundle_name) {
  1515. $instance_info = field_info_instance($entity_type, $field['field_name'], $bundle_name);
  1516. $instances[] = t('@instance_label in %entity_label', array('@instance_label' => $instance_info['label'], '%entity_label' => $entity_type_info['bundles'][$bundle_name]['label']));
  1517. }
  1518. }
  1519. return theme('item_list', array('items' => $instances));
  1520. }
  1521. /**
  1522. * Determines whether the given entity type is translatable.
  1523. *
  1524. * @param $entity_type
  1525. * The entity type enabled for translation.
  1526. * @param $entity
  1527. * (optional) The entity belonging to the bundle enabled for translation. A
  1528. * bundle name can alternatively be passed. If an empty value is passed the
  1529. * bundle-level check is skipped. Defaults to NULL.
  1530. * @param $skip_handler
  1531. * (optional) A boolean indicating whether skip checking if the entity type is
  1532. * registered as a field translation handler. Defaults to FALSE.
  1533. */
  1534. function entity_translation_enabled($entity_type, $entity = NULL, $skip_handler = FALSE) {
  1535. $enabled_types = variable_get('entity_translation_entity_types', array());
  1536. $enabled = !empty($enabled_types[$entity_type]) && ($skip_handler || field_has_translation_handler($entity_type, 'entity_translation'));
  1537. // If the entity type is not enabled or we are not checking bundle status, we
  1538. // have a result.
  1539. if (!$enabled || !isset($entity)) {
  1540. return $enabled;
  1541. }
  1542. // Determine the bundle to check for translatability.
  1543. $bundle = FALSE;
  1544. if (is_object($entity)) {
  1545. list(, , $bundle) = entity_extract_ids($entity_type, $entity);
  1546. }
  1547. elseif (is_string($entity)) {
  1548. $bundle = $entity;
  1549. }
  1550. return $bundle && entity_translation_enabled_bundle($entity_type, $bundle);
  1551. }
  1552. /**
  1553. * Determines whether the given entity bundle is translatable.
  1554. *
  1555. * NOTE: Does not check for whether the entity type is translatable.
  1556. * Consider using entity_translation_enabled() instead.
  1557. *
  1558. * @param $entity_type
  1559. * The entity type the bundle to be checked belongs to.
  1560. * @param $bundle
  1561. * The name of the bundle to be checked.
  1562. */
  1563. function entity_translation_enabled_bundle($entity_type, $bundle) {
  1564. $info = entity_get_info($entity_type);
  1565. $bundle_callback = isset($info['translation']['entity_translation']['bundle callback']) ? $info['translation']['entity_translation']['bundle callback'] : FALSE;
  1566. return empty($bundle_callback) || call_user_func($bundle_callback, $bundle);
  1567. }
  1568. /**
  1569. * Return the entity translation settings for the given entity type and bundle.
  1570. */
  1571. function entity_translation_settings($entity_type, $bundle) {
  1572. $settings = variable_get('entity_translation_settings_' . $entity_type . '__' . $bundle, array());
  1573. if (empty($settings)) {
  1574. $info = entity_get_info($entity_type);
  1575. if (!empty($info['translation']['entity_translation']['default settings'])) {
  1576. $settings = $info['translation']['entity_translation']['default settings'];
  1577. }
  1578. }
  1579. $settings += array(
  1580. 'default_language' => ENTITY_TRANSLATION_LANGUAGE_DEFAULT,
  1581. 'hide_language_selector' => TRUE,
  1582. 'exclude_language_none' => FALSE,
  1583. 'lock_language' => FALSE,
  1584. 'shared_fields_original_only' => FALSE,
  1585. );
  1586. return $settings;
  1587. }
  1588. /**
  1589. * Entity language callback.
  1590. *
  1591. * This callback changes the entity language from the actual one to the active
  1592. * form language. This overriding allows to obtain language dependent form
  1593. * widgets where multilingual values are supported (e.g. field or path alias
  1594. * widgets) even if the code was not originally written with supporting multiple
  1595. * values per language in mind.
  1596. *
  1597. * The main drawback of this approach is that code needing to access the actual
  1598. * language in the entity form build/validation/submit workflow cannot rely on
  1599. * the entity_language() function. On the other hand in these scenarios assuming
  1600. * the presence of Entity translation should be safe, thus being able to rely on
  1601. * the EntityTranslationHandlerInterface::getLanguage() method.
  1602. *
  1603. * @param $entity_type
  1604. * The the type of the entity.
  1605. * @param $entity
  1606. * The entity whose language has to be returned.
  1607. *
  1608. * @return
  1609. * A valid language code.
  1610. */
  1611. function entity_translation_language($entity_type, $entity) {
  1612. $handler = entity_translation_get_handler($entity_type, $entity);
  1613. $langcode = $handler->getFormLanguage();
  1614. return !empty($langcode) ? $langcode : $handler->getLanguage();
  1615. }
  1616. /**
  1617. * Translation handler factory.
  1618. *
  1619. * @param $entity_type
  1620. * (optional) The type of $entity; e.g. 'node' or 'user'.
  1621. * @param $entity
  1622. * (optional) The entity to be translated. A bundle name may be passed to
  1623. * instantiate an empty entity.
  1624. *
  1625. * @return EntityTranslationHandlerInterface
  1626. * A class implementing EntityTranslationHandlerInterface.
  1627. */
  1628. function entity_translation_get_handler($entity_type = NULL, $entity = NULL) {
  1629. if (class_exists('EntityTranslationHandlerFactory')) {
  1630. $factory = EntityTranslationHandlerFactory::getInstance();
  1631. return empty($entity) ? $factory->getLastHandler($entity_type) : $factory->getHandler($entity_type, $entity);
  1632. }
  1633. // @todo BC layer. Remove before the first stable release.
  1634. elseif (!empty($entity_type) && is_object($entity)) {
  1635. $entity_info = entity_get_info($entity_type);
  1636. return new EntityTranslationDefaultHandler($entity_type, $entity_info, $entity);
  1637. }
  1638. }
  1639. /**
  1640. * Returns the translation handler wrapping the entity being edited.
  1641. *
  1642. * @param $form
  1643. * The entity form.
  1644. * @param $form_state
  1645. * A keyed array containing the current state of the form.
  1646. *
  1647. * @return EntityTranslationHandlerInterface
  1648. * A class implementing EntityTranslationHandlerInterface.
  1649. */
  1650. function entity_translation_entity_form_get_handler($form, $form_state) {
  1651. $handler = FALSE;
  1652. if ($info = entity_translation_edit_form_info($form, $form_state)) {
  1653. $handler = entity_translation_get_handler($info['entity type'], $info['entity']);
  1654. }
  1655. return $handler;
  1656. }
  1657. /**
  1658. * Returns the translation handler associated to the currently submitted form.
  1659. *
  1660. * @return EntityTranslationHandlerInterface
  1661. * A translation handler instance if available, FALSE oterwise.
  1662. *
  1663. * @deprecated This is no longer used and will be removed in the first stable
  1664. * release.
  1665. */
  1666. function entity_translation_current_form_get_handler() {
  1667. $handler = FALSE;
  1668. if (!empty($_POST['form_build_id'])) {
  1669. $form_state = form_state_defaults();
  1670. if ($form = form_get_cache($_POST['form_build_id'], $form_state)) {
  1671. $handler = entity_translation_entity_form_get_handler($form, $form_state);
  1672. }
  1673. }
  1674. return $handler;
  1675. }
  1676. /**
  1677. * Returns an array of edit form info as defined in hook_translation_info().
  1678. *
  1679. * @param $form
  1680. * The entity edit form.
  1681. * @param $form_state
  1682. * The entity edit form state.
  1683. *
  1684. * @return
  1685. * An edit form info array containing the entity to be translated in the
  1686. * 'entity' key.
  1687. */
  1688. function entity_translation_edit_form_info($form, $form_state) {
  1689. $info = FALSE;
  1690. $entity_type = isset($form['#entity_type']) && is_string($form['#entity_type']) ? $form['#entity_type'] : FALSE;
  1691. if ($entity_type) {
  1692. $entity_info = entity_get_info($form['#entity_type']);
  1693. if (!empty($entity_info['translation']['entity_translation']['edit form'])) {
  1694. $entity_keys = explode('][', $entity_info['translation']['entity_translation']['edit form']);
  1695. $key_exists = FALSE;
  1696. $entity = drupal_array_get_nested_value($form_state, $entity_keys, $key_exists);
  1697. if ($key_exists) {
  1698. $info = array(
  1699. 'entity type' => $form['#entity_type'],
  1700. 'entity' => (object) $entity,
  1701. );
  1702. }
  1703. }
  1704. }
  1705. return $info;
  1706. }
  1707. /**
  1708. * Checks whether an entity translation is accessible.
  1709. *
  1710. * @param $translation
  1711. * An array representing an entity translation.
  1712. *
  1713. * @return
  1714. * TRUE if the current user is allowed to view the translation.
  1715. */
  1716. function entity_translation_access($entity_type, $translation) {
  1717. return $translation['status'] || user_access('translate any entity') || user_access("translate $entity_type entities");
  1718. }
  1719. /**
  1720. * Returns the set of languages available for translations.
  1721. */
  1722. function entity_translation_languages($entity_type = NULL, $entity = NULL) {
  1723. if (isset($entity) && $entity_type == 'node' && module_exists('i18n_node')) {
  1724. // @todo Inherit i18n language settings.
  1725. }
  1726. elseif (variable_get('entity_translation_languages_enabled', FALSE)) {
  1727. $languages = language_list('enabled');
  1728. return $languages[1];
  1729. }
  1730. return language_list();
  1731. }
  1732. /**
  1733. * Implements hook_views_api().
  1734. */
  1735. function entity_translation_views_api() {
  1736. return array(
  1737. 'api' => 3,
  1738. 'path' => drupal_get_path('module', 'entity_translation') . '/views',
  1739. );
  1740. }
  1741. /**
  1742. * Implements hook_uuid_entities_features_export_entity_alter().
  1743. */
  1744. function entity_translation_uuid_entities_features_export_entity_alter($entity, $entity_type) {
  1745. // We do not need to export most of the keys:
  1746. // - The entity type is determined from the entity the translations are
  1747. // attached to.
  1748. // - The entity id will change from one site to another.
  1749. // - The user id needs to be removed because it will change as well.
  1750. // - Created and changed could be left but the UUID module removes created and
  1751. // changed values from the entities it exports, hence we do the same for
  1752. // consistency.
  1753. if (entity_translation_enabled($entity_type, $entity)) {
  1754. $fields = array('entity_type', 'entity_id', 'uid', 'created', 'changed');
  1755. $handler = entity_translation_get_handler($entity_type, $entity);
  1756. $translations = $handler->getTranslations();
  1757. if ($translations && isset($translations->data)) {
  1758. foreach ($translations->data as &$translation) {
  1759. foreach ($fields as $field) {
  1760. unset($translation[$field]);
  1761. }
  1762. }
  1763. }
  1764. }
  1765. }
  1766. /**
  1767. * Implements hook_entity_uuid_presave().
  1768. */
  1769. function entity_translation_entity_uuid_presave(&$entity, $entity_type) {
  1770. // UUID exports entities as arrays, therefore we need to cast the translations
  1771. // array back into an object.
  1772. $entity_info = entity_get_info($entity_type);
  1773. if (isset($entity_info['entity keys']) && isset($entity_info['entity keys']['translations'])) {
  1774. $key = $entity_info['entity keys']['translations'];
  1775. if (isset($entity->{$key})) {
  1776. $entity->{$key} = (object) $entity->{$key};
  1777. }
  1778. }
  1779. }
  1780. /**
  1781. * Implement hook_pathauto_alias_alter().
  1782. *
  1783. * When bulk-updating aliases for nodes automatically create a path for every
  1784. * translation.
  1785. */
  1786. function entity_translation_pathauto_alias_alter(&$alias, array &$context) {
  1787. $info = entity_get_info();
  1788. $entity_type = $context['module'];
  1789. // Ensure that we are dealing with a bundle having entity translation enabled.
  1790. if ($context['op'] == 'bulkupdate' && !empty($info[$entity_type]['token type']) && !empty($context['data'][$info[$entity_type]['token type']])) {
  1791. $entity = $context['data'][$info[$entity_type]['token type']];
  1792. if (entity_translation_enabled($entity_type, $entity)) {
  1793. $translations = entity_translation_get_handler($entity_type, $entity)->getTranslations();
  1794. // Only create extra aliases if we are working on the original language to
  1795. // avoid infinite recursion.
  1796. if ($context['language'] == $translations->original) {
  1797. foreach ($translations->data as $language => $translation) {
  1798. // We already have an alias for the original language, so let's not
  1799. // create another one.
  1800. if ($language == $translations->original) {
  1801. continue;
  1802. }
  1803. pathauto_create_alias($entity_type, $context['op'], $context['source'], $context['data'], $context['type'], $language);
  1804. }
  1805. }
  1806. }
  1807. }
  1808. }
  1809. /**
  1810. * Implements hook_entity_translation_delete().
  1811. */
  1812. function path_entity_translation_delete($entity_type, $entity, $langcode) {
  1813. // Remove any existing path alias for the removed translation.
  1814. $handler = entity_translation_get_handler($entity_type, $entity);
  1815. path_delete(array('source' => $handler->getViewPath(), 'language' => $langcode));
  1816. }