i18n_string.inc 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509
  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. if (is_array($value) && isset($value['value'])) {
  1121. $format = isset($value['format']) ? $value['format'] : NULL;
  1122. $value = $value['value'];
  1123. }
  1124. else {
  1125. $format = isset($info['format']) ? $this->get_field($info['format']) : NULL;
  1126. }
  1127. $strings[$this->get_textgroup()][$string_type][$object_id][$field] = array(
  1128. 'string' => is_array($value) || isset($info['empty']) && $value === $info['empty'] ? NULL : $value,
  1129. 'title' => $info['title'],
  1130. 'format' => $format,
  1131. 'name' => array_merge($object_keys, array($field)),
  1132. );
  1133. }
  1134. return $strings;
  1135. }
  1136. /**
  1137. * Get string context
  1138. */
  1139. public function get_string_context() {
  1140. return array($this->get_string_info('type'), $this->get_key());
  1141. }
  1142. /**
  1143. * Get translate path for object
  1144. *
  1145. * @param $langcode
  1146. * Language code if we want ti for a specific language
  1147. */
  1148. public function get_translate_path($langcode = NULL) {
  1149. $replacements = array('%i18n_language' => $langcode ? $langcode : '');
  1150. if ($path = $this->get_string_info('translate path')) {
  1151. return $this->path_replace($path, $replacements);
  1152. }
  1153. elseif ($path = $this->get_info('translate tab')) {
  1154. // If we've got a translate tab path, we just add language to it
  1155. return $this->path_replace($path . '/%i18n_language', $replacements);
  1156. }
  1157. }
  1158. /**
  1159. * Translation mode for object
  1160. */
  1161. public function get_translate_mode() {
  1162. return !$this->get_langcode() ? I18N_MODE_LOCALIZE : I18N_MODE_NONE;
  1163. }
  1164. /**
  1165. * Get textgroup name
  1166. */
  1167. public function get_textgroup() {
  1168. return $this->get_string_info('textgroup');
  1169. }
  1170. /**
  1171. * Get textgroup object
  1172. */
  1173. protected function textgroup() {
  1174. if (!isset($this->textgroup)) {
  1175. $this->textgroup = i18n_string_textgroup($this->get_textgroup());
  1176. }
  1177. return $this->textgroup;
  1178. }
  1179. /**
  1180. * Translate object.
  1181. *
  1182. * Translations are cached so it runs only once per language.
  1183. *
  1184. * @return object/array
  1185. * A clone of the object with its properties translated.
  1186. */
  1187. public function translate($langcode, $options = array()) {
  1188. // We may have it already translated. As objects are statically cached, translations are too.
  1189. if (!isset($this->translations[$langcode])) {
  1190. $this->translations[$langcode] = $this->translate_object($langcode, $options);
  1191. }
  1192. return $this->translations[$langcode];
  1193. }
  1194. /**
  1195. * Translate access (localize strings)
  1196. */
  1197. protected function localize_access() {
  1198. // We could check also whether the object has strings to translate:
  1199. // && $this->get_strings(array('empty' => TRUE))
  1200. // However it may be better to display the 'No available strings' message
  1201. // for the user to have a clue of what's going on. See i18n_string_translate_page_object()
  1202. return user_access('translate interface') && user_access('translate user-defined strings');
  1203. }
  1204. /**
  1205. * Translate all properties for object.
  1206. *
  1207. * On top of object strings we search for all textgroup:type:objectid:* properties
  1208. *
  1209. * @param $langcode
  1210. * A clone of the object or array
  1211. */
  1212. protected function translate_object($langcode, $options) {
  1213. // Clone object or array so we don't affect the original one.
  1214. $object = is_object($this->object) ? clone $this->object : $this->object;
  1215. // Get object strings for translatable properties.
  1216. if ($strings = $this->get_strings()) {
  1217. // We preload some of the property translations with a single query.
  1218. if ($context = $this->get_translate_context($langcode, $options)) {
  1219. $found = $this->textgroup()->multiple_translation_search($context, $langcode);
  1220. }
  1221. // Replace all strings in object.
  1222. foreach ($strings as $i18nstring) {
  1223. $this->translate_field($object, $i18nstring, $langcode, $options);
  1224. }
  1225. }
  1226. return $object;
  1227. }
  1228. /**
  1229. * Context to be pre-loaded before translation.
  1230. */
  1231. protected function get_translate_context($langcode, $options) {
  1232. // One-query translation of all textgroup:type:objectid:* properties
  1233. $context = $this->get_string_context();
  1234. $context[] = '*';
  1235. return $context;
  1236. }
  1237. /**
  1238. * Translate object property.
  1239. *
  1240. * Mot often, this is a direct field set, but sometimes fields may have different formats.
  1241. */
  1242. protected function translate_field(&$object, $i18nstring, $langcode, $options) {
  1243. $field_name = $i18nstring->property;
  1244. $translation = $i18nstring->format_translation($langcode, $options);
  1245. if (is_object($object)) {
  1246. $object->$field_name = $translation;
  1247. }
  1248. elseif (is_array($object)) {
  1249. $object[$field_name] = $translation;
  1250. }
  1251. }
  1252. /**
  1253. * Remove all strings for this object.
  1254. */
  1255. public function strings_remove($options = array()) {
  1256. $result = array();
  1257. foreach ($this->load_strings() as $key => $string) {
  1258. $result[$key] = $string->remove($options);
  1259. }
  1260. return _i18n_string_result_count($result);
  1261. }
  1262. /**
  1263. * Update all strings for this object.
  1264. */
  1265. public function strings_update($options = array()) {
  1266. $options += array('empty' => TRUE, 'update' => TRUE);
  1267. $result = array();
  1268. $existing = $this->load_strings();
  1269. // Update object strings
  1270. foreach ($this->get_strings($options) as $key => $string) {
  1271. $result[$key] = $string->update($options);
  1272. unset($existing[$key]);
  1273. }
  1274. // Delete old existing strings.
  1275. foreach ($existing as $key => $string) {
  1276. $result[$key] = $string->remove($options);
  1277. }
  1278. return _i18n_string_result_count($result);
  1279. }
  1280. /**
  1281. * Load all existing strings for this object.
  1282. */
  1283. public function load_strings() {
  1284. list($type, $id) = $this->get_string_context();
  1285. return $this->textgroup()->load_strings(array('type' => $type, 'objectid' => $id));
  1286. }
  1287. }
  1288. /**
  1289. * Textgroup handler for i18n_string API which integrated persistent caching.
  1290. */
  1291. class i18n_string_textgroup_cached extends i18n_string_textgroup_default {
  1292. /**
  1293. * Defines the timeout for the persistent caching.
  1294. * @var int
  1295. */
  1296. public $caching_time = CACHE_TEMPORARY;
  1297. /**
  1298. * Extends the existing constructor with a cache handling.
  1299. *
  1300. * @param string $textgroup
  1301. * The name of this textgroup.
  1302. */
  1303. public function __construct($textgroup) {
  1304. parent::__construct($textgroup);
  1305. // Fetch persistent caches, the persistent caches contain only metadata.
  1306. // Those metadata are processed by the related cache_get() methods.
  1307. foreach (array('cache_multiple', 'strings') as $caches_type) {
  1308. if (($cache = cache_get('i18n:string:tgroup:' . $this->textgroup . ':' . $caches_type)) && !empty($cache->data)) {
  1309. $this->{$caches_type} = $cache->data;
  1310. }
  1311. }
  1312. }
  1313. /**
  1314. * Class destructor.
  1315. *
  1316. * Updates the persistent caches for the next usage.
  1317. * This function not only stores the data of the textgroup objects but also
  1318. * of the string objects. That way we ensure that only cacheable string object
  1319. * go into the persistent cache.
  1320. */
  1321. public function __destruct() {
  1322. // Reduce size to cache by removing NULL values.
  1323. $this->strings = array_filter($this->strings);
  1324. $strings_to_cache = array();
  1325. // Store the persistent caches. We just store the metadata the translations
  1326. // are stored by the string object itself. However storing the metadata
  1327. // reduces the number of DB queries executed during runtime.
  1328. $cache_data = array();
  1329. foreach ($this->strings as $context => $i18n_string_object) {
  1330. $cache_data[$context] = $context;
  1331. $strings_to_cache[$context] = $i18n_string_object;
  1332. }
  1333. cache_set('i18n:string:tgroup:' . $this->textgroup . ':strings', $cache_data, 'cache', $this->caching_time);
  1334. $cache_data = array();
  1335. foreach ($this->cache_multiple as $pattern => $strings) {
  1336. foreach ($strings as $context => $i18n_string_object) {
  1337. $cache_data[$pattern][$context] = $context;
  1338. $strings_to_cache[$context] = $i18n_string_object;
  1339. }
  1340. }
  1341. cache_set('i18n:string:tgroup:' . $this->textgroup . ':cache_multiple', $cache_data, 'cache', $this->caching_time);
  1342. // Cache the string objects related to this textgroup.
  1343. // Store only the public visible data into the persistent cache.
  1344. foreach ($strings_to_cache as $i18n_string_object) {
  1345. // If this isn't an object it's an unprocessed cache item and doesn't need
  1346. // to be stored again.
  1347. if (is_object($i18n_string_object)) {
  1348. cache_set($i18n_string_object->get_cid(), get_object_vars($i18n_string_object), 'cache', $this->caching_time);
  1349. }
  1350. }
  1351. }
  1352. /**
  1353. * Reset cache, needed for tests.
  1354. *
  1355. * Takes care of the persistent caches.
  1356. */
  1357. public function cache_reset() {
  1358. // Reset the persistent caches.
  1359. cache_clear_all('i18n:string:tgroup:' . $this->textgroup , 'cache', TRUE);
  1360. // Reset the complete string object cache too. This will affect string
  1361. // objects of other textgroups as well.
  1362. cache_clear_all('i18n:string:obj:', 'cache', TRUE);
  1363. return parent::cache_reset();
  1364. }
  1365. /**
  1366. * Get translation from cache.
  1367. *
  1368. * Extends the original handler with persistent caching.
  1369. *
  1370. * @param string $context
  1371. * The context to look out for.
  1372. * @return i18n_string_object|NULL
  1373. * The string object if available or NULL otherwise.
  1374. */
  1375. protected function cache_get($context) {
  1376. if (isset($this->strings[$context])) {
  1377. // If the cache contains a string re-build i18n_string_object.
  1378. if (is_string($this->strings[$context])) {
  1379. $i8n_string_object = new i18n_string_object(array('textgroup' => $this->textgroup));
  1380. $i8n_string_object->set_context($context);
  1381. $this->strings[$context] = $i8n_string_object;
  1382. }
  1383. // Now run the original handling.
  1384. return parent::cache_get($context);
  1385. }
  1386. return NULL;
  1387. }
  1388. /**
  1389. * Get strings from multiple cache.
  1390. *
  1391. * @param $context array
  1392. * String context as array with language property at the end.
  1393. *
  1394. * @return mixed
  1395. * Array of strings (may be empty) if we've got a cache hit.
  1396. * Null otherwise.
  1397. */
  1398. protected function multiple_cache_get($context) {
  1399. // Ensure the values from the persistent cache are properly re-build.
  1400. $cache_key = implode(':', $context);
  1401. if (isset($this->cache_multiple[$cache_key])) {
  1402. foreach ($this->cache_multiple[$cache_key] as $cached_context) {
  1403. if (is_string($cached_context)) {
  1404. $i8n_string_object = new i18n_string_object(array('textgroup' => $this->textgroup));
  1405. $i8n_string_object->set_context($cached_context);
  1406. $this->cache_multiple[$cache_key][$cached_context] = $i8n_string_object;
  1407. }
  1408. }
  1409. }
  1410. else {
  1411. // Now we try more generic keys. For instance, if we are searching 'term:1:*'
  1412. // we may try too 'term:*:*' and filter out the results.
  1413. foreach ($context as $key => $value) {
  1414. if ($value != '*') {
  1415. $try = array_merge($context, array($key => '*'));
  1416. return $this->multiple_cache_get($try);
  1417. }
  1418. }
  1419. }
  1420. return parent::multiple_cache_get($context);
  1421. }
  1422. public function string_update($i18nstring, $options = array()) {
  1423. // Flush persistent cache.
  1424. cache_clear_all($i18nstring->get_cid(), 'cache', TRUE);
  1425. return parent::string_update($i18nstring, $options);
  1426. }
  1427. public function string_remove($i18nstring, $options = array()) {
  1428. // Flush persistent cache.
  1429. cache_clear_all($i18nstring->get_cid(), 'cache', TRUE);
  1430. return parent::string_remove($i18nstring, $options);
  1431. }
  1432. }