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

Revision 1083, 25.3 KB (checked in by max-horvath, 7 years ago)

"2006-08-28 Benoit Gregoire <bock@…>

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