i18n_string.inc 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502
  1. <?php
  2. /**
  3. * @file
  4. * API for internationalization strings
  5. */
  6. /**
  7. * String object that contains source and translations.
  8. *
  9. * Note all database operations must go through textgroup object so we can switch storage at some point.
  10. */
  11. class i18n_string_object {
  12. // Updated source string
  13. public $string;
  14. // Properties from locale source
  15. public $lid;
  16. public $source;
  17. public $textgroup;
  18. public $location;
  19. public $context;
  20. public $version;
  21. // Properties from i18n_tring
  22. public $type;
  23. public $objectid;
  24. public $property;
  25. public $objectkey;
  26. public $format;
  27. // Properties from metadata
  28. public $title;
  29. // Array of translations to multiple languages
  30. public $translations = array();
  31. // Textgroup object
  32. protected $_textgroup;
  33. /**
  34. * Class constructor
  35. */
  36. public function __construct($data = NULL) {
  37. if ($data) {
  38. $this->set_properties($data);
  39. }
  40. // Attempt to re-build the data from the persistent cache.
  41. $this->rebuild_from_cache($data);
  42. }
  43. /**
  44. * Rebuild the object data based on the persistent cache.
  45. *
  46. * Since the textgroup defines if a string is cacheable or not the caching
  47. * of the string objects happens in the textgroup handler itself.
  48. *
  49. * @see i18n_string_textgroup_cached::__destruct()
  50. */
  51. protected function rebuild_from_cache($data = NULL) {
  52. // Check if we've the required information to repopulate the cache and do so
  53. // if possible.
  54. $meta_data_exist = isset($this->textgroup) && isset($this->type) && isset($this->objectid) && isset($this->property);
  55. if ($meta_data_exist && ($cache = cache_get($this->get_cid())) && !empty($cache->data)) {
  56. // Re-spawn the cached data.
  57. // @TODO do we need a array_diff to ensure we don't overwrite the data
  58. // provided by the $data parameter?
  59. $this->set_properties($cache->data);
  60. }
  61. }
  62. /**
  63. * Reset cache, needed for tests.
  64. */
  65. public function cache_reset() {
  66. $this->translations = array();
  67. // Ensure a possible persistent cache of this object is cleared too.
  68. cache_clear_all($this->get_cid(), 'cache', TRUE);
  69. }
  70. /**
  71. * Returns the caching id for this object.
  72. *
  73. * @return string
  74. * The caching id.
  75. */
  76. public function get_cid() {
  77. return 'i18n:string:obj:' . $this->get_name();
  78. }
  79. /**
  80. * Get message parameters from context and string.
  81. */
  82. public function get_args() {
  83. return array(
  84. '%location' => $this->location,
  85. '%textgroup' => $this->textgroup,
  86. '%string' => ($string = $this->get_string()) ? $string : t('[empty string]'),
  87. );
  88. }
  89. /**
  90. * Set context properties
  91. */
  92. public function set_context($context) {
  93. $parts = is_array($context) ? $context : explode(':', $context);
  94. $this->context = is_array($context) ? implode(':', $context) : $context;
  95. // Location will be the full string name
  96. $this->location = $this->textgroup . ':' . $this->context;
  97. $this->type = array_shift($parts);
  98. $this->objectid = $parts ? array_shift($parts) : '';
  99. $this->objectkey = (int)$this->objectid;
  100. // Remaining elements glued again with ':'
  101. $this->property = $parts ? implode(':', $parts) : '';
  102. // Attempt to re-build the other data from the persistent cache.
  103. $this->rebuild_from_cache();
  104. return $this;
  105. }
  106. /**
  107. * Get string name including textgroup and context
  108. */
  109. public function get_name() {
  110. return $this->textgroup . ':' . $this->type . ':' . $this->objectid . ':' . $this->property;
  111. }
  112. /**
  113. * Get source string
  114. */
  115. public function get_string() {
  116. if (isset($this->string)) {
  117. return $this->string;
  118. }
  119. elseif (isset($this->source)) {
  120. return $this->source;
  121. }
  122. elseif ($this->textgroup()->debug) {
  123. return empty($this->lid) ? t('[Source not found]') : t('[String not found]');
  124. }
  125. else {
  126. return '';
  127. }
  128. }
  129. /**
  130. * Set source string
  131. *
  132. * @param $string
  133. * Plain string or array with 'string', 'format', etc...
  134. */
  135. public function set_string($string) {
  136. if (is_array($string)) {
  137. $this->string = isset($string['string']) ? $string['string'] : NULL;
  138. if (isset($string['format'])) {
  139. $this->format = $string['format'];
  140. }
  141. if (isset($string['title'])) {
  142. $this->title = $string['title'];
  143. }
  144. }
  145. else {
  146. $this->string = $string;
  147. }
  148. return $this;
  149. }
  150. /**
  151. * Get string title.
  152. */
  153. public function get_title() {
  154. return isset($this->title) ? $this->title : t('String');
  155. }
  156. /**
  157. * Get translation to language from string object
  158. */
  159. public function get_translation($langcode) {
  160. if (!isset($this->translations[$langcode])) {
  161. $translation = $this->textgroup()->load_translation($this, $langcode);
  162. if ($translation && isset($translation->translation)) {
  163. $this->set_translation($translation, $langcode);
  164. }
  165. else {
  166. // No source, no translation
  167. $this->translations[$langcode] = FALSE;
  168. }
  169. }
  170. // Which doesn't mean we've got a translation, only that we've got the result cached
  171. return $this->translations[$langcode];
  172. }
  173. /**
  174. * Set translation for language
  175. *
  176. * @param $translation
  177. * Translation object (from database) or string
  178. */
  179. public function set_translation($translation, $langcode = NULL) {
  180. if (is_object($translation)) {
  181. $langcode = $langcode ? $langcode : $translation->language;
  182. $string = isset($translation->translation) ? $translation->translation : FALSE;
  183. $this->set_properties($translation);
  184. }
  185. else {
  186. $string = $translation;
  187. }
  188. $this->translations[$langcode] = $string;
  189. return $this;
  190. }
  191. /**
  192. * Format the resulting translation or the default string applying callbacks
  193. *
  194. * There's a hidden variable, 'i18n_string_debug', that when set to TRUE will display additional info
  195. */
  196. public function format_translation($langcode, $options = array()) {
  197. $options += array('langcode' => $langcode, 'sanitize' => TRUE, 'cache' => FALSE, 'debug' => $this->textgroup()->debug);
  198. if ($translation = $this->get_translation($langcode)) {
  199. $string = $translation;
  200. if (isset($options['filter'])) {
  201. $string = call_user_func($options['filter'], $string);
  202. }
  203. }
  204. else {
  205. // Get default source string if no translation.
  206. $string = $this->get_string();
  207. $options['sanitize'] = !empty($options['sanitize default']);
  208. }
  209. if (!empty($this->format)) {
  210. $options += array('format' => $this->format);
  211. }
  212. // Add debug information if enabled
  213. if ($options['debug']) {
  214. $info = array($langcode, $this->textgroup, $this->context);
  215. if (!empty($this->format)) {
  216. $info[] = $this->format;
  217. }
  218. $options += array('suffix' => '');
  219. $options['suffix'] .= ' [' . implode(':', $info) . ']';
  220. }
  221. // Finally, apply options, filters, callback, etc...
  222. return i18n_string_format($string, $options);
  223. }
  224. /**
  225. * Get source string provided a string object.
  226. *
  227. * @return
  228. * String object if source exists.
  229. */
  230. public function get_source() {
  231. // If already searched and not found we don't have a source,
  232. if (isset($this->lid) && !$this->lid) {
  233. return NULL;
  234. }
  235. elseif (!isset($this->lid) || !isset($this->source)) {
  236. // We may have lid from loading a translation but not loaded the source yet.
  237. if ($source = $this->textgroup()->load_source($this)) {
  238. // Set properties but don't override existing ones
  239. $this->set_properties($source, FALSE, FALSE);
  240. if (!isset($this->string)) {
  241. $this->string = $source->source;
  242. }
  243. return $this;
  244. }
  245. else {
  246. $this->lid = FALSE;
  247. return NULL;
  248. }
  249. }
  250. else {
  251. return $this;
  252. }
  253. }
  254. /**
  255. * Set properties from object or array
  256. *
  257. * @param $properties
  258. * Obejct or array of properties
  259. * @param $set_null
  260. * Whether to set null properties too
  261. * @param $override
  262. * Whether to set properties that are already set in this object
  263. */
  264. public function set_properties($properties, $set_null = TRUE, $override = TRUE) {
  265. foreach ((array)$properties as $field => $value) {
  266. if (property_exists($this, $field) && ($set_null || isset($value)) && ($override || !isset($this->$field))) {
  267. $this->$field = $value;
  268. }
  269. }
  270. return $this;
  271. }
  272. /**
  273. * Access textgroup object
  274. */
  275. protected function textgroup() {
  276. if (!isset($this->_textgroup)) {
  277. $this->_textgroup = i18n_string_textgroup($this->textgroup);
  278. }
  279. return $this->_textgroup;
  280. }
  281. /**
  282. * Update this string.
  283. */
  284. public function update($options = array()) {
  285. return $this->textgroup()->string_update($this, $options);
  286. }
  287. /**
  288. * Delete this string.
  289. */
  290. public function remove($options = array()) {
  291. return $this->textgroup()->string_remove($this, $options);
  292. }
  293. /**
  294. * Check whether there is any problem for the user to translate a this string.
  295. *
  296. * @param $account
  297. * Optional user account, defaults to current user.
  298. *
  299. * @return
  300. * None if the user has access to translate the string.
  301. * Error message if the user cannot translate that string.
  302. */
  303. public function check_translate_access($account = NULL) {
  304. return i18n_string_translate_check_string($this, $account);
  305. }
  306. }
  307. /**
  308. * Textgroup handler for i18n_string API
  309. */
  310. class i18n_string_textgroup_default {
  311. // Text group name
  312. public $textgroup;
  313. // Debug flag, set to true to print out more information.
  314. public $debug;
  315. // Cached or preloaded string objects
  316. public $strings = array();
  317. // Multiple translations search map
  318. protected $cache_multiple = array();
  319. /**
  320. * Class constructor.
  321. *
  322. * There are to hidden variables to produce debugging information:
  323. * - 'i18n_string_debug', generic for all text groups.
  324. * - 'i18n_string_debug_TEXTGROUP', enable debug only for TEXTGROUP.
  325. */
  326. public function __construct($textgroup) {
  327. $this->textgroup = $textgroup;
  328. $this->debug = variable_get('i18n_string_debug', FALSE) || variable_get('i18n_string_debug_' . $textgroup, FALSE);
  329. }
  330. /**
  331. * Build string object
  332. *
  333. * @param $context
  334. * Context array or string
  335. * @param $string string
  336. * Current value for string source
  337. */
  338. public function build_string($context, $string = NULL) {
  339. // First try to locate string on cache
  340. $context = is_array($context) ? implode(':', $context) : $context;
  341. if ($cached = $this->cache_get($context)) {
  342. $i18nstring = $cached;
  343. }
  344. else {
  345. $i18nstring = new i18n_string_object();
  346. $i18nstring->textgroup = $this->textgroup;
  347. $i18nstring->set_context($context);
  348. $this->cache_set($context, $i18nstring);
  349. }
  350. if (isset($string)) {
  351. $i18nstring->set_string($string);
  352. }
  353. return $i18nstring;
  354. }
  355. /**
  356. * Add source string to the locale tables for translation.
  357. *
  358. * It will also add data into i18n_string table for faster retrieval and indexing of groups of strings.
  359. * Some string context doesn't have a numeric oid (I.e. content types), it will be set to zero.
  360. *
  361. * This function checks for already existing string without context for this textgroup and updates it accordingly.
  362. * It is intended for backwards compatibility, using already created strings.
  363. *
  364. * @param $i18nstring
  365. * String object
  366. * @param $format
  367. * Text format, for strings that will go through some filter
  368. * @return
  369. * Update status.
  370. */
  371. protected function string_add($i18nstring, $options = array()) {
  372. $options += array('watchdog' => TRUE);
  373. // Default return status if nothing happens
  374. $status = -1;
  375. $source = NULL;
  376. $location = $i18nstring->location;
  377. // The string may not be allowed for translation depending on its format.
  378. if (!$this->string_check($i18nstring, $options)) {
  379. // The format may have changed and it's not allowed now, delete the source string
  380. return $this->string_remove($i18nstring, $options);
  381. }
  382. elseif ($source = $i18nstring->get_source()) {
  383. if ($source->source != $i18nstring->string || $source->location != $location) {
  384. $i18nstring->location = $location;
  385. // String has changed, mark translations for update
  386. $status = $this->save_source($i18nstring);
  387. db_update('locales_target')
  388. ->fields(array('i18n_status' => I18N_STRING_STATUS_UPDATE))
  389. ->condition('lid', $source->lid)
  390. ->execute();
  391. }
  392. elseif (empty($source->version)) {
  393. // When refreshing strings, we've done version = 0, update it
  394. $this->save_source($i18nstring);
  395. }
  396. }
  397. else {
  398. // We don't have the source object, create it
  399. $status = $this->save_source($i18nstring);
  400. }
  401. // Make sure we have i18n_string part, create or update
  402. // This will also create the source object if doesn't exist
  403. $this->save_string($i18nstring);
  404. if ($options['watchdog']) {
  405. switch ($status) {
  406. case SAVED_UPDATED:
  407. watchdog('i18n_string', 'Updated string %location for textgroup %textgroup: %string', $i18nstring->get_args());
  408. break;
  409. case SAVED_NEW:
  410. watchdog('i18n_string', 'Created string %location for text group %textgroup: %string', $i18nstring->get_args());
  411. break;
  412. }
  413. }
  414. return $status;
  415. }
  416. /**
  417. * Check if string is ok for translation
  418. */
  419. protected static function string_check($i18nstring, $options = array()) {
  420. $options += array('messages' => FALSE, 'watchdog' => TRUE);
  421. if (!empty($i18nstring->format) && !i18n_string_allowed_format($i18nstring->format)) {
  422. // This format is not allowed, so we remove the string, in this case we produce a warning
  423. drupal_set_message(t('The string %location for textgroup %textgroup is not allowed for translation because of its text format.', $i18nstring->get_args()), 'warning');
  424. return FALSE;
  425. }
  426. else {
  427. return TRUE;
  428. }
  429. }
  430. /**
  431. * Filter array of strings
  432. *
  433. * @param array $string_list
  434. * Array of strings to be filtered.
  435. * @param array $filter
  436. * Array of name value conditions.
  437. *
  438. * @return array
  439. * Strings from $string_list that match the filter conditions.
  440. */
  441. protected static function string_filter($string_list, $filter) {
  442. // Remove 'language' and '*' conditions.
  443. if (isset($filter['language'])) {
  444. unset($filter['language']);
  445. }
  446. while ($field = array_search('*', $filter)) {
  447. unset($filter[$field]);
  448. }
  449. foreach ($string_list as $key => $string) {
  450. foreach ($filter as $field => $value) {
  451. if ($string->$field != $value) {
  452. unset($string_list[$key]);
  453. break;
  454. }
  455. }
  456. }
  457. return $string_list;
  458. }
  459. /**
  460. * Build query for i18n_string table
  461. */
  462. protected static function string_query($context, $multiple = FALSE) {
  463. // Search the database using lid if we've got it or textgroup, context otherwise
  464. $query = db_select('i18n_string', 's')->fields('s');
  465. if (!empty($context->lid)) {
  466. $query->condition('s.lid', $context->lid);
  467. }
  468. else {
  469. $query->condition('s.textgroup', $context->textgroup);
  470. if (!$multiple) {
  471. $query->condition('s.context', $context->context);
  472. }
  473. else {
  474. // Query multiple strings
  475. foreach (array('type', 'objectid', 'property') as $field) {
  476. if (!empty($context->$field)) {
  477. $query->condition('s.' . $field, $context->$field);
  478. }
  479. }
  480. }
  481. }
  482. return $query;
  483. }
  484. /**
  485. * Remove string object.
  486. *
  487. * @return
  488. * SAVED_DELETED | FALSE (If the operation failed because no source)
  489. */
  490. public function string_remove($i18nstring, $options = array()) {
  491. $options += array('watchdog' => TRUE, 'messages' => $this->debug);
  492. if ($source = $i18nstring->get_source()) {
  493. db_delete('locales_target')->condition('lid', $source->lid)->execute();
  494. db_delete('i18n_string')->condition('lid', $source->lid)->execute();
  495. db_delete('locales_source')->condition('lid', $source->lid)->execute();
  496. $this->cache_set($source->context, NULL);
  497. if ($options['watchdog']) {
  498. watchdog('i18n_string', 'Deleted string %location for text group %textgroup: %string', $i18nstring->get_args());
  499. }
  500. if ($options['messages']) {
  501. drupal_set_message(t('Deleted string %location for text group %textgroup: %string', $i18nstring->get_args()));
  502. }
  503. return SAVED_DELETED;
  504. }
  505. else {
  506. if ($options['messages']) {
  507. drupal_set_message(t('Cannot delete string, not found %location for text group %textgroup: %string', $i18nstring->get_args()));
  508. }
  509. return FALSE;
  510. }
  511. }
  512. /**
  513. * Translate string object
  514. *
  515. * @param $i18nstring
  516. * String object
  517. * @param $options
  518. * Array with aditional options
  519. */
  520. protected function string_translate($i18nstring, $options = array()) {
  521. $langcode = isset($options['langcode']) ? $options['langcode'] : i18n_langcode();
  522. // Search for existing translation (result will be cached in this function call)
  523. $i18nstring->get_translation($langcode);
  524. return $i18nstring;
  525. }
  526. /**
  527. * Update / create / remove string.
  528. *
  529. * @param $name
  530. * String context.
  531. * @pram $string
  532. * New value of string for update/create. May be empty for removing.
  533. * @param $format
  534. * Text format, that must have been checked against allowed formats for translation
  535. * @param $options
  536. * Processing options, the ones used here are:
  537. * - 'watchdog', whether to produce watchdog messages.
  538. * - 'messages', whether to produce user messages.
  539. * - 'check', whether to check string format and then update/delete if not allowed.
  540. * @return status
  541. * SAVED_UPDATED | SAVED_NEW | SAVED_DELETED | FALSE (If the string is to be removed but has no source)
  542. */
  543. public function string_update($i18nstring, $options = array()) {
  544. $options += array('watchdog' => TRUE, 'messages' => $this->debug, 'check' => TRUE);
  545. if ((!$options['check'] || $this->string_check($i18nstring, $options)) && $i18nstring->get_string()) {
  546. // String is ok, has a value so we store it into the database.
  547. $status = $this->string_add($i18nstring, $options);
  548. }
  549. elseif ($i18nstring->get_source()) {
  550. // Just remove it if we already had a source created before.
  551. $status = $this->string_remove($i18nstring, $options);
  552. }
  553. else {
  554. // String didn't pass validation or we have an empty string but was not stored anyway.
  555. $status = FALSE;
  556. }
  557. if ($options['messages']) {
  558. switch ($status) {
  559. case SAVED_UPDATED:
  560. drupal_set_message(t('Updated string %location for text group %textgroup: %string', $i18nstring->get_args()));
  561. break;
  562. case SAVED_NEW:
  563. drupal_set_message(t('Created string %location for text group %textgroup: %string', $i18nstring->get_args()));
  564. break;
  565. }
  566. }
  567. if ($options['watchdog']) {
  568. switch ($status) {
  569. case SAVED_UPDATED:
  570. watchdog('i18n_string', 'Updated string %location for text group %textgroup: %string', $i18nstring->get_args());
  571. break;
  572. case SAVED_NEW:
  573. watchdog('i18n_string', 'Created string %location for text group %textgroup: %string', $i18nstring->get_args());
  574. break;
  575. }
  576. }
  577. return $status;
  578. }
  579. /**
  580. * Set string object into cache
  581. */
  582. protected function cache_set($context, $string) {
  583. $this->strings[$context] = $string;
  584. }
  585. /**
  586. * Get translation from cache
  587. */
  588. protected function cache_get($context) {
  589. return isset($this->strings[$context]) ? $this->strings[$context] : NULL;
  590. }
  591. /**
  592. * Reset cache, needed for tests
  593. */
  594. public function cache_reset() {
  595. $this->strings = array();
  596. $this->string_format = array();
  597. // Reset the persistent caches.
  598. cache_clear_all('i18n:string:tgroup:' . $this->textgroup , 'cache', TRUE);
  599. // Reset the complete string object cache too.
  600. cache_clear_all('i18n:string:obj:', 'cache', TRUE);
  601. }
  602. /**
  603. * Load multiple strings.
  604. *
  605. * @return array
  606. * List of strings indexed by full string name.
  607. */
  608. public function load_strings($conditions = array()) {
  609. // Add textgroup condition and load all
  610. $conditions['textgroup'] = $this->textgroup;
  611. $list = array();
  612. foreach (i18n_string_load_multiple($conditions) as $string) {
  613. $list[$string->get_name()] = $string;
  614. $this->cache_set($string->context, $string);
  615. }
  616. return $list;
  617. }
  618. /**
  619. * Load string source from db
  620. */
  621. public static function load_source($i18nstring) {
  622. // Search the database using lid if we've got it or textgroup, context otherwise
  623. $query = db_select('locales_source', 's')->fields('s');
  624. $query->leftJoin('i18n_string', 'i', 's.lid = i.lid');
  625. $query->fields('i', array('format', 'objectid', 'type', 'property', 'objectindex'));
  626. if (!empty($i18nstring->lid)) {
  627. $query->condition('s.lid', $i18nstring->lid);
  628. }
  629. else {
  630. $query->condition('s.textgroup', $i18nstring->textgroup);
  631. $query->condition('s.context', $i18nstring->context);
  632. }
  633. // Speed up the query, we just need one row
  634. return $query->range(0, 1)->execute()->fetchObject();
  635. }
  636. /**
  637. * Load translation from db
  638. *
  639. * @todo Optimize when we've already got the source string
  640. */
  641. public static function load_translation($i18nstring, $langcode) {
  642. // Search the database using lid if we've got it or textgroup, context otherwise
  643. if (!empty($i18nstring->lid)) {
  644. // We've already got lid, we just need translation data
  645. $query = db_select('locales_target', 't');
  646. $query->condition('t.lid', $i18nstring->lid);
  647. }
  648. else {
  649. // Still don't have lid, load string properties too
  650. $query = db_select('i18n_string', 's')->fields('s');
  651. $query->leftJoin('locales_target', 't', 's.lid = t.lid');
  652. $query->condition('s.textgroup', $i18nstring->textgroup);
  653. $query->condition('s.context', $i18nstring->context);
  654. }
  655. // Add translation fields
  656. $query->fields('t', array('translation', 'i18n_status'));
  657. $query->condition('t.language', $langcode);
  658. // Speed up the query, we just need one row
  659. $query->range(0, 1);
  660. return $query->execute()->fetchObject();
  661. }
  662. /**
  663. * Save / update string object
  664. *
  665. * There seems to be a race condition sometimes so skip errors, #277711
  666. *
  667. * @param $string
  668. * Full string object to be saved
  669. * @param $source
  670. * Source string object
  671. */
  672. protected function save_string($string, $update = FALSE) {
  673. if (!$string->get_source()) {
  674. // Create source string so we get an lid
  675. $this->save_source($string);
  676. }
  677. if (!isset($string->objectkey)) {
  678. $string->objectkey = (int)$string->objectid;
  679. }
  680. if (!isset($string->format)) {
  681. $string->format = '';
  682. }
  683. $status = db_merge('i18n_string')
  684. ->key(array('lid' => $string->lid))
  685. ->fields(array(
  686. 'textgroup' => $string->textgroup,
  687. 'context' => $string->context,
  688. 'objectid' => $string->objectid,
  689. 'type' => $string->type,
  690. 'property' => $string->property,
  691. 'objectindex' => $string->objectkey,
  692. 'format' => $string->format,
  693. ))
  694. ->execute();
  695. return $status;
  696. }
  697. /**
  698. * Save translation to the db
  699. *
  700. * @param $string
  701. * Full string object with translation data (language, translation)
  702. */
  703. protected function save_translation($string, $langcode) {
  704. db_merge('locales_target')
  705. ->key(array('lid' => $string->lid, 'language' => $langcode))
  706. ->fields(array('translation' => $string->get_translation($langcode)))
  707. ->execute();
  708. }
  709. /**
  710. * Save source string (create / update)
  711. */
  712. protected static function save_source($source) {
  713. if (isset($source->string)) {
  714. $source->source = $source->string;
  715. }
  716. if (empty($source->version)) {
  717. $source->version = 1;
  718. }
  719. return drupal_write_record('locales_source', $source, !empty($source->lid) ? 'lid' : array());
  720. }
  721. /**
  722. * Remove source and translations for user defined string.
  723. *
  724. * Though for most strings the 'name' or 'string id' uniquely identifies that string,
  725. * there are some exceptions (like profile categories) for which we need to use the
  726. * source string itself as a search key.
  727. *
  728. * @param $context
  729. * Textgroup and location glued with ':'.
  730. * @param $string
  731. * Optional source string (string in default language).
  732. */
  733. public function context_remove($context, $string = NULL, $options = array()) {
  734. $options += array('messages' => $this->debug);
  735. $i18nstring = $this->build_string($context, $string);
  736. $status = $this->string_remove($i18nstring, $options);
  737. return $this;
  738. }
  739. /**
  740. * Translate source string
  741. */
  742. public function context_translate($context, $string, $options = array()) {
  743. $i18nstring = $this->build_string($context, $string);
  744. return $this->string_translate($i18nstring, $options);
  745. }
  746. /**
  747. * Update / create translation source for user defined strings.
  748. *
  749. * @param $name
  750. * Textgroup and location glued with ':'.
  751. * @param $string
  752. * Source string in default language. Default language may or may not be English.
  753. * @param $options
  754. * Array with additional options:
  755. * - 'format', String format if the string has text format.
  756. * - 'messages', Whether to print out status messages.
  757. * - 'check', whether to check string format and then update/delete if not allowed.
  758. */
  759. public function context_update($context, $string, $options = array()) {
  760. $options += array('format' => FALSE, 'messages' => $this->debug, 'watchdog' => TRUE, 'check' => TRUE);
  761. $i18nstring = $this->build_string($context, $string);
  762. $i18nstring->format = $options['format'];
  763. $this->string_update($i18nstring, $options);
  764. return $this;
  765. }
  766. /**
  767. * Build combinations of an array of arrays respecting keys.
  768. *
  769. * Example:
  770. * array(array(a,b), array(1,2)) will translate into
  771. * array(a,1), array(a,2), array(b,1), array(b,2)
  772. */
  773. protected static function multiple_combine($properties) {
  774. $combinations = array();
  775. // Get first key, value. We need to make sure the array pointer is reset.
  776. $value = reset($properties);
  777. $key = key($properties);
  778. array_shift($properties);
  779. $values = is_array($value) ? $value : array($value);
  780. foreach ($values as $value) {
  781. if ($properties) {
  782. foreach (self::multiple_combine($properties) as $merge) {
  783. $combinations[] = array_merge(array($key => $value), $merge);
  784. }
  785. }
  786. else {
  787. $combinations[] = array($key => $value);
  788. }
  789. }
  790. return $combinations;
  791. }
  792. /**
  793. * Get multiple translations with search conditions.
  794. *
  795. * @param $translations
  796. * Array of translation objects as loaded from the db.
  797. * @param $langcode
  798. * Language code, array of language codes or * to search all translations.
  799. *
  800. * @return array
  801. * Array of i18n string objects.
  802. */
  803. protected function multiple_translation_build($translations, $langcode) {
  804. $strings = array();
  805. foreach ($translations as $translation) {
  806. // The string object may be already in list
  807. if (isset($strings[$translation->context])) {
  808. $string = $strings[$translation->context];
  809. }
  810. else {
  811. $string = $this->build_string($translation->context);
  812. $string->set_properties($translation);
  813. $strings[$string->context] = $string;
  814. }
  815. // If this is a translation we set it there too
  816. if ($translation->language && $translation->translation) {
  817. $string->set_translation($translation);
  818. }
  819. elseif ($langcode) {
  820. // This may only happen when we have a source string but not translation.
  821. $string->set_translation(FALSE, $langcode);
  822. }
  823. }
  824. return $strings;
  825. }
  826. /**
  827. * Load multiple translations from db
  828. *
  829. * @todo Optimize when we've already got the source object
  830. *
  831. * @param $conditions
  832. * Array of field values to use as query conditions.
  833. * @param $langcode
  834. * Language code to search.
  835. * @param $index
  836. * Field to use as index for the result.
  837. * @return array
  838. * Array of string objects with translation set.
  839. */
  840. protected function multiple_translation_load($conditions, $langcode) {
  841. $conditions += array(
  842. 'language' => $langcode,
  843. 'textgroup' => $this->textgroup
  844. );
  845. // We may be querying all translations at the same time or just one language.
  846. // The language field needs some special treatment though.
  847. $query = db_select('i18n_string', 's')->fields('s');
  848. $query->leftJoin('locales_target', 't', 's.lid = t.lid');
  849. $query->fields('t', array('translation', 'language', 'i18n_status'));
  850. foreach ($conditions as $field => $value) {
  851. // Single array value, reduce array
  852. if (is_array($value) && count($value) == 1) {
  853. $value = reset($value);
  854. }
  855. if ($value === '*') {
  856. continue;
  857. }
  858. elseif ($field == 'language') {
  859. $query->condition('t.language', $value);
  860. }
  861. else {
  862. $query->condition('s.' . $field, $value);
  863. }
  864. }
  865. return $this->multiple_translation_build($query->execute()->fetchAll(), $langcode);
  866. }
  867. /**
  868. * Search multiple translations with key combinations.
  869. *
  870. * Each $context field may be a single value, an array of values or '*'.
  871. * Example:
  872. * array('term', array(1,2), '*')
  873. * This will be mapped into the following conditions (provided language code is 'es')
  874. * array('type' => 'term', 'objectid' => array(1,2), 'property' => '*', 'language' => 'es')
  875. * And will result in these combinations to search for
  876. * array('type' => 'term', 'objectid' => 1, 'property' => '*', 'language' => 'es')
  877. * array('type' => 'term', 'objectid' => 2, 'property' => '*', 'language' => 'es')
  878. *
  879. * @param $context array
  880. * Array with String context conditions.
  881. *
  882. * @return
  883. * Array of translation objects indexed by context.
  884. */
  885. public function multiple_translation_search($context, $langcode) {
  886. // First, build conditions and identify the variable field.
  887. $keys = array('type', 'objectid', 'property');
  888. $conditions = array_combine($keys, $context) + array('language' => $langcode);
  889. // Find existing searches in cache, compile remaining ones.
  890. $translations = $search = array();
  891. foreach ($this->multiple_combine($conditions) as $combination) {
  892. $cached = $this->multiple_cache_get($combination);
  893. if (isset($cached)) {
  894. // Cache hit. Merge and remove value from search.
  895. $translations += $cached;
  896. }
  897. else {
  898. // Not in cache, add to search conditions skipping duplicated values.
  899. // As array_merge_recursive() has some bug in PHP 5.2, http://drupal.org/node/1244598
  900. // we use our simplified version here, instead of $search = array_merge_recursive($search, $combination);
  901. foreach ($combination as $key => $value) {
  902. if (!isset($search[$key]) || !in_array($value, $search[$key], TRUE)) {
  903. $search[$key][] = $value;
  904. }
  905. }
  906. }
  907. }
  908. // If we've got any search values left, find translations.
  909. if ($search) {
  910. // Load translations for conditions and set them to the cache
  911. $loaded = $this->multiple_translation_load($search, $langcode);
  912. if ($loaded) {
  913. $translations += $loaded;
  914. }
  915. // Set cache for each of the multiple search keys.
  916. foreach ($this->multiple_combine($search) as $combination) {
  917. $list = $loaded ? $this->string_filter($loaded, $combination) : array();
  918. $this->multiple_cache_set($combination, $list);
  919. }
  920. }
  921. return $translations;
  922. }
  923. /**
  924. * Set multiple cache.
  925. *
  926. * @param $context
  927. * String context with language property at the end.
  928. * @param $strings
  929. * Array of strings (may be empty) to cache.
  930. */
  931. protected function multiple_cache_set($context, $strings) {
  932. $cache_key = implode(':', $context);
  933. $this->cache_multiple[$cache_key] = $strings;
  934. }
  935. /**
  936. * Get strings from multiple cache.
  937. *
  938. * @param $context array
  939. * String context as array with language property at the end.
  940. *
  941. * @return mixed
  942. * Array of strings (may be empty) if we've got a cache hit.
  943. * Null otherwise.
  944. */
  945. protected function multiple_cache_get($context) {
  946. $cache_key = implode(':', $context);
  947. if (isset($this->cache_multiple[$cache_key])) {
  948. return $this->cache_multiple[$cache_key];
  949. }
  950. else {
  951. // Now we try more generic keys. For instance, if we are searching 'term:1:*'
  952. // we may try too 'term:*:*' and filter out the results.
  953. foreach ($context as $key => $value) {
  954. if ($value != '*') {
  955. $try = array_merge($context, array($key => '*'));
  956. $cache_key = implode(':', $try);
  957. if (isset($this->cache_multiple[$cache_key])) {
  958. // As we've found some more generic key, we need to filter using original conditions.
  959. $strings = $this->string_filter($this->cache_multiple[$cache_key], $context);
  960. return $strings;
  961. }
  962. }
  963. }
  964. // If we've reached here, we didn't find any cache match.
  965. return NULL;
  966. }
  967. }
  968. /**
  969. * Translate array of source strings
  970. *
  971. * @param $context
  972. * Context array with placeholders (*)
  973. * @param $strings
  974. * Optional array of source strings indexed by the placeholder property
  975. *
  976. * @return array
  977. * Array of string objects (with translation) indexed by the placeholder field
  978. */
  979. public function multiple_translate($context, $strings = array(), $options = array()) {
  980. // First, build conditions and identify the variable field
  981. $search = $context = array_combine(array('type', 'objectid', 'property'), $context);
  982. $langcode = isset($options['langcode']) ? $options['langcode'] : i18n_langcode();
  983. // If we've got keyed source strings set the array of keys on the placeholder field
  984. // or if not, remove that condition so we search all strings with that keys.
  985. foreach ($search as $field => $value) {
  986. if ($value === '*') {
  987. $property = $field;
  988. if ($strings) {
  989. $search[$field] = array_keys($strings);
  990. }
  991. }
  992. }
  993. // Now we'll add the language code to conditions and get the translations indexed by the property field
  994. $result = $this->multiple_translation_search($search, $langcode);
  995. // Remap translations using property field. If we've got strings it is important that they are in the same order.
  996. $translations = $strings;
  997. foreach ($result as $key => $i18nstring) {
  998. $translations[$i18nstring->$property] = $i18nstring;
  999. }
  1000. // Set strings as source or create
  1001. foreach ($strings as $key => $source) {
  1002. if (isset($translations[$key]) && is_object($translations[$key])) {
  1003. $translations[$key]->set_string($source);
  1004. }
  1005. else {
  1006. // Not found any string for this property, create it to map in the response
  1007. // But make sure we set this language's translation to FALSE so we don't search again
  1008. $newcontext = $context;
  1009. $newcontext[$property] = $key;
  1010. $translations[$key] = $this->build_string($newcontext)
  1011. ->set_string($source)
  1012. ->set_translation(FALSE, $langcode);
  1013. }
  1014. }
  1015. return $translations;
  1016. }
  1017. /**
  1018. * Update string translation, only if source exists.
  1019. *
  1020. * @param $context
  1021. * String context as array
  1022. * @param $langcode
  1023. * Language code to create the translation for
  1024. * @param $translation
  1025. * String translation for this language
  1026. */
  1027. function update_translation($context, $langcode, $translation) {
  1028. $i18nstring = $this->build_string($context);
  1029. if ($source = $i18nstring->get_source()) {
  1030. $source->set_translation($translation, $langcode);
  1031. $this->save_translation($source, $langcode);
  1032. return $source;
  1033. }
  1034. }
  1035. /**
  1036. * Recheck strings after update
  1037. */
  1038. public function update_check() {
  1039. // Find strings in locales_source that have no data in i18n_string
  1040. $query = db_select('locales_source', 'l')
  1041. ->fields('l')
  1042. ->condition('l.textgroup', $this->textgroup);
  1043. $alias = $query->leftJoin('i18n_string', 's', 'l.lid = s.lid');
  1044. $query->isNull('s.lid');
  1045. foreach ($query->execute()->fetchAll() as $string) {
  1046. $i18nstring = $this->build_string($string->context, $string->source);
  1047. $this->save_string($i18nstring);
  1048. }
  1049. }
  1050. }
  1051. /**
  1052. * String object wrapper
  1053. */
  1054. class i18n_string_object_wrapper extends i18n_object_wrapper {
  1055. // Text group object
  1056. protected $textgroup;
  1057. // Properties for translation
  1058. protected $properties;
  1059. /**
  1060. * Get object strings for translation
  1061. *
  1062. * This will return a simple array of string objects, indexed by full string name.
  1063. *
  1064. * @param $options
  1065. * Array with processing options.
  1066. * - 'empty', whether to return empty strings, defaults to FALSE.
  1067. */
  1068. public function get_strings($options = array()) {
  1069. $options += array('empty' => FALSE);
  1070. $strings = array();
  1071. foreach ($this->get_properties() as $textgroup => $textgroup_list) {
  1072. foreach ($textgroup_list as $type => $type_list) {
  1073. foreach ($type_list as $object_id => $object_list) {
  1074. foreach ($object_list as $key => $string) {
  1075. if ($options['empty'] || !empty($string['string'])) {
  1076. // Build string object, that will trigger static caches everywhere.
  1077. $i18nstring = i18n_string_textgroup($textgroup)
  1078. ->build_string(array($type, $object_id, $key))
  1079. ->set_string($string);
  1080. $strings[$i18nstring->get_name()] = $i18nstring;
  1081. }
  1082. }
  1083. }
  1084. }
  1085. }
  1086. return $strings;
  1087. }
  1088. /**
  1089. * Get object translatable properties
  1090. *
  1091. * This will return a big array indexed by textgroup, object type, object id and string key.
  1092. * Each element is an array with string information, and may have these properties:
  1093. * - 'string', the string itself, will be NULL if the object doesn't have that string
  1094. * - 'format', string format when needed
  1095. * - 'title', string readable name
  1096. */
  1097. public function get_properties() {
  1098. if (!isset($this->properties)) {
  1099. $this->properties = $this->build_properties();
  1100. // Call hook_i18n_string_list_TEXTGROUP_alter(), last chance for modules
  1101. drupal_alter('i18n_string_list_' . $this->get_textgroup(), $this->properties, $this->type, $this->object);
  1102. }
  1103. return $this->properties;
  1104. }
  1105. /**
  1106. * Build properties from object.
  1107. */
  1108. protected function build_properties() {
  1109. list($string_type, $object_id) = $this->get_string_context();
  1110. $object_keys = array(
  1111. $this->get_textgroup(),
  1112. $string_type,
  1113. $object_id,
  1114. );
  1115. $strings = array();
  1116. foreach ($this->get_string_info('properties', array()) as $field => $info) {
  1117. $info = is_array($info) ? $info : array('title' => $info);
  1118. $field_name = isset($info['field']) ? $info['field'] : $field;
  1119. $value = $this->get_field($field_name);
  1120. $strings[$this->get_textgroup()][$string_type][$object_id][$field] = array(
  1121. 'string' => is_array($value) || isset($info['empty']) && $value === $info['empty'] ? NULL : $value,
  1122. 'title' => $info['title'],
  1123. 'format' => isset($info['format']) ? $this->get_field($info['format']) : NULL,
  1124. 'name' => array_merge($object_keys, array($field)),
  1125. );
  1126. }
  1127. return $strings;
  1128. }
  1129. /**
  1130. * Get string context
  1131. */
  1132. public function get_string_context() {
  1133. return array($this->get_string_info('type'), $this->get_key());
  1134. }
  1135. /**
  1136. * Get translate path for object
  1137. *
  1138. * @param $langcode
  1139. * Language code if we want ti for a specific language
  1140. */
  1141. public function get_translate_path($langcode = NULL) {
  1142. $replacements = array('%i18n_language' => $langcode ? $langcode : '');
  1143. if ($path = $this->get_string_info('translate path')) {
  1144. return $this->path_replace($path, $replacements);
  1145. }
  1146. elseif ($path = $this->get_info('translate tab')) {
  1147. // If we've got a translate tab path, we just add language to it
  1148. return $this->path_replace($path . '/%i18n_language', $replacements);
  1149. }
  1150. }
  1151. /**
  1152. * Translation mode for object
  1153. */
  1154. public function get_translate_mode() {
  1155. return !$this->get_langcode() ? I18N_MODE_LOCALIZE : I18N_MODE_NONE;
  1156. }
  1157. /**
  1158. * Get textgroup name
  1159. */
  1160. public function get_textgroup() {
  1161. return $this->get_string_info('textgroup');
  1162. }
  1163. /**
  1164. * Get textgroup object
  1165. */
  1166. protected function textgroup() {
  1167. if (!isset($this->textgroup)) {
  1168. $this->textgroup = i18n_string_textgroup($this->get_textgroup());
  1169. }
  1170. return $this->textgroup;
  1171. }
  1172. /**
  1173. * Translate object.
  1174. *
  1175. * Translations are cached so it runs only once per language.
  1176. *
  1177. * @return object/array
  1178. * A clone of the object with its properties translated.
  1179. */
  1180. public function translate($langcode, $options = array()) {
  1181. // We may have it already translated. As objects are statically cached, translations are too.
  1182. if (!isset($this->translations[$langcode])) {
  1183. $this->translations[$langcode] = $this->translate_object($langcode, $options);
  1184. }
  1185. return $this->translations[$langcode];
  1186. }
  1187. /**
  1188. * Translate access (localize strings)
  1189. */
  1190. protected function localize_access() {
  1191. // We could check also whether the object has strings to translate:
  1192. // && $this->get_strings(array('empty' => TRUE))
  1193. // However it may be better to display the 'No available strings' message
  1194. // for the user to have a clue of what's going on. See i18n_string_translate_page_object()
  1195. return user_access('translate interface') && user_access('translate user-defined strings');
  1196. }
  1197. /**
  1198. * Translate all properties for object.
  1199. *
  1200. * On top of object strings we search for all textgroup:type:objectid:* properties
  1201. *
  1202. * @param $langcode
  1203. * A clone of the object or array
  1204. */
  1205. protected function translate_object($langcode, $options) {
  1206. // Clone object or array so we don't affect the original one.
  1207. $object = is_object($this->object) ? clone $this->object : $this->object;
  1208. // Get object strings for translatable properties.
  1209. if ($strings = $this->get_strings()) {
  1210. // We preload some of the property translations with a single query.
  1211. if ($context = $this->get_translate_context($langcode, $options)) {
  1212. $found = $this->textgroup()->multiple_translation_search($context, $langcode);
  1213. }
  1214. // Replace all strings in object.
  1215. foreach ($strings as $i18nstring) {
  1216. $this->translate_field($object, $i18nstring, $langcode, $options);
  1217. }
  1218. }
  1219. return $object;
  1220. }
  1221. /**
  1222. * Context to be pre-loaded before translation.
  1223. */
  1224. protected function get_translate_context($langcode, $options) {
  1225. // One-query translation of all textgroup:type:objectid:* properties
  1226. $context = $this->get_string_context();
  1227. $context[] = '*';
  1228. return $context;
  1229. }
  1230. /**
  1231. * Translate object property.
  1232. *
  1233. * Mot often, this is a direct field set, but sometimes fields may have different formats.
  1234. */
  1235. protected function translate_field(&$object, $i18nstring, $langcode, $options) {
  1236. $field_name = $i18nstring->property;
  1237. $translation = $i18nstring->format_translation($langcode, $options);
  1238. if (is_object($object)) {
  1239. $object->$field_name = $translation;
  1240. }
  1241. elseif (is_array($object)) {
  1242. $object[$field_name] = $translation;
  1243. }
  1244. }
  1245. /**
  1246. * Remove all strings for this object.
  1247. */
  1248. public function strings_remove($options = array()) {
  1249. $result = array();
  1250. foreach ($this->load_strings() as $key => $string) {
  1251. $result[$key] = $string->remove($options);
  1252. }
  1253. return _i18n_string_result_count($result);
  1254. }
  1255. /**
  1256. * Update all strings for this object.
  1257. */
  1258. public function strings_update($options = array()) {
  1259. $options += array('empty' => TRUE, 'update' => TRUE);
  1260. $result = array();
  1261. $existing = $this->load_strings();
  1262. // Update object strings
  1263. foreach ($this->get_strings($options) as $key => $string) {
  1264. $result[$key] = $string->update($options);
  1265. unset($existing[$key]);
  1266. }
  1267. // Delete old existing strings.
  1268. foreach ($existing as $key => $string) {
  1269. $result[$key] = $string->remove($options);
  1270. }
  1271. return _i18n_string_result_count($result);
  1272. }
  1273. /**
  1274. * Load all existing strings for this object.
  1275. */
  1276. public function load_strings() {
  1277. list($type, $id) = $this->get_string_context();
  1278. return $this->textgroup()->load_strings(array('type' => $type, 'objectid' => $id));
  1279. }
  1280. }
  1281. /**
  1282. * Textgroup handler for i18n_string API which integrated persistent caching.
  1283. */
  1284. class i18n_string_textgroup_cached extends i18n_string_textgroup_default {
  1285. /**
  1286. * Defines the timeout for the persistent caching.
  1287. * @var int
  1288. */
  1289. public $caching_time = CACHE_TEMPORARY;
  1290. /**
  1291. * Extends the existing constructor with a cache handling.
  1292. *
  1293. * @param string $textgroup
  1294. * The name of this textgroup.
  1295. */
  1296. public function __construct($textgroup) {
  1297. parent::__construct($textgroup);
  1298. // Fetch persistent caches, the persistent caches contain only metadata.
  1299. // Those metadata are processed by the related cache_get() methods.
  1300. foreach (array('cache_multiple', 'strings') as $caches_type) {
  1301. if (($cache = cache_get('i18n:string:tgroup:' . $this->textgroup . ':' . $caches_type)) && !empty($cache->data)) {
  1302. $this->{$caches_type} = $cache->data;
  1303. }
  1304. }
  1305. }
  1306. /**
  1307. * Class destructor.
  1308. *
  1309. * Updates the persistent caches for the next usage.
  1310. * This function not only stores the data of the textgroup objects but also
  1311. * of the string objects. That way we ensure that only cacheable string object
  1312. * go into the persistent cache.
  1313. */
  1314. public function __destruct() {
  1315. // Reduce size to cache by removing NULL values.
  1316. $this->strings = array_filter($this->strings);
  1317. $strings_to_cache = array();
  1318. // Store the persistent caches. We just store the metadata the translations
  1319. // are stored by the string object itself. However storing the metadata
  1320. // reduces the number of DB queries executed during runtime.
  1321. $cache_data = array();
  1322. foreach ($this->strings as $context => $i18n_string_object) {
  1323. $cache_data[$context] = $context;
  1324. $strings_to_cache[$context] = $i18n_string_object;
  1325. }
  1326. cache_set('i18n:string:tgroup:' . $this->textgroup . ':strings', $cache_data, 'cache', $this->caching_time);
  1327. $cache_data = array();
  1328. foreach ($this->cache_multiple as $pattern => $strings) {
  1329. foreach ($strings as $context => $i18n_string_object) {
  1330. $cache_data[$pattern][$context] = $context;
  1331. $strings_to_cache[$context] = $i18n_string_object;
  1332. }
  1333. }
  1334. cache_set('i18n:string:tgroup:' . $this->textgroup . ':cache_multiple', $cache_data, 'cache', $this->caching_time);
  1335. // Cache the string objects related to this textgroup.
  1336. // Store only the public visible data into the persistent cache.
  1337. foreach ($strings_to_cache as $i18n_string_object) {
  1338. // If this isn't an object it's an unprocessed cache item and doesn't need
  1339. // to be stored again.
  1340. if (is_object($i18n_string_object)) {
  1341. cache_set($i18n_string_object->get_cid(), get_object_vars($i18n_string_object), 'cache', $this->caching_time);
  1342. }
  1343. }
  1344. }
  1345. /**
  1346. * Reset cache, needed for tests.
  1347. *
  1348. * Takes care of the persistent caches.
  1349. */
  1350. public function cache_reset() {
  1351. // Reset the persistent caches.
  1352. cache_clear_all('i18n:string:tgroup:' . $this->textgroup , 'cache', TRUE);
  1353. // Reset the complete string object cache too. This will affect string
  1354. // objects of other textgroups as well.
  1355. cache_clear_all('i18n:string:obj:', 'cache', TRUE);
  1356. return parent::cache_reset();
  1357. }
  1358. /**
  1359. * Get translation from cache.
  1360. *
  1361. * Extends the original handler with persistent caching.
  1362. *
  1363. * @param string $context
  1364. * The context to look out for.
  1365. * @return i18n_string_object|NULL
  1366. * The string object if available or NULL otherwise.
  1367. */
  1368. protected function cache_get($context) {
  1369. if (isset($this->strings[$context])) {
  1370. // If the cache contains a string re-build i18n_string_object.
  1371. if (is_string($this->strings[$context])) {
  1372. $i8n_string_object = new i18n_string_object(array('textgroup' => $this->textgroup));
  1373. $i8n_string_object->set_context($context);
  1374. $this->strings[$context] = $i8n_string_object;
  1375. }
  1376. // Now run the original handling.
  1377. return parent::cache_get($context);
  1378. }
  1379. return NULL;
  1380. }
  1381. /**
  1382. * Get strings from multiple cache.
  1383. *
  1384. * @param $context array
  1385. * String context as array with language property at the end.
  1386. *
  1387. * @return mixed
  1388. * Array of strings (may be empty) if we've got a cache hit.
  1389. * Null otherwise.
  1390. */
  1391. protected function multiple_cache_get($context) {
  1392. // Ensure the values from the persistent cache are properly re-build.
  1393. $cache_key = implode(':', $context);
  1394. if (isset($this->cache_multiple[$cache_key])) {
  1395. foreach ($this->cache_multiple[$cache_key] as $cached_context) {
  1396. if (is_string($cached_context)) {
  1397. $i8n_string_object = new i18n_string_object(array('textgroup' => $this->textgroup));
  1398. $i8n_string_object->set_context($cached_context);
  1399. $this->cache_multiple[$cache_key][$cached_context] = $i8n_string_object;
  1400. }
  1401. }
  1402. }
  1403. else {
  1404. // Now we try more generic keys. For instance, if we are searching 'term:1:*'
  1405. // we may try too 'term:*:*' and filter out the results.
  1406. foreach ($context as $key => $value) {
  1407. if ($value != '*') {
  1408. $try = array_merge($context, array($key => '*'));
  1409. return $this->multiple_cache_get($try);
  1410. }
  1411. }
  1412. }
  1413. return parent::multiple_cache_get($context);
  1414. }
  1415. public function string_update($i18nstring, $options = array()) {
  1416. // Flush persistent cache.
  1417. cache_clear_all($i18nstring->get_cid(), 'cache', TRUE);
  1418. return parent::string_update($i18nstring, $options);
  1419. }
  1420. public function string_remove($i18nstring, $options = array()) {
  1421. // Flush persistent cache.
  1422. cache_clear_all($i18nstring->get_cid(), 'cache', TRUE);
  1423. return parent::string_remove($i18nstring, $options);
  1424. }
  1425. }