Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/site/app/app_model.php
blob: 7375d5f68086284aa7cf2fd245707501158ac95a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
<?php
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is addons.mozilla.org site.
 *
 * The Initial Developer of the Original Code is
 * The Mozilla Foundation.
 * Portions created by the Initial Developer are Copyright (C) 2006
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Frederic Wenzel <fwenzel@mozilla.com> (Original Author)
 *   Justin Scott <fligtar@gmail.com>
 *   Mike Shaver <shaver@mozilla.org>
 *   Wil Clouser <clouserw@mozilla.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

class AppModel extends Model
{
    var $translate = true;  // run dl10n magic?
    var $translationReplace = true; // replace translation indexes with translations
    var $Cache; // holds the cache object
    var $caching = QUERY_CACHE; // query caching enabled?
    var $default_fields = null; // if none are selected, which fields will we fetch for this model? Null means "all".

    /**
     * Constructor
     */
    function __construct($id = false, $table = null, $ds = null) {
        if ($this->caching) {
            loadModel('Memcaching');
            $this->Cache = new Memcaching();
        }
        return parent::__construct($id, $table, $ds);
    }
    
    /**
     * This function will dynamically join translations into the current find operation,
     * according to whichever fields it finds in $this->translated_fields.
     * Please also see: http://wiki.mozilla.org/Update:Remora_Localization
     *
     * @param array queryData as defined in cake's Model->findAll()
     * @return boolean will always return true
     */
    function beforeFind(&$queryData) {

        // Tell the user they are bad because they don't have a model name.
        if (!isset($this->name)) {
            trigger_error('No model name was found for class: '.$get_class($this).'.', E_NOTICE); 
        }
    
        if (!$this->translate) return true; // don't do anything if translation was deactivated
        
        // This will build a finderQuery for the translations, and bind our current model to the translations table on the fly
        if (isset($this->translated_fields) && is_array($this->translated_fields)) {
            
            // Allow querying for a locale other than currently set
            $lang = $this->getLang();

            // fallback language is usually English. If we are selecting addons however,
            // we fall back to what's defined for that addon.
            if ($this->name == 'Addon') {
                $fb_locale = '`Addon`.`defaultlocale`';
            } else {
                $fb_locale = "'en-US'";
            }

            // These parts are separated due to the way the query is built
            $_query = '';
            $_joins = array();

            // Generate a field list just like Cake would do it, so that we
            // know which translations to join in.
            // If the user didn't give us a field list, we use the default field
            // list set for this Model. We have to have cake 
            // generate the list for us now, because once we set a fields
            // array, Cake won't select any other fields anymore than the ones 
            // we request.
            if (!empty($queryData['fields']))
                $_fields = $queryData['fields'];
            else
                $_fields = $this->default_fields;
            
            // if it's a string only, wrap it into an array so all the
            // following array magic works with it as well
            if (is_string($_fields)) $_fields = array($_fields);
            $db =& ConnectionManager::getDataSource($this->useDbConfig);
            $_fields = $db->fields($this, $this->name, $_fields);

            foreach ($this->translated_fields as $field) {
                // only handle translatable fields that are actually selected
                if (false === $pos = array_search("`{$this->name}`.`{$field}`", $_fields)) {
                    continue;
                }
                
                // for each translated field, we select the localized string, 
                // automatically falling back to en-US if nothing is found.
                // We also fetch the locale, which will be the requested 
                // locale if found and en-US in case of fallback.
                // naming is {fieldname} and {fieldname}_locale resp., which
                // means, fallback is transparent.
                $_select = "IFNULL(`tr_{$field}`.localized_string, `fb_{$field}`.localized_string) AS `{$field}`";
                
                // replace the translation id with the translation unless explicitly opted out of
                if ($this->translationReplace === false) {
                    // append the translation
                    $_fields[] = $_select;
                } else {
                    // replace the translation index field
                    $_fields[$pos] = $_select;
                }
                // add the respective locale field to the end of the list
                // (that is: the requested locale if the localized string
                // is not null, otherwise the fallback locale)
                $_fields[] = "IF(!ISNULL(`tr_{$field}`.localized_string), `tr_{$field}`.locale, `fb_{$field}`.locale) AS `{$field}_locale`";
                

                // Our query design requires us to join on the same table repeatedly.
                // Each join requires a different table name, so we're actually
                // calling our tables the same things as the fields. We're also
                // creating a string for the fallback versions (usually en-US). 
                // The requested locale has the prefix "tr_" (as "translation")
                // and the fallback has the prefix "fb_".
                $_joins[] = "LEFT JOIN translations AS `tr_{$field}` ON (`{$this->name}`.`{$field}` = `tr_{$field}`.id AND `tr_{$field}`.locale='{$lang}')";
                $_joins[] = "LEFT JOIN translations AS `fb_{$field}` ON (`{$this->name}`.`{$field}` = `fb_{$field}`.id AND `fb_{$field}`.locale={$fb_locale})";
            }

            // if we didn't actually translate anything, return now.
            if (empty($_joins)) return true;

            // magically replace translated fields in query conditions by
            // their more complicated counterparts, since MySQL apparently
            // can't back-reference the "AS" names from the where clause.
            $queryData['conditions'] = $this->_resolveTranslation($queryData['conditions']);
            $queryData['order'] = $this->_resolveTranslation($queryData['order']);

            // add our translation join magic to the query that's about to be executed
            $queryData['joins'] = array_merge($queryData['joins'], $_joins);
            $queryData['fields'] = $_fields;
        }

        // If this is false, the find won't execute.
        // DO return $queryData here. Changing the array by reference up there
        // does not imply PHP4 actually keeping it changed after we return. :(
        return $queryData;
    }

    /**
     * Take a condition or "order by" string and replace Translation.* by
     * the fallback queries.
     */
    function _resolveTranslation($subject) {
        $patterns = array(
            '/`?Translation`?\.([\w_]+)_locale/', // query locales first, because they match the second pattern as well!
            '/`?Translation`?\.([\w_]+)/'
            );
        $replacements = array(
            'IF(!ISNULL(`tr_\\1`.`localized_string`), `tr_\\1`.`locale`, `fb_\\1`.`locale`)',
            'IFNULL(`tr_\\1`.`localized_string`, `fb_\\1`.`localized_string`)'
            );
        if (is_array($subject)) {
            foreach($subject as $key => $value) {
                $new_key = $this->_resolveTranslation($key);
                $new_value = $this->_resolveTranslation($value);
                // set the new replaced value
                $subject[$new_key] = $new_value;
                // if the key changed, remove the old one
                if ($key != $new_key) {
                    unset($subject[$key]);
                }
            }
            return $subject;

        } else {
            return preg_replace($patterns, $replacements, $subject);
        }
    }

    /**
     * findAll(), checking for cached result objects.
     */
    function findAll($conditions = null, $fields = null, $order = null, $limit = null, $page = 1, $recursive = null) {
        if ($this->caching && isset($this->name)) {
            $cachekey = func_get_args();
            $cachekey = $this->_cachekey('findAll:'.serialize($cachekey));
            // if this was already cached, return it immediately
            if (false !== $cached = $this->Cache->get($cachekey)) {
                return $cached;
            }
        }

        // else fetch the result normally
        $result = parent::findAll($conditions, $fields, $order, $limit, $page, $recursive);
        if ($this->caching && $result !== false) {
            // cache it
            $this->Cache->set($cachekey, $result);
        }
        // and return the result
        return $result;
    }

    /**
     * query(), checking for cached result objects (only on select queries,
     * of course).
     * Note: If you execute multiple queries in one line with a select query 
     * first, followed by some writing (insert or so), this *will* break.
     * Don't do this.
     */
    function query($query = null, $use_shadow_database = false, $cakeCaching = true) {
        if ($this->caching
            && is_string($query)
            && (0 === strpos(strtolower(ltrim($query)), 'select'))
            && isset($this->name)) {
            
            $cachekey = $this->_cachekey('query:'.$query);
            if ($cached = $this->Cache->get($cachekey)) return $cached;
        }
        
        if ($use_shadow_database && !defined('SHADOW_DISABLED')) {
            $this->useDbConfig = 'shadow';
            $result = parent::query($query, $cakeCaching);
            $this->useDbConfig = 'default';
        } else {
            $result = parent::query($query, $cakeCaching);
        }
        
        if ($this->caching && !empty($cachekey) && $result !== false) {
            // cache it (if it's a select query, otherwise $cachekey 
            // would be empty)
            $res = $this->Cache->set($cachekey, $result);
        }
        // and return the result
        return $result;
    }

    /**
     * generate a cache key for memcaching queries
     * @param string additional key uniqueness factors (SQL query etc)
     * @deprecated since 4.0.1
     */
    function _cachekey($key = '') {
        // attach some unique factors to the key
        $key .= $this->name.':';
        $key .= LANG.':'.APP_ID.':';

        // serialize the bound model names
        $params = array('belongsTo', 'hasMany', 'hasAndBelongsToMany');
        foreach ($params as $param)
            $key .= serialize(array_keys($this->$param));

        return MEMCACHE_PREFIX.md5($key);
    }
    

   /**
    * Allowed querying for a locale other than currently set.
    * Gets locale set by setLang()
    * @return string $lang The language code to use
    */
    function getLang() {
        if (!empty($this->useLang)) {
            $lang = $this->useLang;
        }
        else {
            $lang = LANG;
        }

        return $lang;
    }

   /**
    * Sets current language to use in queries
    * @param string $lang The language code to use
    * @param object &$controller Reference to the controller
    * @return boolean true
    */
    function setLang($lang, &$controller = null) {
        $this->useLang = $lang;

        if (isset($controller) && is_object($controller->Translation)) {
            $controller->Translation->useLang = $lang;
        }

        return true;
    }

    /**
     * Remora overwrites the default application model in order to implement
     * more sophisticated validation methods as described in:
     * http://wiki.cakephp.org/tutorials:advanced_validation
     * http://bakery.cakephp.org/articles/view/55
     */
    function invalidFields($data = array()) {
        
        if(!$this->beforeValidate()) {
            return false;
        }
        
        if (!isset($this->validate) || empty($this->validate)) {
            if (!empty($this->validationErrors)) {
                return $this->validationErrors;
            } else {
                return array();
            } 
        }
        
        
        if (!isset($this->data)) {
            
            $this->set($data);
        } elseif (!empty($data)) {
            $data = array_merge($data, $this->data);
            $this->set($data);
        } else {
            $data = $this->data;
        }
        
        $errors = array();
        
        foreach ($data as $table => $field) {
            foreach ($this->validate as $field_name => $validators) {
                if (!is_array($validators)) $validators = array(array($validators)); // wrap validator into array if it's only one
                foreach($validators as $validator) {
                    if (!is_array($validator)) $validator = array($validator); // wrap validator into array if it's only one
                    if (isset($validator[0])) {
                        if (method_exists($this, $validator[0])) {
                            if (isset($data[$table][$field_name]) && !call_user_func(array(&$this, $validator[0]))) {
                                if (!isset($errors[$field_name])) {
                                    $errors[$field_name] = isset($validator[1]) ? $validator[1] : 1;
                                }
                            }
                        } else {
                            if (isset($data[$table][$field_name]) && is_string($data[$table][$field_name]) && !preg_match($validator[0], $data[$table][$field_name])) {
                                if (!isset($errors[$field_name])) {
                                    $errors[$field_name] = isset($validator[1]) ? $validator[1] : 1;
                                }
                            }
                        }
                    }
                }
            }
        }
        $this->validationErrors = array_merge($this->validationErrors, $errors);
        
        return $this->validationErrors;
    }
    
    var $hasMany_full = array();
    var $hasAndBelongsToMany_full = array();
    var $belongsTo_full = array();
    
    function bindFully() {
        $this->bindModel(array('hasMany' => $this->hasMany_full,
                               'hasAndBelongsToMany' => $this->hasAndBelongsToMany_full,
                               'belongsTo' => $this->belongsTo_full));
    }
    
    function unbindFully() {
        $unbind = array();
        foreach ($this->belongsTo as $model=>$info) {
            $unbind['belongsTo'][] = $model;
        }
        foreach ($this->hasOne as $model=>$info) {
            $unbind['hasOne'][] = $model;
        }
        foreach ($this->hasMany as $model=>$info) {
            $unbind['hasMany'][] = $model;
        }
        foreach ($this->hasAndBelongsToMany as $model=>$info) {
            $unbind['hasAndBelongsToMany'][] = $model;
        }
        $this->unbindModel($unbind);
    }
   
   /**
    * Updates a table without requiring a primary key
    * @param mixed $update Array of fields and values to update or the update string
    * @param mixed $where Array of fields and values to match or the where string
    * @param int $limit Limit of rows to affect
    */
    function update($update, $where, $limit = 0) {
        //Return if no fields to update or if no where clause
        if (empty($update) || empty($where)) {
            return false;
        }
        
        $db =& ConnectionManager::getDataSource($this->useDbConfig);
        
        //Create update string from array
        if (is_array($update)) {
            foreach ($update as $field => $value) {
                if (empty($updateQry)) {
                    $updateQry = "`{$field}`='{$value}'";
                }
                else {
                    $updateQry .= ", `{$field}`='{$value}'";
                }
            }
        }
        elseif (is_string($update)) {
            $updateQry = $update;
        }
        
        //Create where clause from array
        if (is_array($where)) {
            foreach ($where as $field => $value) {
                if (empty($whereQry)) {
                    $whereQry = "`{$field}`='{$value}'";
                }
                else {
                    $whereQry .= " AND `{$field}`='{$value}'";
                }
            }
        }
        elseif (is_string($where)) {
            $whereQry = $where;
        }
        
        $limitQry = empty($limit) ? '' : " LIMIT {$limit}";
        
        return $db->execute("UPDATE ".$db->name($db->fullTableName($this))." SET {$updateQry} WHERE {$whereQry}{$limitQry}");
    }

    /**
     * save dynamically localized strings to translation table
     * before storing actual data
     */
    function beforeSave() {
        if (!isset($this->translated_fields) || empty($this->translated_fields)) {
            return true;
        } else {
            // we don't need this magic if none of the translated fields are to be saved
            $_tr_fields_tobestored = array_intersect($this->translated_fields, array_keys($this->data[$this->name]));
            if (empty($_tr_fields_tobestored)) return true;
        }
        
        // copy the data we intend to save
        $data = $this->data;

        // Allow querying for a locale other than currently set
        $lang = $this->getLang();
        
        // Make sure translation ids are returned
        $this->translationReplace = false;
        
        // start a transaction
        $db =& ConnectionManager::getDataSource($this->useDbConfig);
        $this->begin();

        if ($this->exists()) {
            // editing an existing record
            $olddata = $this->findById($this->id);
        } else {
            $olddata = false;
        }

        // try to store all translated strings
        $errors = false;
        foreach ($this->translated_fields as $tr_field) {
            if (!isset($data[$this->name][$tr_field])) continue;
            
            // remove existing translation if empty
            $_remove = (empty($data[$this->name][$tr_field]));

            // see if there is a row for us to update, otherwise we'll insert a new one
            if ($olddata && !empty($olddata[$this->name][$tr_field])) {
                $_res = $db->execute("SELECT * FROM translations WHERE id = {$olddata[$this->name][$tr_field]} AND locale = '{$lang}';");
                $_update = ($_res !== false && ($db->lastNumRows() > 0));
                $_trans_id = $olddata[$this->name][$tr_field];
            } else {
                // if we would remove it anyway, don't make a new ID
                if ($_remove) {
                    unset($data[$this->name][$tr_field]);
                    continue;
                }
                
                $_update = false;
                // generate a new primary key id
                $db->execute('UPDATE translations_seq SET id=LAST_INSERT_ID(id+1);');
                $_res = $db->execute('SELECT LAST_INSERT_ID() AS id FROM translations_seq;');
                if ($_row = $db->fetchRow()) {
                    $_trans_id = $_row[0]['id'];
                } else {
                    $_trans_id = false;
                }
            }

            // don't create a new but empty translation
            if (!$_update && $_remove) {
                unset($data[$this->name][$tr_field]);
                continue;
            }
            if ($_update) {
                // update an existing translation
                if ($_remove) {
                    $_string = 'NULL';
                } else {
                    $_string = "'{$data[$this->name][$tr_field]}'";
                }
                $_res = $db->execute("UPDATE translations SET "
                    ."localized_string = {$_string}, "
                    ."modified = NOW() "
                    ."WHERE id = {$_trans_id} AND locale = '{$lang}';");
                $this->commit();
            } else {
                // insert a new translation
                $sql = "INSERT INTO translations (id, locale, localized_string, created) VALUES "
                    ."({$_trans_id}, '{$lang}', '{$data[$this->name][$tr_field]}', NOW());";
                $_res = $db->execute($sql);
            }
            
            // errors? don't go on
            if ($_res === false) {
                $errors = true;
                break;
            }
            
            // replace localized string by localization id in data to be saved
            $data[$this->name][$tr_field] = $_trans_id;
        }
        
        // return to default
        $this->translationReplace = true;
        // if something went wrong, roll back
        if ($errors) {
            $this->rollback();
            return false;
        } else {
            $this->data = $data;
            return true;
        }
    }

    /**
     * after saving successfully, commit the transaction
     */
    function afterSave() {
        $db =& ConnectionManager::getDataSource($this->useDbConfig);
        if ($db->_transactionStarted) {
            return $this->commit();
        } else {
            return true;
        }
    }

    /**
     * start a transaction
     */
    function begin() {
        $db =& ConnectionManager::getDataSource($this->useDbConfig);
        if (!$db->_transactionStarted) {
            if ($db->execute("START TRANSACTION") !== false) {
                $db->_transactionStarted = true;
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    /**
     * rollback a transaction
     */
    function rollback() {
        $db =& ConnectionManager::getDataSource($this->useDbConfig);
        if ($db->_transactionStarted) {
            $db->_transactionStarted = false;
            return ($db->execute("ROLLBACK") !== false);
        }
        return false;
    }

    /**
     * commit a transaction
     */
    function commit() {
        $db =& ConnectionManager::getDataSource($this->useDbConfig);
        if ($db->_transactionStarted) {
            $db->_transactionStarted = false;
            return ($db->execute("COMMIT") !== false);
        }
        return false;
    }
    
    /**
     * Gets translations for all locales for the specific record and fields
     * @param int $id the primary key to pull from
     * @param array $fields optional array of fields to pull
     * @param bool $includeIDs whether to return the translation ids as well
     * @return array translations
     */
    function getAllTranslations($id, $fields = array(), $includeNULL = false, $returnIDs = false, $cache = false) {
        // If no fields passed, use all localizable fields in this model
        if (empty($fields) || !is_array($fields)) {
            $fields = $this->translated_fields;
        }
        
        $translations = array();
        
        // Pull the translation ids for the selected fields
        $tableInfo = $this->query("SELECT ".implode($fields, ', ')." FROM {$this->table} AS {$this->name} WHERE {$this->name}.id={$id}", $cache, $cache);
        if (!empty($tableInfo)) {
            foreach ($tableInfo[0][$this->name] as $field => $translation_id) {
                // If there's a translation id, add it to list to pull
                if (!empty($translation_id)) {
                    $translation_ids[$field] = $translation_id;
                }
                
                $translations[$field] = array();
            }
        }
        
        // Pull translations for all ids
        if (!empty($translation_ids)) {
            $where = $includeNULL ? '' : ' AND Translation.localized_string IS NOT NULL';
            $results = $this->query("SELECT * FROM translations AS Translation WHERE Translation.id IN (".implode($translation_ids, ',')."){$where}", $cache, $cache);
            if (!empty($results)) {
                foreach ($results as $result) {
                    $field = array_search($result['Translation']['id'], $translation_ids);
                    $translations[$field][$result['Translation']['locale']] = $result['Translation']['localized_string'];
                }
            }
        }
        else {
            // No translations found
            if ($returnIDs) {
                return array($translations, array());
            }
            else {
                return $translations;
            }
        }
        
        if ($returnIDs) {
            return array($translations, $translation_ids);
        }
        else {
            return $translations;
        }
    }
    
    /**
     * Save translations for new, updated, and deleted locales.
     * This should only be used for mass updating and is more efficient
     * for mass updating than normal save()ing
     * @param int $id id to update
     * @param array $rawData array of translation data not escaped
     * @param array $data array of translation data escaped
     */
    function saveTranslations($id, $rawData, $data) {
        // Pull all existing translations for fields to save
        $fields = array_keys($data);
        list($existing, $translation_ids) = $this->getAllTranslations($id, $fields, true, true);
        
        // Handle updated and deleted translations
        if (!empty($existing)) {
            foreach ($existing as $field => $translations) {
                if (!empty($translations)) {
                    foreach ($translations as $locale => $translation) {
                        if (isset($data[$field][$locale]) && empty($data[$field][$locale]) && !empty($translation)) {
                            // Translation was deleted
                            $this->execute("UPDATE translations SET localized_string=NULL, modified=NOW() WHERE id={$translation_ids[$field]} AND locale='{$locale}'");
                        }
                        elseif (!empty($rawData[$field][$locale]) && $rawData[$field][$locale] != $translation) {
                            // If not the same, the translation was updated
                            $this->execute("UPDATE translations SET localized_string='{$data[$field][$locale]}', modified=NOW() WHERE id={$translation_ids[$field]} AND locale='{$locale}'");
                        }
                        // Else, no changes
                        
                        unset($data[$field][$locale]);
                    }
                }
            }
        }
        
        // Handle new translations
        if (!empty($data)) {
            foreach ($data as $field => $translations) {
                if (!empty($translations)) {
                    foreach ($translations as $locale => $translation) {
                        if (!empty($translation)) {
                            // Add new locale
                            if (!empty($translation_ids[$field])) {
                                // Translation id already set for this field
                                $this->execute("INSERT INTO translations (id, locale, localized_string, created) VALUES({$translation_ids[$field]}, '{$locale}', '{$data[$field][$locale]}', NOW())");
                            }
                            else {
                                // Translation id not yet set for this field, so we hand off to normal beforeSave() magic
                                if (in_array($field, $this->translated_fields)) {
                                    $this->setLang($locale);
                                    $this->id = $id;
                                    $save = array($field => $data[$field][$locale]);
                                    $this->save($save, false);
                                    $this->setLang(LANG);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    /**
     * Separates an array of data into localized fields and unlocalized fields
     */
    function splitLocalizedFields($data) {
        $localizedFields = array();
        $unlocalizedFields = array();
        
        if (!empty($data)) {
            foreach ($data as $field => $value) {
                if (in_array($field, $this->translated_fields)) {
                    $localizedFields[$field] = $value;
                }
                else {
                    $unlocalizedFields[$field] = $value;
                }
            }
        }
        
        return array($localizedFields, $unlocalizedFields);
    }
    
    /**
     * Strips fields that aren't in the specified whitelist
     */
    function stripFields($data, $allowedFields) {
        $safe = array();
        if (!empty($data)) {
            foreach ($data as $field => $value) {
                if (in_array($field, $allowedFields)) {
                    $safe[$field] = $value;
                }
            }
        }
        
        return $safe;
    }
    
}
?>