root/trunk/wifidog-auth/wifidog/classes/Content/Langstring/Langstring.php @ 877

Revision 877, 24.7 KB (checked in by fproulx, 7 years ago)

2005-12-29 Fran�ois Proulx <francois.proulx@…>

  • Added Aidan's file_exists_incpath function to Dependencies class
  • Translated and standardized most of PostgreSQL abstraction class.
  • Removed blank lines at end of many files
  • Tested the new Phlickr package, which fixes URL on Flickr
  • Property svn:eol-style set to native
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
Line 
1<?php
2
3/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4
5// +-------------------------------------------------------------------+
6// | WiFiDog Authentication Server                                     |
7// | =============================                                     |
8// |                                                                   |
9// | The WiFiDog Authentication Server is part of the WiFiDog captive  |
10// | portal suite.                                                     |
11// +-------------------------------------------------------------------+
12// | PHP version 5 required.                                           |
13// +-------------------------------------------------------------------+
14// | Homepage:     http://www.wifidog.org/                             |
15// | Source Forge: http://sourceforge.net/projects/wifidog/            |
16// +-------------------------------------------------------------------+
17// | This program is free software; you can redistribute it and/or     |
18// | modify it under the terms of the GNU General Public License as    |
19// | published by the Free Software Foundation; either version 2 of    |
20// | the License, or (at your option) any later version.               |
21// |                                                                   |
22// | This program is distributed in the hope that it will be useful,   |
23// | but WITHOUT ANY WARRANTY; without even the implied warranty of    |
24// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the     |
25// | GNU General Public License for more details.                      |
26// |                                                                   |
27// | You should have received a copy of the GNU General Public License |
28// | along with this program; if not, contact:                         |
29// |                                                                   |
30// | Free Software Foundation           Voice:  +1-617-542-5942        |
31// | 59 Temple Place - Suite 330        Fax:    +1-617-542-2652        |
32// | Boston, MA  02111-1307,  USA       gnu@gnu.org                    |
33// |                                                                   |
34// +-------------------------------------------------------------------+
35
36/**
37 * @package    WiFiDogAuthServer
38 * @subpackage ContentClasses
39 * @author     Benoit Gregoire <bock@step.polymtl.ca>
40 * @copyright  2004-2005 Benoit Gregoire, Technologies Coeus inc.
41 * @version    CVS: $Id$
42 * @link       http://sourceforge.net/projects/wifidog/
43 */
44
45require_once('classes/Cache.php');
46require_once('classes/LocaleList.php');
47
48
49/**
50 * Représente un Langstring en particulier, ne créez pas un objet langstrings
51 * si vous n'en avez pas spécifiquement besoin
52 *
53 * @package    WiFiDogAuthServer
54 * @subpackage ContentClasses
55 * @author     Benoit Gregoire <bock@step.polymtl.ca>
56 * @copyright  2004-2005 Benoit Gregoire, Technologies Coeus inc.
57 */
58class Langstring extends Content {
59    /**
60     * HTML allowed to be used
61     */
62    const ALLOWED_HTML_TAGS = "<a><br><b><h1><h2><h3><h4><i><img><li><ol><p><strong><u><ul><li>";
63
64    /**
65     * Constructor
66     *
67     * @param string $content_id Content id
68     *
69     * @access public
70     */
71    public function __construct($content_id)
72    {
73        // Define globals
74        global $db;
75
76        parent::__construct($content_id);
77        $this->mBd = &$db;
78    }
79
80    /**
81     * Retourne la première chaîne disponible dans la langue par défaut de
82     * l'usager (si disponible), sinon dans la même langue majeure, sinon
83     * la première chaîne disponible
84     *
85     * @return string Chaîne UTF-8 retournée
86     *
87     * @access public
88     */
89    public function getString()
90    {
91        // Init values
92        $retval = null;
93        $row = null;
94        $_useCache = false;
95        $_cachedData = null;
96
97        // Create new cache objects
98        $_cacheLanguage = new Cache('langstrings_' . $this->id . '_substring_' . substr(Locale :: getCurrentLocale()->getId(), 0, 2) . '_string', $this->id);
99        $_cache = new Cache('langstrings_' . $this->id . '_substring__string', $this->id);
100
101        // Check if caching has been enabled.
102        if ($_cacheLanguage->isCachingEnabled) {
103            if ($_cachedData = $_cacheLanguage->getCachedData()) {
104                // Return cached data.
105                $_useCache = true;
106                $retval = $_cachedData;
107            } else {
108                // Language specific cached data has not been found.
109                // Try to get language independent cached data.
110                if ($_cachedData = $_cache->getCachedData()) {
111                    // Return cached data.
112                    $_useCache = true;
113                    $retval = $_cachedData;
114                }
115            }
116        }
117
118        if (!$_useCache) {
119            //Get user's prefered language
120            $sql = "SELECT value, locales_id, \n";
121            $sql .= Locale :: getSqlCaseStringSelect(Locale :: getCurrentLocale()->getId());
122            $sql .= " as score FROM langstring_entries WHERE langstring_entries.langstrings_id = '{$this->id}' AND value!='' ORDER BY score LIMIT 1";
123            $this->mBd->execSqlUniqueRes($sql, $row, false);
124
125            if ($row == null) {
126                $retval = "(Langstring vide)";
127            } else {
128                $retval = $row['value'];
129
130                // Check if caching has been enabled.
131                if ($_cache->isCachingEnabled) {
132                    // Save data into cache, because it wasn't saved into cache before.
133                    $_cache->saveCachedData($retval);
134                }
135            }
136        }
137
138        return $retval;
139    }
140
141    /**
142     * Ajoute une chaîne de caractère au Langstring
143     *
144     * @param string $string             La chaîne de caractère à ajouter.  Si la chaîne
145     *                                   est vide ('') ou null, la fonction retourne sans
146     *                                   toucher à la base de donnée
147     * @param string $locale             La langue régionale de la chaîne ajoutée, exemple:
148     *                                   'fr_CA', peut être NULL
149     * @param bool   $allow_empty_string Allow to store an empty string
150     *
151     * @return bool True si une chaîne a été ajoutée à la base de donnée,
152     * false autrement.
153     *
154     * @access public
155     */
156    public function addString($string, $locale, $allow_empty_string = false)
157    {
158        // Init values
159        $retval = false;
160        $id = 'NULL';
161        $idSQL = $id;
162
163        if ($locale) {
164            $language = new Locale($locale);
165            $id = $language->GetId();
166            $idSQL = "'".$id."'";
167        }
168
169        if ($allow_empty_string || ($string != null && $string != '')) {
170            $string = $this->mBd->escapeString($string);
171            $this->mBd->execSqlUpdate("INSERT INTO langstring_entries (langstring_entries_id, langstrings_id, locales_id, value) VALUES ('".get_guid()."', '$this->id', $idSQL , '$string')", FALSE);
172
173            // Create new cache object.
174            $_cache = new Cache('langstrings_' . $this->id . '_substring_' .  $id . '_string', $this->id);
175
176            // Check if caching has been enabled.
177            if ($_cache->isCachingEnabled) {
178                // Remove old cached data.
179                $_cache->eraseCachedData();
180
181                // Save data into cache.
182                $_cache->saveCachedData($string);
183            }
184
185            $retval = true;
186        }
187
188        return $retval;
189    }
190
191    /**
192     * Updates the string associated with the locale
193     *
194     * @param string $string La chaîne de caractère à ajouter. Si la chaîne
195     *                       est vide ('') ou null, la fonction retourne
196     *                       sans toucher à la base de donnée
197     * @param string $locale La langue régionale de la chaîne ajoutée,
198     *                       exemple: 'fr_CA', peut être NULL
199     *
200     * @return bool True si une chaîne a été ajoutée à la base de donnée, false autrement.
201     *
202     * @access public
203     */
204    public function UpdateString($string, $locale)
205    {
206        // Init values
207        $retval = false;
208        $id = 'NULL';
209        $row = null;
210
211        if ($locale) {
212            $language = new Locale($locale);
213            $id = $language->GetId();
214            $idSQL = "'" . $id . "'";
215        }
216
217        if ($string != null && $string != '') {
218            $string = $this->mBd->escapeString($string);
219            // If the update returns 0 ( no update ), try inserting the record
220            $this->mBd->execSqlUniqueRes("SELECT * FROM langstring_entries WHERE locales_id = $idSQL AND langstrings_id = '$this->id'", $row, false);
221
222            if ($row != null) {
223                $this->mBd->execSqlUpdate("UPDATE langstring_entries SET value = '$string' WHERE langstrings_id = '$this->id' AND locales_id = $idSQL", false);
224
225                // Create new cache object.
226                $_cache = new Cache('langstrings_' . $this->id . '_substring_' .  $id . '_string', $this->id);
227
228                // Check if caching has been enabled.
229                if ($_cache->isCachingEnabled) {
230                    // Remove old cached data.
231                    $_cache->eraseCachedData();
232
233                    // Save data into cache.
234                    $_cache->saveCachedData($string);
235                }
236            } else {
237                $this->addString($string, $locale);
238            }
239
240            $retval = true;
241        }
242
243        return $retval;
244    }
245
246    /**
247     * Affiche l'interface d'administration de l'objet
248     *
249     * @param string $type_interface SIMPLE pour éditer un seul champ, COMPLETE
250     *                               pour voir toutes les chaînes, LARGE pour
251     *                               avoir un textarea.
252     * @param int    $num_nouveau    Nombre de champ à afficher pour entrer de
253     *                               nouvelles chaîne en une seule opération
254     *
255     * @return string HTML code of administration interface
256     *
257     * @access public
258     */
259    public function getAdminUI($type_interface = "LARGE", $num_nouveau = 1)
260    {
261        // Init values.
262        $html = '';
263        $result = "";
264        //$variantsCounter = 0;
265        //$_hideNewContent = false;
266
267        $html .= "<div class='admin_class'>Langstring (".get_class($this)." instance)</div>\n";
268        $html .= "<div class='admin_section_container'>\n";
269
270        $html .= _("Only these HTML tags are allowed : ").htmlentities(self :: ALLOWED_HTML_TAGS);
271
272        $liste_languages = new LocaleList();
273        $sql = "SELECT * FROM langstring_entries WHERE langstring_entries.langstrings_id = '$this->id' ORDER BY locales_id";
274        $this->mBd->execSql($sql, $result, FALSE); //echo "type_interface: $type_interface\n";
275
276        $html .= "<ul class='admin_section_list'>\n";
277
278        if ($result != null) {
279            while (list ($key, $value) = each($result)) {
280//                The next lines are a preview of a new suggested input mode
281//                ==========================================================
282//
283//                // Increase variants counter
284//                $variantsCounter++;
285//
286//                // Hide new content input
287//                $_hideNewContent = true;
288//
289//                $html .= "<li class='admin_section_list_item'>\n";
290//                $html .= "<div class='admin_section_data'>\n";
291//
292//                if ($type_interface == 'LARGE') {
293//                    $html .= "<textarea name='langstrings_".$this->id."_substring_$value[langstring_entries_id]_string' cols='60' rows='3'>".htmlspecialchars($value['value'], ENT_QUOTES, 'UTF-8')."</textarea>\n";
294//                } else {
295//                    $html .= "<input type='text' name='langstrings_".$this->id."_substring_$value[langstring_entries_id]_string' size='44' value='".htmlspecialchars($value['value'], ENT_QUOTES, 'UTF-8')."'>\n";
296//                }
297//
298//                $html .= "<div class='admin_section_data' id='langstrings_".$this->id."_substring_$value[langstring_entries_id]_language_section' style='display: none;'>\n";
299//                $html .= $liste_languages->GenererFormSelect("$value[locales_id]", "langstrings_".$this->id."_substring_$value[langstring_entries_id]_language", 'Langstring::AfficherInterfaceAdmin', TRUE);
300//                $html .= "</div>\n";
301//
302//                $html .= "</div>\n";
303//                $html .= "<div class='admin_section_tools'>\n";
304//                $name = "langstrings_".$this->id."_substring_$value[langstring_entries_id]_erase";
305//
306//                // Choose language button
307//                $html .= "<a href='javascript:showHideView(\"langstrings_".$this->id."_substring_$value[langstring_entries_id]_language_section\", \"langstrings_".$this->id."_substring_$value[langstring_entries_id]_language_section_image\");'><img src='" . BASE_SSL_PATH . "images/icons/language.gif' id='langstrings_".$this->id."_substring_$value[langstring_entries_id]_language_section_image' class='admin_section_button' alt='"._("Choose language")."' title='"._("Choose language")."'></a>";
308//
309//                // Add string button
310//                if (count($result) == $variantsCounter) {
311//                    // This is the last string variant - show "add string" button.
312//                    $html .= "<a href='javascript:showHideView(\"langstrings_".$this->id."_add_new_entry_view\", \"langstrings_".$this->id."_add_new_entry_image\");'><img src='" . BASE_SSL_PATH . "images/icons/add.gif' id='langstrings_".$this->id."_add_new_entry_image' class='admin_section_button' alt='"._("Add new string")."' title='"._("Add new string")."'></a>";
313//                } else {
314//                    $html .= "<img src='" . BASE_SSL_PATH . "images/icons/add.gif' id='langstrings_".$this->id."_add_new_entry_image' class='admin_section_button_disabled' alt='"._("Add new string")."' title='"._("Add new string")."'>";
315//                }
316//
317//                // Delete string button
318//                $html .= "<input type='image' name='$name' class='admin_section_button' src='" . BASE_SSL_PATH . "images/icons/delete.gif' alt='"._("Delete string")."' title='"._("Delete string")."'>";
319//
320//                $html .= "</div>\n";
321//                $html .= "</li>\n";
322
323                $html .= "<li class='admin_section_list_item'>\n";
324                $html .= "<div class='admin_section_data'>\n";
325
326                $html .= $liste_languages->GenererFormSelect("$value[locales_id]", "langstrings_".$this->id."_substring_$value[langstring_entries_id]_language", 'Langstring::AfficherInterfaceAdmin', TRUE);
327
328                if ($type_interface == 'LARGE') {
329                    $html .= "<textarea name='langstrings_".$this->id."_substring_$value[langstring_entries_id]_string' cols='60' rows='3'>".htmlspecialchars($value['value'], ENT_QUOTES, 'UTF-8')."</textarea>\n";
330                } else {
331                    $html .= "<input type='text' name='langstrings_".$this->id."_substring_$value[langstring_entries_id]_string' size='44' value='".htmlspecialchars($value['value'], ENT_QUOTES, 'UTF-8')."'>\n";
332                }
333
334                $html .= "</div>\n";
335                $html .= "<div class='admin_section_tools'>\n";
336
337                $name = "langstrings_".$this->id."_substring_$value[langstring_entries_id]_erase";
338
339                $html .= "<input type='submit' name='$name' value='"._("Delete string")."'>";
340                $html .= "</div>\n";
341                $html .= "</li>\n";
342            }
343        }
344
345//        The next lines are a preview of a new suggested input mode
346//        ==========================================================
347//
348//        //Nouvelles chaîne
349//        $locale = LocaleList :: GetDefault();
350//
351//        $html .= "<li class='admin_section_list_item' id='langstrings_".$this->id."_add_new_entry_view'" . ($_hideNewContent ? " style='display: none;'" : "") . ">\n";
352//        $html .= "<div class='admin_section_data'>\n";
353//
354//        $new_substring_name = "langstrings_".$this->id."_substring_new_string";
355//
356//        if ($type_interface == 'LARGE') {
357//            $html .= "<textarea name='$new_substring_name' cols='60' rows='3'></textarea>\n";
358//        } else {
359//            $html .= "<input type='text' name='$new_substring_name' size='44' value=''>\n";
360//        }
361//
362//        $html .= "<div class='admin_section_data' id='langstrings_".$this->id."_substring_new_language_section'>\n";
363//        $html .= "<img src='" . BASE_SSL_PATH . "images/icons/language.gif' id='langstrings_".$this->id."_substring_new_language_section_image' class='admin_section_button' alt='"._("Choose language")."' title='"._("Choose language")."'>";
364//        $html .= $liste_languages->GenererFormSelect($locale, "langstrings_".$this->id."_substring_new_language", 'Langstring::AfficherInterfaceAdmin', TRUE);
365//        $html .= "</div>\n";
366//
367//        $html .= "</div>\n";
368//        $html .= "<div class='admin_section_tools'>\n";
369//
370//        $new_substring_submit_name = "langstrings_".$this->id."_add_new_entry";
371//
372//        // Add string button
373//        $html .= "<input type='image' name='$new_substring_submit_name' class='admin_section_button' src='" . BASE_SSL_PATH . "images/icons/add.gif' alt='"._("Add new string")."' title='"._("Add new string")."'>";
374//
375//        $html .= "</div>\n";
376//        $html .= "</li>\n";
377//
378//        $html .= "</ul>\n";
379//        $html .= "</div>\n";
380
381        //Nouvelles chaîne
382        $locale = LocaleList :: GetDefault();
383        $html .= "<li class='admin_section_list_item'>\n";
384        $html .= "<div class='admin_section_data'>\n";
385
386        $html .= $liste_languages->GenererFormSelect($locale, "langstrings_".$this->id."_substring_new_language", 'Langstring::AfficherInterfaceAdmin', TRUE);
387        $new_substring_name = "langstrings_".$this->id."_substring_new_string";
388
389        if ($type_interface == 'LARGE') {
390            $html .= "<textarea name='$new_substring_name' cols='60' rows='3'></textarea>\n";
391        } else {
392            $html .= "<input type='text' name='$new_substring_name' size='44' value=''>\n";
393        }
394
395        $html .= "</div>\n";
396        $html .= "<div class='admin_section_tools'>\n";
397
398        $new_substring_submit_name = "langstrings_".$this->id."_add_new_entry";
399
400        $html .= "<input type='submit' name='$new_substring_submit_name' value='"._("Add new string")."'>";
401        $html .= "</div>\n";
402        $html .= "</li>\n";
403
404        $html .= "</ul>\n";
405        $html .= "</div>\n";
406
407        return parent :: getAdminUI($html);
408    }
409
410    /**
411     * Processes the input of the administration interface for Langstring
412     *
413     * @return void
414     *
415     * @access public
416     */
417    public function processAdminUI()
418    {
419        // Init values.
420        $result = null;
421
422        if ($this->isOwner(User :: getCurrentUser()) || User :: getCurrentUser()->isSuperAdmin()) {
423            parent :: processAdminUI();
424            $generateur_form_select = new FormSelectGenerator();
425            $sql = "SELECT * FROM langstring_entries WHERE langstring_entries.langstrings_id = '$this->id'";
426            $this->mBd->execSql($sql, $result, FALSE);
427
428            if ($result != null) {
429                while (list ($key, $value) = each($result)) {
430                    $language = $generateur_form_select->getResult("langstrings_".$this->id."_substring_$value[langstring_entries_id]_language", 'Langstring::AfficherInterfaceAdmin');
431
432                    if (empty ($language)) {
433                        $language = '';
434                        $languageSQL = 'NULL';
435                    } else {
436                        $languageSQL = "'".$language."'";
437                    }
438
439                    if (!empty ($_REQUEST["langstrings_".$this->id."_substring_$value[langstring_entries_id]_erase"]) && $_REQUEST["langstrings_".$this->id."_substring_$value[langstring_entries_id]_erase"] == true) {
440                        $this->mBd->execSqlUpdate("DELETE FROM langstring_entries WHERE langstrings_id = '$this->id' AND langstring_entries_id='$value[langstring_entries_id]'", FALSE);
441
442                        // Create new cache object.
443                        $_cache = new Cache('langstrings_' . $this->id . '_substring_' .  $language . '_string', $this->id);
444
445                        // Check if caching has been enabled.
446                        if ($_cache->isCachingEnabled) {
447                            // Remove old cached data.
448                            $_cache->eraseCachedData();
449                        }
450                    } else {
451                        // Strip HTML tags !
452                        $string = $_REQUEST["langstrings_".$this->id."_substring_$value[langstring_entries_id]_string"];
453                        $string = $this->mBd->escapeString(strip_tags($string, self :: ALLOWED_HTML_TAGS));
454                        $this->mBd->execSqlUpdate("UPDATE langstring_entries SET locales_id = $languageSQL , value = '$string' WHERE langstrings_id = '$this->id' AND langstring_entries_id='$value[langstring_entries_id]'", FALSE);
455
456                        // Create new cache object.
457                        $_cache = new Cache('langstrings_' . $this->id . '_substring_' .  $language . '_string', $this->id);
458
459                        // Check if caching has been enabled.
460                        if ($_cache->isCachingEnabled) {
461                            // Remove old cached data.
462                            $_cache->eraseCachedData();
463
464                            // Save data into cache.
465                            $_cache->saveCachedData($string);
466                        }
467                    }
468                }
469            }
470
471            //Ajouter nouvelles chaîne(s) si champ non vide ou si l'usager a appuyé sur le bouton ajouter
472            $new_substring_name = "langstrings_".$this->id."_substring_new_string";
473            $new_substring_submit_name = "langstrings_".$this->id."_add_new_entry";
474
475            if ((isset ($_REQUEST[$new_substring_submit_name]) && $_REQUEST[$new_substring_submit_name] == true) || !empty ($_REQUEST[$new_substring_name])) {
476                $language = $generateur_form_select->getResult("langstrings_".$this->id."_substring_new_language", 'Langstring::AfficherInterfaceAdmin');
477
478                if (empty ($language)) {
479                    $language = null;
480                }
481
482                $this->addString($_REQUEST[$new_substring_name], $language, true);
483            }
484        }
485    }
486
487    /**
488     * Retreives the user interface of this object.
489     *
490     * Anything that overrides this method should call the parent method with
491     * it's output at the END of processing.
492     *
493     * @param string $subclass_admin_interface HTML content of the interface
494     *                                         element of a children
495     *
496     * @return string The HTML fragment for this interface
497     *
498     * @access public
499     */
500    public function getUserUI($subclass_user_interface = null)
501    {
502        // Init values
503        $html = '';
504
505        $html .= "<div class='user_ui_container'>\n";
506        $html .= "<div class='user_ui_object_class'>Langstring (".get_class($this)." instance)</div>\n";
507        $html .= "<div class='langstring'>\n";
508        $html .= $this->getString();
509        $html .= $subclass_user_interface;
510        $html .= "</div>\n";
511        $html .= "</div>\n";
512
513        return parent::getUserUI($html);
514    }
515
516    /**
517     * Reloads the object from the database.
518     *
519     * Should normally be called after a set operation.
520     *
521     * This function is private because calling it from a subclass will call
522     * the constructor from the wrong scope
523     *
524     * @return void
525     *
526     * @access private
527     */
528    private function refresh()
529    {
530        $this->__construct($this->id);
531    }
532
533    /**
534     * Deletes a Langstring object
535     *
536     * @param string $errmsg Reference to error message
537     *
538     * @return bool True if deletion was successful
539     *
540     * @access public
541     * @internal Persistent content will not be deleted
542     */
543    public function delete(&$errmsg)
544    {
545        // Init values.
546        $_retval = false;
547
548        if ($this->isPersistent()) {
549            $errmsg = _("Content is persistent (you must make it non persistent before you can delete it)");
550        } else {
551            global $db;
552
553            if ($this->isOwner(User :: getCurrentUser()) || User :: getCurrentUser()->isSuperAdmin()) {
554                $_sql = "DELETE FROM content WHERE content_id='$this->id'";
555                $db->execSqlUpdate($_sql, false);
556                $_retval = true;
557
558                // Create new cache object.
559                $_cache = new Cache('all', $this->id);
560
561                // Check if caching has been enabled.
562                if ($_cache->isCachingEnabled) {
563                    // Remove old cached data.
564                    $_cache->eraseCachedGroupData();
565                }
566            } else {
567                $errmsg = _("Access denied (not owner of content)");
568            }
569        }
570
571        return $_retval;
572    }
573
574}
575
576/*
577 * Local variables:
578 * tab-width: 4
579 * c-basic-offset: 4
580 * c-hanging-comment-ender-p: nil
581 * End:
582 */
583
584?>
Note: See TracBrowser for help on using the browser.