"Fossies" - the Fresh Open Source Software Archive

Member "impresscms-1.4.2/htdocs/include/functions.php" (24 Dec 2020, 68935 Bytes) of package /linux/www/impresscms-1.4.2.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) PHP source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "functions.php" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes reports: 1.4.2_rc_vs_1.4.2 or 1.4.1_vs_1.4.2.

    1 <?php
    2 // $Id: functions.php 1032 2007-09-09 13:01:16Z dugris $
    3 //  ------------------------------------------------------------------------ //
    4 //                XOOPS - PHP Content Management System                      //
    5 //                    Copyright (c) 2000 XOOPS.org                           //
    6 //                       <http://www.xoops.org/>                             //
    7 //  ------------------------------------------------------------------------ //
    8 //  This program is free software; you can redistribute it and/or modify     //
    9 //  it under the terms of the GNU General Public License as published by     //
   10 //  the Free Software Foundation; either version 2 of the License, or        //
   11 //  (at your option) any later version.                                      //
   12 //                                                                           //
   13 //  You may not change or alter any portion of this comment or credits       //
   14 //  of supporting developers from this source code or any supporting         //
   15 //  source code which is considered copyrighted (c) material of the          //
   16 //  original comment or credit authors.                                      //
   17 //                                                                           //
   18 //  This program is distributed in the hope that it will be useful,          //
   19 //  but WITHOUT ANY WARRANTY; without even the implied warranty of           //
   20 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            //
   21 //  GNU General Public License for more details.                             //
   22 //                                                                           //
   23 //  You should have received a copy of the GNU General Public License        //
   24 //  along with this program; if not, write to the Free Software              //
   25 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA //
   26 //  ------------------------------------------------------------------------ //
   27 
   28 /**
   29  * Helper functions available in the ImpressCMS process
   30  *
   31  * @copyright   http://www.xoops.org/ The XOOPS Project
   32  * @copyright   http://www.impresscms.org/ The ImpressCMS Project
   33  * @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU General Public License (GPL)
   34  * @package core
   35  * @since       XOOPS
   36  * @author      http://www.xoops.org The XOOPS Project
   37  * @author      modified by marcan <marcan@impresscms.org>
   38  * @version $Id: functions.php 8806 2009-05-31 22:28:54Z pesianstranger $
   39  */
   40 
   41 /**
   42  * The header
   43  *
   44  * Implements all functions that are executed within the header of the page
   45  * (meta tags, header expiration, etc)
   46  * It will all be echoed, so no return in this function
   47  *
   48  * @param bool  $closehead  close the <head> tag
   49  */
   50 function xoops_header($closehead=true) {
   51     global $icmsConfig, $xoopsTheme, $icmsConfigPlugins, $icmsConfigMetaFooter;
   52     $myts =& icms_core_Textsanitizer::getInstance();
   53 
   54     if(!headers_sent())
   55     {
   56         header('Content-Type:text/html; charset='._CHARSET);
   57         header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
   58         header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
   59         header('Cache-Control: no-store, no-cache, max-age=1, s-maxage=1, must-revalidate, post-check=0, pre-check=0');
   60         header("Pragma: no-cache");
   61         header("X-Frame-Options: SAMEORIGIN");
   62     }
   63     echo "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>";
   64     echo '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="'._LANGCODE.'" lang="'._LANGCODE.'">
   65     <head>
   66     <meta http-equiv="content-type" content="text/html; charset='._CHARSET.'" />
   67     <meta http-equiv="content-language" content="'._LANGCODE.'" />
   68     <meta name="robots" content="'.htmlspecialchars($icmsConfigMetaFooter['meta_robots']).'" />
   69     <meta name="keywords" content="'.htmlspecialchars($icmsConfigMetaFooter['meta_keywords']).'" />
   70     <meta name="description" content="'.htmlspecialchars($icmsConfigMetaFooter['meta_description']).'" />
   71     <meta name="rating" content="'.htmlspecialchars($icmsConfigMetaFooter['meta_rating']).'" />
   72     <meta name="author" content="'.htmlspecialchars($icmsConfigMetaFooter['meta_author']).'" />
   73     <meta name="copyright" content="'.htmlspecialchars($icmsConfigMetaFooter['meta_copyright']).'" />
   74     <meta name="generator" content="ImpressCMS" />
   75     <title>'.htmlspecialchars($icmsConfig['sitename']).'</title>
   76     <script type="text/javascript" src="'.ICMS_URL.'/include/xoops.js"></script>
   77     <script type="text/javascript" src="'.ICMS_URL.'/include/linkexternal.js"></script>
   78     <link rel="stylesheet" type="text/css" media="all" href="' . ICMS_URL . '/icms'.(( defined('_ADM_USE_RTL') && _ADM_USE_RTL )?'_rtl':'').'.css" />';
   79 
   80     $style_info = '';
   81     if(!empty($icmsConfigPlugins['sanitizer_plugins'])){
   82         foreach ($icmsConfigPlugins['sanitizer_plugins'] as $key) {
   83             if( empty( $key ) )
   84             continue;
   85             if(file_exists(ICMS_ROOT_PATH.'/plugins/textsanitizer/'.$key.'/'.$key.'.css')){
   86                 echo '<link rel="stylesheet" media="screen" href="'.ICMS_URL.'/plugins/textsanitizer/'.$key.'/'.$key.'.css" type="text/css" />';
   87             }else{
   88                 $extension = include_once ICMS_ROOT_PATH.'/plugins/textsanitizer/'.$key.'/'.$key.'.php';
   89                 $func = 'style_'.$key;
   90                 if ( function_exists($func) ) {
   91                     $style_info = $func();
   92                     if (!empty($style_info)) {
   93                         if(!file_exists(ICMS_ROOT_PATH.'/'.$style_info)){
   94                             echo '<style media="screen" type="text/css">
   95                             '.$style_info.'
   96                             </style>';
   97                         }else{
   98                             echo '<link rel="stylesheet" media="screen" href="'.$style_info.'" type="text/css" />';
   99                         }
  100                     }
  101                 }
  102             }
  103         }
  104     }
  105 
  106     $themecss = xoops_getcss($icmsConfig['theme_set']);
  107     if ($themecss) {
  108         echo '<link rel="stylesheet" type="text/css" media="all" href="'.$themecss.'" />';
  109     }
  110     if ($closehead) {
  111         echo '</head><body>';
  112     }
  113 }
  114 
  115 /**
  116  * The footer
  117  *
  118  * Implements all functions that are executed in the footer
  119  */
  120 function xoops_footer() {
  121     global $icmsConfigMetaFooter;
  122     echo '</body></html>';
  123     ob_end_flush();
  124 }
  125 
  126 
  127 /**
  128  * Get the timestamp based on the user settings
  129  *
  130  * @param string  $time  String with time
  131  * @param string  $timeoffset  The time offset string
  132  * @return string  $usertimestamp  The generated user timestamp
  133  * @todo Move to a static class method - user
  134  */
  135 function xoops_getUserTimestamp($time, $timeoffset="")
  136 {
  137     global $icmsConfig;
  138     if($timeoffset == '')
  139     {
  140         if(icms::$user) {$timeoffset = icms::$user->getVar('timezone_offset');}
  141         else {$timeoffset = $icmsConfig['default_TZ'];}
  142     }
  143     $usertimestamp = (int) ($time) + ((float)($timeoffset) - $icmsConfig['server_TZ'])*3600;
  144     return $usertimestamp;
  145 }
  146 
  147 /**
  148  * Function to calculate server timestamp from user entered time (timestamp)
  149  *
  150  * @param string  $timestamp  String with time
  151  * @return string  $timestamp  The generated timestamp
  152  * @todo Move to a static class method - date and time
  153  */
  154 function userTimeToServerTime($timestamp, $userTZ=null)
  155 {
  156     global $icmsConfig;
  157     if(!isset($userTZ)) {$userTZ = $icmsConfig['default_TZ'];}
  158     $timestamp = $timestamp - (($userTZ - $icmsConfig['server_TZ']) * 3600);
  159     return $timestamp;
  160 }
  161 
  162 /**
  163  * Format an URL
  164  *
  165  * @param string  $url  The URL to format
  166  * @return string  $url The generated URL
  167  * @todo Move to a static class method - string formatting
  168  */
  169 function formatURL($url)
  170 {
  171     $url = trim($url);
  172     if($url != '')
  173     {
  174         if((!preg_match("/^http[s]*:\/\//i", $url)) && (!preg_match("/^ftp*:\/\//i", $url)) && (!preg_match("/^ed2k*:\/\//i", $url))) {$url = 'http://'.$url;}
  175     }
  176     return $url;
  177 }
  178 
  179 /**
  180  * Function to redirect a user to certain pages
  181  *
  182  * @param string  $url  The URL to redirect to
  183  * @param int  $time  The time it takes to redirect to the URL
  184  * @param string  $message  The message to show while redirecting
  185  * @param bool  $addredirect  Add a link to the redirect URL?
  186  * @param string  $allowExternalLink  Allow external links
  187  */
  188 function redirect_header($url, $time = 3, $message = '', $addredirect = true, $allowExternalLink = false)
  189 {
  190     global $icmsConfig, $icmsConfigPersona;
  191     if(preg_match("/[\\0-\\31]|about:|script:/i", $url))
  192     {
  193         if(preg_match('/^\b(java)?script:([\s]*)history\.go\(-[0-9]*\)([\s]*[;]*[\s]*)$/si', $url)) {$url = ICMS_URL;}
  194     }
  195     if(!$allowExternalLink && $pos = strpos($url, '://' ))
  196     {
  197         $xoopsLocation = substr(ICMS_URL, strpos(ICMS_URL, '://') + 3);
  198         if(substr($url, $pos + 3, strlen($xoopsLocation)) != $xoopsLocation) {$url = ICMS_URL;}
  199         elseif(substr($url, $pos + 3, strlen($xoopsLocation)+1) == $xoopsLocation.'.') {$url = ICMS_URL;}
  200     }
  201     $theme = $icmsConfig['theme_set'];
  202     // if the user selected a theme in the theme block, let's use this theme
  203     if(isset($_SESSION['xoopsUserTheme']) && in_array($_SESSION['xoopsUserTheme'], $icmsConfig['theme_set_allowed'])) {$theme = $_SESSION['xoopsUserTheme'];}
  204 
  205     $xoopsThemeFactory = new icms_view_theme_Factory();
  206     $xoopsThemeFactory->allowedThemes = $icmsConfig['theme_set_allowed'];
  207     $xoopsThemeFactory->defaultTheme = $theme;
  208     $icmsTheme = $xoTheme =& $xoopsThemeFactory->createInstance(array("plugins" => array()));
  209     $xoopsTpl = $icmsTpl =& $xoTheme->template;
  210 
  211     if($icmsConfig['debug_mode'] == 2 && is_object(icms::$user) &&  icms::$user->isAdmin())
  212     {
  213         $xoopsTpl->assign('time', 300);
  214         $xoopsTpl->assign('xoops_logdump', icms::$logger->dump());
  215     }
  216     else {$xoopsTpl->assign('time', (int) ($time));}
  217     if(!empty($_SERVER['REQUEST_URI']) && $addredirect && strstr($url, 'user.php'))
  218     {
  219         if(!strstr($url, '?')) {$url .= '?xoops_redirect='.urlencode($_SERVER['REQUEST_URI']);}
  220         else {$url .= '&amp;xoops_redirect='.urlencode($_SERVER['REQUEST_URI']);}
  221     }
  222     if(defined('SID') && SID && (!isset($_COOKIE[session_name()]) || ($icmsConfig['use_mysession'] && $icmsConfig['session_name'] != '' && !isset($_COOKIE[$icmsConfig['session_name']]))))
  223     {
  224         if(!strstr($url, '?')) {$url .= '?' . SID;}
  225         else {$url .= '&amp;'.SID;}
  226     }
  227     $url = preg_replace("/&amp;/i", '&', htmlspecialchars($url, ENT_QUOTES));
  228     $xoopsTpl->assign('url', $url);
  229     $message = trim($message) != '' ? $message : _TAKINGBACK;
  230     $xoopsTpl->assign('message', $message);
  231     $xoopsTpl->assign('lang_ifnotreload', sprintf(_IFNOTRELOAD, $url));
  232     // GIJ start
  233     if( ! headers_sent() && $icmsConfigPersona['use_custom_redirection']==1) {
  234         $_SESSION['redirect_message'] = $message ;
  235         header( "Location: ".preg_replace("/[&]amp;/i",'&',$url) ) ;
  236         exit();
  237     }else{
  238         $xoopsTpl->display('db:system_redirect.html');
  239         if (defined('XOOPS_CPFUNC_LOADED')) {
  240             icms_cp_footer();
  241         } else {
  242             include ICMS_ROOT_PATH.'/footer.php';
  243         }
  244         exit();
  245     }
  246     // GIJ end
  247 }
  248 
  249 /**
  250  * Gets environment key from the $_SERVER or $_ENV superglobal
  251  *
  252  * @param string  $key  The key to get
  253  * @return string  $ret  The retrieved key
  254  */
  255 function xoops_getenv($key)
  256 {
  257     $ret = '';
  258     if(array_key_exists($key, $_SERVER) && isset($_SERVER[$key]))
  259     {
  260         $ret = $_SERVER[$key];
  261         return $ret;
  262     }
  263     if(array_key_exists($key, $_ENV) && isset($_ENV[$key]))
  264     {
  265         $ret = $_ENV[$key];
  266         return $ret;
  267     }
  268     return $ret;
  269 }
  270 
  271 /**
  272  * Function to get css file for a certain themeset
  273  *
  274  * @param string  $theme  The theme set from the config
  275  * @return mixed  The generated theme HTML string or an empty string
  276  */
  277 function xoops_getcss($theme = '')
  278 {
  279     if($theme == '') {$theme = $GLOBALS['icmsConfig']['theme_set'];}
  280     $uagent = xoops_getenv('HTTP_USER_AGENT');
  281     if(stristr($uagent, 'mac')) {$str_css = 'styleMAC.css';}
  282     elseif(preg_match("/MSIE ([0-9]\.[0-9]{1,2})/i", $uagent)) {$str_css = 'style.css';}
  283     else {$str_css = 'styleNN.css';}
  284     if(is_dir(ICMS_THEME_PATH.'/'.$theme))
  285     {
  286         if(file_exists(ICMS_THEME_PATH.'/'.$theme.'/'.$str_css)) {return ICMS_THEME_URL.'/'.$theme.'/'.$str_css;}
  287         elseif(file_exists(ICMS_THEME_PATH.'/'.$theme.'/style.css')) {return ICMS_THEME_URL.'/'.$theme.'/style.css';}
  288     }
  289     if(is_dir(ICMS_THEME_PATH.'/'.$theme.'/css'))
  290     {
  291         if(file_exists(ICMS_THEME_PATH.'/'.$theme.'/css/'.$str_css)) {return ICMS_THEME_URL.'/'.$theme.'/css/'.$str_css;}
  292         elseif(file_exists(ICMS_THEME_PATH.'/'.$theme.'/css/style.css')) {return ICMS_THEME_URL.'/'.$theme.'/css/style.css';}
  293     }
  294     return '';
  295 }
  296 
  297 /**
  298  * Gets the handler for a class
  299  *
  300  * @param string  $name  The name of the handler to get
  301  * @param bool  $optional   Is the handler optional?
  302  * @return      object      $inst       The instance of the object that was created
  303  * @todo This will not be needed when the autoload is complete
  304  */
  305 function &xoops_gethandler($name, $optional = false) {
  306     // Lookup table: old xoops names => fully qualified refactored name
  307     $lookup = array(
  308         //"avatar"          => "",
  309         //"block"               => "icms_block",
  310         //"blockposition"       => "icms_block_position",
  311         //"comment"         => "",
  312         "config"            => "icms_config",
  313         //"configcategory"  => "",
  314         //"configitem"      => "",
  315         //"configoption"        => "",
  316         //"group"               => "",
  317         //"groupperm"           => "",
  318         //"image"               => "",
  319         //"imagecategory"       => "",
  320         //"imageset"            => "",
  321         //"member"          => "",
  322         //"module"          => "",
  323         //"notification"        => "",
  324         //"object"          => "",
  325         //"online"          => "",
  326         //"page"                => "",
  327         //"privmessage"     => "",
  328         //"session"         => "",
  329         //"tplfile"         => "",
  330         //"tplset"          => "",
  331         //"icmspersistablecategory" => "",
  332     );
  333     $lower = strtolower($name);
  334     return icms::handler(isset($lookup[$lower]) ? $lookup[$lower] : $name);
  335 }
  336 
  337 // RMV-NOTIFY
  338 // ################ Notification Helper Functions ##################
  339 /**
  340  * We want to be able to delete by module, by user, or by item.
  341  * How do we specify this??
  342  *
  343  * @param   int  $module_id The ID of the module to unsubscribe from
  344  * @return  bool    Did the unsubscribing succeed?
  345  * @todo Move to a static class method - Notification
  346  */
  347 function xoops_notification_deletebymodule ($module_id)
  348 {
  349     $notification_handler = icms::handler('icms_data_notification');
  350     return $notification_handler->unsubscribeByModule ($module_id);
  351 }
  352 
  353 /**
  354  * Deletes / unsubscribes by user ID
  355  *
  356  * @param   int  $user_id   The User ID to unsubscribe
  357  * @return  bool    Did the unsubscribing succeed?
  358  * @todo Move to a static class method - Notification
  359  */
  360 function xoops_notification_deletebyuser ($user_id)
  361 {
  362     $notification_handler =& icms::handler('icms_data_notification');
  363     return $notification_handler->unsubscribeByUser ($user_id);
  364 }
  365 
  366 /**
  367  * Deletes / unsubscribes by Item ID
  368  *
  369  * @param   int  $module_id The Module ID to unsubscribe
  370  * @param   int  $category  The Item ID to unsubscribe
  371  * @param   int  $item_id   The Item ID to unsubscribe
  372  * @return  bool    Did the unsubscribing succeed?
  373  * @todo Move to a static class method - Notification
  374  */
  375 function xoops_notification_deletebyitem ($module_id, $category, $item_id)
  376 {
  377     $notification_handler =& icms::handler('icms_data_notification');
  378     return $notification_handler->unsubscribeByItem ($module_id, $category, $item_id);
  379 }
  380 
  381 // ################### Comment helper functions ####################
  382 /**
  383  * Count the comments belonging to a certain item in a certain module
  384  *
  385  * @param   int  $module_id The Module ID to count the comments for
  386  * @param   int  $item_id   The Item ID to count the comments for
  387  * @return  int The number of comments
  388  * @todo Move to a static class method - Comment
  389  */
  390 function xoops_comment_count($module_id, $item_id = null)
  391 {
  392     $comment_handler = icms::handler('icms_data_comment');
  393     $criteria = new icms_db_criteria_Compo(new icms_db_criteria_Item('com_modid', (int) ($module_id)));
  394     if(isset($item_id)) {$criteria->add(new icms_db_criteria_Item('com_itemid', (int) ($item_id)));}
  395     return $comment_handler->getCount($criteria);
  396 }
  397 
  398 /**
  399  * Delete the comments belonging to a certain item in a certain module
  400  *
  401  * @param   int  $module_id The Module ID to delete the comments for
  402  * @param   int  $item_id   The Item ID to delete the comments for
  403  * @return  bool    Did the deleting of the comments succeed?
  404  * @todo Move to a static class method - Comment
  405  */
  406 function xoops_comment_delete($module_id, $item_id)
  407 {
  408     if( (int) ($module_id) > 0 && (int) ($item_id) > 0)
  409     {
  410         $comment_handler = icms::handler('icms_data_comment');
  411         $comments =& $comment_handler->getByItemId($module_id, $item_id);
  412         if(is_array($comments))
  413         {
  414             $count = count($comments);
  415             $deleted_num = array();
  416             for($i = 0; $i < $count; $i++)
  417             {
  418                 if(false != $comment_handler->delete($comments[$i]))
  419                 {
  420                     // store poster ID and deleted post number into array for later use
  421                     $poster_id = $comments[$i]->getVar('com_uid');
  422                     if($poster_id != 0) {$deleted_num[$poster_id] = !isset($deleted_num[$poster_id]) ? 1 : ($deleted_num[$poster_id] + 1);}
  423                 }
  424             }
  425             $member_handler = icms::handler('icms_member');
  426             foreach($deleted_num as $user_id => $post_num)
  427             {
  428                 // update user posts
  429                 $com_poster = $member_handler->getUser($user_id);
  430                 if(is_object($com_poster)) {$member_handler->updateUserByField($com_poster, 'posts', $com_poster->getVar('posts') - $post_num);}
  431             }
  432             return true;
  433         }
  434     }
  435     return false;
  436 }
  437 
  438 // ################ Group Permission Helper Functions ##################
  439 /**
  440  * Deletes group permissions by module and item id
  441  *
  442  * @param   int  $module_id The Module ID to delete the permissions for
  443  * @param   string  $perm_name  The permission name (for the module_id and item_id to delete
  444  * @param   int  $item_id   The Item ID to delete the permissions for
  445  * @return  int Did the deleting of the group permissions succeed?
  446  * @todo Move to a static class method - Groupperm
  447  */
  448 function xoops_groupperm_deletebymoditem($module_id, $perm_name, $item_id = null)
  449 {
  450     // do not allow system permissions to be deleted
  451     if( (int) ($module_id) <= 1) {return false;}
  452     $gperm_handler = icms::handler('icms_member_groupperm');
  453     return $gperm_handler->deleteByModule($module_id, $perm_name, $item_id);
  454 }
  455 
  456 /**
  457  * Converts text to UTF-8 encoded text
  458  *
  459  * @param   string  $text   The Text to convert
  460  * @return  string  $text   The converted text
  461  * @todo Move to a static class method - String
  462  */
  463 function xoops_utf8_encode(&$text)
  464 {
  465     if(XOOPS_USE_MULTIBYTES == 1)
  466     {
  467         if(function_exists('mb_convert_encoding')) {return mb_convert_encoding($text, 'UTF-8', 'auto');}
  468         return $text;
  469     }
  470     return utf8_encode($text);
  471 }
  472 
  473 /**
  474  * Converts text to UTF-8 encoded text
  475  * @see xoops_utf8_encode
  476  * @todo Move to a static class method - String
  477  */
  478 function xoops_convert_encoding(&$text) {return xoops_utf8_encode($text);}
  479 
  480 /**
  481  * Get the icmsModule object of a specified module
  482  *
  483  * @param string $moduleName dirname of the module
  484  * @return object icmsModule object of the specified module
  485  * @todo Move to a static class method - Module
  486  */
  487 function &icms_getModuleInfo($moduleName = false)
  488 {
  489     static $icmsModules;
  490     if(isset($icmsModules[$moduleName]))
  491     {
  492         $ret =& $icmsModules[$moduleName];
  493         return $ret;
  494     }
  495     global $icmsModule;
  496     if(!$moduleName)
  497     {
  498         if(isset($icmsModule) && is_object($icmsModule))
  499         {
  500             $icmsModules[$icmsModule->getVar('dirname')] = & $icmsModule;
  501             return $icmsModules[$icmsModule->getVar('dirname')];
  502         }
  503     }
  504     if(!isset($icmsModules[$moduleName]))
  505     {
  506         if(isset($icmsModule) && is_object($icmsModule) && $icmsModule->getVar('dirname') == $moduleName) {$icmsModules[$moduleName] = & $icmsModule;}
  507         else
  508         {
  509             $hModule = icms::handler('icms_module');
  510             if($moduleName != 'icms') {$icmsModules[$moduleName] = $hModule->getByDirname($moduleName);}
  511             else {$icmsModules[$moduleName] = & $hModule->getByDirname('system');}
  512         }
  513     }
  514     return $icmsModules[$moduleName];
  515 }
  516 
  517 /**
  518  * Get the config array of a specified module
  519  *
  520  * @param string $moduleName dirname of the module
  521  * @return array of configs
  522  * @todo Move to a static class method - Module
  523  */
  524 function &icms_getModuleConfig($moduleName = false)
  525 {
  526     static $icmsConfigs;
  527     if(isset ($icmsConfigs[$moduleName]))
  528     {
  529         $ret = & $icmsConfigs[$moduleName];
  530         return $ret;
  531     }
  532     global $icmsModule, $icmsModuleConfig;
  533     if(!$moduleName)
  534     {
  535         if(isset($icmsModule) && is_object($icmsModule))
  536         {
  537             $icmsConfigs[$icmsModule->getVar('dirname')] = & $icmsModuleConfig;
  538             return $icmsConfigs[$icmsModule->getVar('dirname')];
  539         }
  540     }
  541     // if we still did not found the icmsModule, this is because there is none
  542     if(!$moduleName)
  543     {
  544         $ret = false;
  545         return $ret;
  546     }
  547     if(isset($icmsModule) && is_object($icmsModule) && $icmsModule->getVar('dirname') == $moduleName) {$icmsConfigs[$moduleName] = & $icmsModuleConfig;}
  548     else
  549     {
  550         $module = & icms_getModuleInfo($moduleName);
  551         if(!is_object($module))
  552         {
  553             $ret = false;
  554             return $ret;
  555         }
  556         $hModConfig = icms::handler('icms_config');
  557         $icmsConfigs[$moduleName] = & $hModConfig->getConfigsByCat(0, $module->getVar('mid'));
  558     }
  559     return $icmsConfigs[$moduleName];
  560 }
  561 
  562 /**
  563  * Get a specific module config value
  564  *
  565  * @param string $key
  566  * @param string $moduleName
  567  * @param mixed $default
  568  * @return mixed
  569  * @todo Move to a static class method - Config
  570  */
  571 function icms_getConfig($key, $moduleName = false, $default = 'default_is_undefined')
  572 {
  573     if(!$moduleName) {$moduleName = icms_getCurrentModuleName();}
  574     $configs = icms_getModuleConfig($moduleName);
  575     if(isset($configs[$key])) {return $configs[$key];}
  576     else
  577     {
  578         if($default === 'default_is_undefined') {return null;}
  579         else {return $default;}
  580     }
  581 }
  582 
  583 /**
  584  * Get the dirname of the current module
  585  *
  586  * @return mixed dirname of the current module or false if no module loaded
  587  * @todo Move to a static class method - Module
  588  */
  589 function icms_getCurrentModuleName()
  590 {
  591     global $icmsModule;
  592     if(is_object($icmsModule)) {return $icmsModule->getVar('dirname');}
  593     else {return false;}
  594 }
  595 
  596 /**
  597  * Checks if a user is admin of $module
  598  *
  599  * @param mixed Module to check or false if no module is passed
  600  * @return bool : true if user is admin
  601  * @todo Move to a static class method - User
  602  */
  603 function icms_userIsAdmin($module = false)
  604 {
  605     static $icms_isAdmin;
  606     if(!$module)
  607     {
  608         global $icmsModule;
  609         $module = $icmsModule->getVar('dirname');
  610     }
  611     if(isset ($icms_isAdmin[$module])) {return $icms_isAdmin[$module];}
  612     if(!icms::$user)
  613     {
  614         $icms_isAdmin[$module] = false;
  615         return $icms_isAdmin[$module];
  616     }
  617     $icms_isAdmin[$module] = false;
  618     $icmsModule = icms_getModuleInfo($module);
  619     if(!is_object($icmsModule)) {return false;}
  620     $module_id = $icmsModule->getVar('mid');
  621     $icms_isAdmin[$module] = icms::$user->isAdmin($module_id);
  622     return $icms_isAdmin[$module];
  623 }
  624 
  625 /**
  626  * Load a module language file
  627  *
  628  * If $module = core, file will be loaded from ICMS_ROOT_PATH/language/
  629  *
  630  * @param string $module dirname of the module
  631  * @param string $file name of the file without ".php"
  632  * @param bool $admin is this for a core admin side feature ?
  633  *
  634  */
  635 function icms_loadLanguageFile($module, $file, $admin=false)
  636 {
  637     global $icmsConfig;
  638     if($module == 'core') {$languagePath = ICMS_ROOT_PATH.'/language/';}
  639     else {$languagePath = ICMS_ROOT_PATH.'/modules/'.$module.'/language/';}
  640     $extraPath = $admin ? 'admin/' : '';
  641     $filename = $languagePath.$icmsConfig['language'].'/'.$extraPath.$file.'.php';
  642     if(!file_exists($filename)) {$filename = $languagePath.'english/'.$extraPath.$file.'.php';}
  643     if(file_exists($filename)) {include_once $filename ;}
  644 }
  645 
  646 /**
  647  * @author pillepop2003 at yahoo dot de
  648  *
  649  * Use this snippet to extract any float out of a string. You can choose how a single dot is treated with the (bool) 'single_dot_as_decimal' directive.
  650  * This function should be able to cover almost all floats that appear in an european environment.
  651  *
  652  * @param string $str   String to get float value from
  653  * @param mixed $set    Array of settings of False if no settings were passed
  654  * @param mixed Float value or 0 if no match was found in the string
  655  * @todo Move to a static class method - String/Data
  656  */
  657 function icms_getfloat($str, $set=FALSE)
  658 {
  659     if(preg_match("/([0-9\.,-]+)/", $str, $match))
  660     {
  661         // Found number in $str, so set $str that number
  662         $str = $match[0];
  663         if(strstr($str, ','))
  664         {
  665             // A comma exists, that makes it easy, cos we assume it separates the decimal part.
  666             $str = str_replace('.', '', $str); // Erase thousand seps
  667             $str = str_replace(',', '.', $str); // Convert , to . for (float) command
  668             return (float)($str);
  669         }
  670         else
  671         {
  672             // No comma exists, so we have to decide, how a single dot shall be treated
  673             if(preg_match("/^[0-9\-]*[\.]{1}[0-9-]+$/", $str) == TRUE && $set['single_dot_as_decimal'] == TRUE) {return (float)($str);}
  674             else
  675             {
  676                 $str = str_replace('.', '', $str);  // Erase thousand seps
  677                 return (float)($str);
  678             }
  679         }
  680     }
  681     else {return 0;}
  682 }
  683 
  684 /**
  685  * Use this snippet to extract any currency out of a string
  686  *
  687  * @param string $var   String to get currency value from
  688  * @param mixed $currencyObj    Currency object or false if no object was passed
  689  * @return string   $ret The returned value
  690  * @todo Move to a static class method - Currency
  691  */
  692 function icms_currency($var, $currencyObj=false)
  693 {
  694     $ret = icms_getfloat($var,  array('single_dot_as_decimal'=> TRUE));
  695     $ret = round($ret, 2);
  696     // make sure we have at least .00 in the $var
  697     $decimal_section_original = strstr($ret, '.');
  698     $decimal_section = $decimal_section_original;
  699     if($decimal_section)
  700     {
  701         if(strlen($decimal_section) == 1) {$decimal_section = '.00';}
  702         elseif(strlen($decimal_section) == 2) {$decimal_section = $decimal_section . '0';}
  703         $ret = str_replace($decimal_section_original, $decimal_section, $ret);
  704     }
  705     else {$ret = $ret . '.00';}
  706     if($currencyObj) {$ret = $ret.' '.$currencyObj->getCode();}
  707     return $ret;
  708 }
  709 
  710 /**
  711  * Strip text from unwanted text (purify)
  712  *
  713  * @param string $text  String to purify
  714  * @param mixed $keyword    The keyword string or false if none was passed
  715  * @return string   $text The purified text
  716  * @todo Remove this and use HTML Purifier
  717  */
  718 function icms_purifyText($text, $keyword = false) {
  719     $text = str_replace('&nbsp;', ' ', $text);
  720     $text = str_replace('<br />', ' ', $text);
  721     $text = str_replace('<br/>', ' ', $text);
  722     $text = str_replace('<br', ' ', $text);
  723     $text = strip_tags($text);
  724     $text = html_entity_decode($text);
  725     $text = icms_core_DataFilter::undoHtmlSpecialChars($text);
  726     $text = str_replace(')', ' ', $text);
  727     $text = str_replace('(', ' ', $text);
  728     $text = str_replace(':', ' ', $text);
  729     $text = str_replace('&euro', ' euro ', $text);
  730     $text = str_replace('&hellip', '...', $text);
  731     $text = str_replace('&rsquo', ' ', $text);
  732     $text = str_replace('!', ' ', $text);
  733     $text = str_replace('?', ' ', $text);
  734     $text = str_replace('"', ' ', $text);
  735     $text = str_replace('-', ' ', $text);
  736     $text = str_replace('\n', ' ', $text);
  737     $text = str_replace('&#8213;', ' ', $text);
  738 
  739     if($keyword) {
  740         $text = str_replace('.', ' ', $text);
  741         $text = str_replace(',', ' ', $text);
  742         $text = str_replace('\'', ' ', $text);
  743     }
  744     $text = str_replace(';', ' ', $text);
  745 
  746     return $text;
  747 }
  748 
  749 /**
  750  * Converts HTML to text equivalents
  751  *
  752  * @param string $document  The document string to convert
  753  * @return string   $text The converted text
  754  * @todo Remove this and use the proper data filter and HTML Purifier
  755  */
  756 function icms_html2text($document)
  757 {
  758     // PHP Manual:: function preg_replace
  759     // $document should contain an HTML document.
  760     // This will remove HTML tags, javascript sections
  761     // and white space. It will also convert some
  762     // common HTML entities to their text equivalent.
  763     // Credits : newbb2
  764     $search = array ("'<script[^>]*?>.*?</script>'si",  // Strip out javascript
  765     "'<img.*?/>'si",       // Strip out img tags
  766     "'<[\/\!]*?[^<>]*?>'si",          // Strip out HTML tags
  767     "'([\r\n])[\s]+'",              // Strip out white space
  768     "'&(quot|#34);'i",              // Replace HTML entities
  769     "'&(amp|#38);'i",
  770     "'&(lt|#60);'i",
  771     "'&(gt|#62);'i",
  772     "'&(nbsp|#160);'i",
  773     "'&(iexcl|#161);'i",
  774     "'&(cent|#162);'i",
  775     "'&(pound|#163);'i",
  776     "'&(copy|#169);'i"
  777     );
  778 
  779     $replace = array ("",
  780     "",
  781     "",
  782     "\\1",
  783     "\"",
  784     "&",
  785     "<",
  786     ">",
  787     " ",
  788     chr(161),
  789     chr(162),
  790     chr(163),
  791     chr(169)
  792     );
  793 
  794     $text = preg_replace($search, $replace, $document);
  795     $text = preg_replace_callback("'&#(\d+);'", function ($m) {
  796                 return chr($m[1]);
  797     }, $text);
  798     return $text;
  799 
  800 }
  801 
  802 /**
  803  * Function to keeps the code clean while removing unwanted attributes and tags.
  804  * This function was got from http://www.php.net/manual/en/function.strip-tags.php#81553
  805  *
  806  * @var $sSource - string - text to remove the tags
  807  * @var $aAllowedTags - array - tags that dont will be striped
  808  * @var $aDisabledAttributes - array - attributes not allowed, will be removed from the text
  809  *
  810  * @return string
  811  * @todo Remove this and replace with the proper data filter and HTML Purifier
  812  */
  813 function icms_cleanTags($sSource, $aAllowedTags = array('<h1>','<b>','<u>','<a>','<ul>','<li>'), $aDisabledAttributes = array('onabort', 'onblur', 'onchange', 'onclick', 'ondblclick', 'onerror', 'onfocus', 'onkeydown', 'onkeyup', 'onload', 'onmousedown', 'onmousemove', 'onmouseover', 'onmouseup', 'onreset', 'onresize', 'onselect', 'onsubmit', 'onunload'))
  814 {
  815     if(empty($aDisabledAttributes)) return strip_tags($sSource, implode('', $aAllowedTags));
  816     return preg_replace('/<(.*?)>/ie', "'<' . preg_replace(array('/javascript:[^\"\']*/i', '/(".implode('|', $aDisabledAttributes).")[ \\t\\n]*=[ \\t\\n]*[\"\'][^\"\']*[\"\']/i', '/\s+/'), array('', '', ' '), stripslashes('\\1')) . '>'", strip_tags($sSource, implode('', $aAllowedTags)));
  817 }
  818 
  819 /**
  820  * Store a cookie
  821  *
  822  * @param string $name name of the cookie
  823  * @param string $value value of the cookie
  824  * @param int $time duration of the cookie
  825  */
  826 function icms_setCookieVar($name, $value, $time = 0)
  827 {
  828     if($time == 0) {$time = time() + 3600 * 24 * 365;}
  829     setcookie($name, $value, $time, '/');
  830 }
  831 
  832 /**
  833  * Get a cookie value
  834  *
  835  * @param string $name name of the cookie
  836  * @param string $default value to return if cookie not found
  837  *
  838  * @return string value of the cookie or default value
  839  */
  840 function icms_getCookieVar($name, $default = '')
  841 {
  842     $name = str_replace('.', '_', $name);
  843     if((isset($_COOKIE[$name])) && ($_COOKIE[$name] > '')) {return $_COOKIE[$name];}
  844     else {return $default;}
  845 }
  846 
  847 /**
  848  * Get URL of the page before the form to be able to redirect their after the form has been posted
  849  *
  850  * @return string url before form
  851  */
  852 function icms_get_page_before_form()
  853 {
  854     return isset($_POST['icms_page_before_form'])
  855             ? icms_core_DataFilter::checkVar($_POST['icms_page_before_form'], 'url')
  856             : icms::$urls['previouspage'];
  857 }
  858 
  859 /**
  860  * Get URL of the page before the form to be able to redirect their after the form has been posted
  861  *
  862  * @param   array   $matches    Array of matches to sanitize
  863  * @return mixed The sanitized tag or empty string
  864  * @todo Move to a static class method - Customtag
  865  */
  866 function icms_sanitizeCustomtags_callback($matches) {
  867     $icms_customtag_handler = icms_getModuleHandler("customtag", "system");
  868     $icms_customTagsObj = $icms_customtag_handler->getCustomtagsByName();
  869     if (!isset($icms_customTagsObj[$matches[1]])) return "";
  870     return $icms_customTagsObj[$matches[1]]->renderWithPhp();
  871 }
  872 
  873 /**
  874  * Get URL of the page before the form to be able to redirect their after the form has been posted
  875  *
  876  * @param   array   $matches    Array of matches to sanitize
  877  * @return mixed The sanitized tag or empty string
  878  * @todo Move to a static class method - Adsense
  879  */
  880 function icms_sanitizeAdsenses_callback($matches) {
  881     $icms_adsense_handler = icms_getModuleHandler("adsense", "system");
  882     $icms_adsensesObj = $icms_adsense_handler->getAdsensesByTag();
  883     if (!isset($icms_adsensesObj[$matches[1]])) return '';
  884     return $icms_adsensesObj[$matches[1]]->render();
  885 }
  886 
  887 /**
  888  * Get an array of the table used in a module
  889  *
  890  * @param string $moduleName name of the module
  891  * @param $items array of items managed by the module
  892  * @return array of tables used in the module
  893  * @todo Move to a static class method - Module
  894  */
  895 function icms_getTablesArray($moduleName, $items)
  896 {
  897     $ret = array();
  898     if (is_array($items))
  899     foreach($items as $item) {$ret[] = $moduleName.'_'.$item;}
  900     return $ret;
  901 }
  902 
  903 /**
  904  * Function to create a navigation menu in content pages.
  905  * This function was based on the function that do the same in mastop publish module
  906  *
  907  * @param integer $id
  908  * @param string $separador
  909  * @param string $style
  910  * @return string
  911  */
  912 function showNav($id = null, $separador = '/', $style="style='font-weight:bold'")
  913 {
  914     $url = ICMS_URL.'/content.php';
  915     if($id == false) {return false;}
  916     else
  917     {
  918         if($id > 0)
  919         {
  920             /**
  921              * @todo this handler doesn't even exist since 1.2. check if the function is still required
  922              */
  923             $content_handler =& xoops_gethandler('content');
  924             $cont = $content_handler->get($id);
  925             if($cont->getVar('content_id') > 0)
  926             {
  927                 $seo = $content_handler->makeLink($cont);
  928                 $ret = "<a href='".$url."?page=".$seo."'>".$cont->getVar('content_title')."</a>";
  929                 if($cont->getVar('content_supid') == 0) {return "<a href='".ICMS_URL."'>"._CT_NAV."</a> $separador ".$ret;}
  930                 elseif($cont->getVar('content_supid') > 0) {$ret = showNav($cont->getVar('content_supid'), $separador)." $separador ".$ret;}
  931             }
  932         }
  933         else {return false;}
  934     }
  935     return $ret;
  936 }
  937 
  938 /**
  939  * Searches text for unwanted tags and removes them
  940  *
  941  * @param string $text  String to purify
  942  * @return string   $text The purified text
  943  * @todo Remove and replace with the proper data filter and HTML Purifier
  944  */
  945 function StopXSS($text)
  946 {
  947     if(!is_array($text))
  948     {
  949         $text = preg_replace("/\(\)/si", "", $text);
  950         $text = strip_tags($text);
  951         $text = str_replace(array("\"",">","<","\\"), "", $text);
  952     }
  953     else
  954     {
  955         foreach($text as $k=>$t)
  956         {
  957             if (is_array($t)) {
  958                 StopXSS($t);
  959             } else {
  960                 $t = preg_replace("/\(\)/si", "", $t);
  961                 $t = strip_tags($t);
  962                 $t = str_replace(array("\"",">","<","\\"), "", $t);
  963                 $text[$k] = $t;
  964             }
  965         }
  966     }
  967     return $text;
  968 }
  969 
  970 /**
  971  * Purifies the CSS that is put in the content (pages) system
  972  *
  973  * @param string $text  String to purify
  974  * @return string   $text The purified text
  975  * @todo Remove and replace with the proper data filter and HTML Purifier
  976  */
  977 function icms_sanitizeContentCss($text)
  978 {
  979     if(preg_match_all('/(.*?)\{(.*?)\}/ie',$text,$css))
  980     {
  981         $css = $css[0];
  982         $perm = $not_perm = array();
  983         foreach($css as $k=>$v)
  984         {
  985             if(!preg_match('/^\#impress_content(.*?)/ie',$v)) {$css[$k] = '#impress_content '.icms_cleanTags(trim($v),array())."\r\n";}
  986             else {$css[$k] = icms_cleanTags(trim($v),array())."\r\n";}
  987         }
  988         $text = implode($css);
  989     }
  990     return $text;
  991 }
  992 
  993 /**
  994  * Function to get the base domain name from a URL.
  995  * credit for this function should goto Phosphorus and Lime, it is released under LGPL.
  996  *
  997  * @param string $url the URL to be stripped.
  998  * @return string
  999  * @todo Move to a static class method - HTTP or URI
 1000  */
 1001 function icms_get_base_domain($url)
 1002 {
 1003     $debug = 0;
 1004     $base_domain = '';
 1005 
 1006     // generic tlds (source: http://en.wikipedia.org/wiki/Generic_top-level_domain)
 1007     $G_TLD = array(
 1008     'biz','com','edu','gov','info','int','mil','name','net','org','aero','asia','cat','coop','jobs','mobi','museum','pro','tel','travel',
 1009     'arpa','root','berlin','bzh','cym','gal','geo','kid','kids','lat','mail','nyc','post','sco','web','xxx',
 1010     'nato', 'example','invalid','localhost','test','bitnet','csnet','ip','local','onion','uucp','co');
 1011 
 1012     // country tlds (source: http://en.wikipedia.org/wiki/Country_code_top-level_domain)
 1013     $C_TLD = array(
 1014     // active
 1015     'ac','ad','ae','af','ag','ai','al','am','an','ao','aq','ar','as','at','au','aw','ax','az',
 1016     'ba','bb','bd','be','bf','bg','bh','bi','bj','bm','bn','bo','br','bs','bt','bw','by','bz',
 1017     'ca','cc','cd','cf','cg','ch','ci','ck','cl','cm','cn','co','cr','cu','cv','cx','cy','cz',
 1018     'de','dj','dk','dm','do','dz','ec','ee','eg','er','es','et','eu','fi','fj','fk','fm','fo',
 1019     'fr','ga','gd','ge','gf','gg','gh','gi','gl','gm','gn','gp','gq','gr','gs','gt','gu','gw',
 1020     'gy','hk','hm','hn','hr','ht','hu','id','ie','il','im','in','io','iq','ir','is','it','je',
 1021     'jm','jo','jp','ke','kg','kh','ki','km','kn','kr','kw','ky','kz','la','lb','lc','li','lk',
 1022     'lr','ls','lt','lu','lv','ly','ma','mc','md','mg','mh','mk','ml','mm','mn','mo','mp','mq',
 1023     'mr','ms','mt','mu','mv','mw','mx','my','mz','na','nc','ne','nf','ng','ni','nl','no','np',
 1024     'nr','nu','nz','om','pa','pe','pf','pg','ph','pk','pl','pn','pr','ps','pt','pw','py','qa',
 1025     're','ro','ru','rw','sa','sb','sc','sd','se','sg','sh','si','sk','sl','sm','sn','sr','st',
 1026     'sv','sy','sz','tc','td','tf','tg','th','tj','tk','tl','tm','tn','to','tr','tt','tv','tw',
 1027     'tz','ua','ug','uk','us','uy','uz','va','vc','ve','vg','vi','vn','vu','wf','ws','ye','yu',
 1028     'za','zm','zw',
 1029     // inactive
 1030     'eh','kp','me','rs','um','bv','gb','pm','sj','so','yt','su','tp','bu','cs','dd','zr');
 1031 
 1032     // get domain
 1033     if(!$full_domain = icms_get_url_domain($url)) {return $base_domain;}
 1034 
 1035     // break up domain, reverse
 1036     $DOMAIN = explode('.', $full_domain);
 1037     if($debug) print_r($DOMAIN);
 1038     $DOMAIN = array_reverse($DOMAIN);
 1039     if($debug) print_r($DOMAIN);
 1040 
 1041     // first check for ip address
 1042     if(count($DOMAIN) == 4 && is_numeric($DOMAIN[0]) && is_numeric($DOMAIN[3])) {return $full_domain;}
 1043 
 1044     // if only 2 domain parts, that must be our domain
 1045     if(count($DOMAIN) <= 2) return $full_domain;
 1046 
 1047     /*
 1048      finally, with 3+ domain parts: obviously D0 is tld now,
 1049      if D0 = ctld and D1 = gtld, we might have something like com.uk so,
 1050      if D0 = ctld && D1 = gtld && D2 != 'www', domain = D2.D1.D0 else if D0 = ctld && D1 = gtld && D2 == 'www',
 1051      domain = D1.D0 else domain = D1.D0 - these rules are simplified below.
 1052      */
 1053     if(in_array($DOMAIN[0], $C_TLD) && in_array($DOMAIN[1], $G_TLD) && $DOMAIN[2] != 'www')
 1054     {
 1055         $full_domain = $DOMAIN[2].'.'.$DOMAIN[1].'.'.$DOMAIN[0];
 1056     }
 1057     else
 1058     {
 1059         $full_domain = $DOMAIN[1].'.'.$DOMAIN[0];
 1060     }
 1061     // did we succeed?
 1062     return $full_domain;
 1063 }
 1064 
 1065 /**
 1066  * Function to get the domain from a URL.
 1067  * credit for this function should goto Phosphorus and Lime, it is released under LGPL.
 1068  *
 1069  * @param string $url the URL to be stripped.
 1070  * @return string
 1071  * @todo Move to a static class method - HTTP or URI
 1072  */
 1073 function icms_get_url_domain($url)
 1074 {
 1075     $domain = '';
 1076     $_URL = parse_url($url);
 1077 
 1078     if(!empty($_URL) || !empty($_URL['host'])) {$domain = $_URL['host'];}
 1079     return $domain;
 1080 }
 1081 
 1082 /**
 1083  * Function to wordwrap given text.
 1084  *
 1085  * @param string $str   The text to be wrapped.
 1086  * @param string $width The column width - text will be wrapped when longer than $width.
 1087  * @param string $break The line is broken using the optional break parameter.
 1088  *          can be '/n' or '<br />'
 1089  * @param string $cut   If cut is set to TRUE, the string is always wrapped at the specified width.
 1090  *          So if you have a word that is larger than the given width, it is broken apart..
 1091  * @return string
 1092  * @todo Move to a static class method - String
 1093  */
 1094 function icms_wordwrap($str, $width, $break = '/n', $cut = false)
 1095 {
 1096     if(strtolower(_CHARSET) !== 'utf-8')
 1097     {
 1098         $str = wordwrap($str, $width, $break, $cut);
 1099         return $str;
 1100     }
 1101     else
 1102     {
 1103         $splitedArray = array();
 1104         $lines = explode("\n", $str);
 1105         foreach($lines as $line)
 1106         {
 1107             $lineLength = strlen($line);
 1108             if($lineLength > $width)
 1109             {
 1110                 $words = explode("\040", $line);
 1111                 $lineByWords = '';
 1112                 $addNewLine = true;
 1113                 foreach($words as $word)
 1114                 {
 1115                     $lineByWordsLength = strlen($lineByWords);
 1116                     $tmpLine = $lineByWords.((strlen($lineByWords) !== 0) ? ' ' : '').$word;
 1117                     $tmplineByWordsLength = strlen($tmpLine);
 1118                     if($tmplineByWordsLength > $width && $lineByWordsLength <= $width && $lineByWordsLength !== 0)
 1119                     {
 1120                         $splitedArray[] = $lineByWords;
 1121                         $lineByWords = '';
 1122                     }
 1123                     $newLineByWords = $lineByWords.((strlen($lineByWords) !== 0) ? ' ' : '').$word;
 1124                     $newLineByWordsLength = strlen($newLineByWords);
 1125                     if($cut && $newLineByWordsLength > $width)
 1126                     {
 1127                         for($i = 0; $i < $newLineByWordsLength; $i = $i + $width) {$splitedArray[] = mb_substr($newLineByWords, $i, $width);}
 1128                         $addNewLine = false;
 1129                     }
 1130                     else    {$lineByWords = $newLineByWords;}
 1131                 }
 1132                 if($addNewLine) {$splitedArray[] = $lineByWords;}
 1133             }
 1134             else    {$splitedArray[] = $line;}
 1135         }
 1136         return implode($break, $splitedArray);
 1137     }
 1138 }
 1139 
 1140 /**
 1141  * Function to get a query from DB
 1142  *
 1143  * @param object $db    Reference to the database object
 1144  * @param string    $table  The table to get the value from
 1145  * @param string    $field  The table to get the value from
 1146  * @param string    $condition  The where condition (where clause) to use
 1147  * @return  mixed
 1148  * @todo Move to a static class method - database
 1149  */
 1150 function getDbValue(&$db, $table, $field, $condition = '')
 1151 {
 1152     $table = $db->prefix( $table );
 1153     $sql = "SELECT `$field` FROM `$table`";
 1154     if($condition) {$sql .= " WHERE $condition";}
 1155     $result = $db->query($sql);
 1156     if($result)
 1157     {
 1158         $row = $db->fetchRow($result);
 1159         if($row) {return $row[0];}
 1160     }
 1161     return false;
 1162 }
 1163 
 1164 /**
 1165  * Function to escape $value makes safe for DB Queries.
 1166  *
 1167  * @param string $quotes - true/false - determines whether to add quotes to the value or not.
 1168  * @param string $value - $variable that is being escaped for query.
 1169  * @return string
 1170  * @todo Move to a static class method - Database or Filter
 1171  * @todo    get_magic_quotes_gpc is removed in PHP 5.4
 1172  */
 1173 function icms_escapeValue($value, $quotes = true)
 1174 {
 1175     if(is_string($value))
 1176     {
 1177         if(get_magic_quotes_gpc) {$value = stripslashes($value);}
 1178         $value = icms::$xoopsDB->escape($value);
 1179         if($quotes) {$value = '"'.$value.'"';}
 1180     }
 1181     elseif($value === null) {$value = 'NULL';}
 1182     elseif(is_bool($value)) {$value = $value ? 1 : 0;}
 1183     elseif(is_numeric($value)) {$value = (int) ($value);}
 1184     elseif(is_int($value)) {$value = (int) ($value);}
 1185     elseif(!is_numeric($value))
 1186     {
 1187         $value = icms::$xoopsDB->escape($value);
 1188         if($quotes) {$value = '"'.$value.'"';}
 1189     }
 1190     return $value;
 1191 }
 1192 
 1193 /**
 1194  * Get a number value in other languages
 1195  *
 1196  * @param int $string Content to be transported into another language
 1197  * @return string inout with replaced numeric values
 1198  *
 1199  * Example: In Persian we use, (۱, ۲, ۳, ۴, ۵, ۶, ۷, ۸, ۹, ۰) instead of (1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
 1200  * Now in a module and we are showing amount of reads, the output in Persian must be ۱۲ (which represents 12).
 1201  * To developers, please use this function when you are having a numeric output, as this is counted as a string in php so you should use %s.
 1202  * Like:
 1203  * $views = sprintf ( 'Viewed: %s Times.', icms_conv_nr2local($string) );
 1204  * @todo Move to a static class method - String or Localization
 1205  */
 1206 function icms_conv_nr2local($string)
 1207 {
 1208     $basecheck = defined('_USE_LOCAL_NUM') && _USE_LOCAL_NUM;
 1209     if ( $basecheck ){
 1210         $string = str_replace(
 1211         array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'),
 1212         array(_LCL_NUM0, _LCL_NUM1, _LCL_NUM2, _LCL_NUM3, _LCL_NUM4, _LCL_NUM5, _LCL_NUM6, _LCL_NUM7, _LCL_NUM8, _LCL_NUM9), $string);
 1213     }
 1214     return $string;
 1215 }
 1216 
 1217 /**
 1218  * Get a number value in other languages and transform it to English
 1219  *
 1220  * This function is exactly the opposite of icms_conv_nr2local();
 1221  * Please view the notes there for more information.
 1222  * @todo Move to a static class method - String or Localization
 1223  */
 1224 function icms_conv_local2nr($string)
 1225 {
 1226     $basecheck = defined('_USE_LOCAL_NUM') && _USE_LOCAL_NUM;
 1227     if ( $basecheck ){
 1228         $string = str_replace(
 1229         array(_LCL_NUM0, _LCL_NUM1, _LCL_NUM2, _LCL_NUM3, _LCL_NUM4, _LCL_NUM5, _LCL_NUM6, _LCL_NUM7, _LCL_NUM8, _LCL_NUM9),
 1230         array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'),
 1231         $string);
 1232     }
 1233     return $string;
 1234 }
 1235 
 1236 /**
 1237  * Get month name by its ID
 1238  *
 1239  * @param int $month_id ID of the month
 1240  * @return string month name
 1241  * @todo Move to a static class method - Date or Calendar
 1242  */
 1243 function Icms_getMonthNameById($month_id) {
 1244     global $icmsConfig;
 1245     icms_loadLanguageFile('core', 'calendar');
 1246     $month_id = icms_conv_local2nr($month_id);
 1247     if( $icmsConfig['use_ext_date'] == true && defined ('_CALENDAR_TYPE') && _CALENDAR_TYPE == "jalali"){
 1248         switch($month_id) {
 1249             case 1:
 1250                 return _CAL_FARVARDIN;
 1251                 break;
 1252             case 2:
 1253                 return _CAL_ORDIBEHESHT;
 1254                 break;
 1255             case 3:
 1256                 return _CAL_KHORDAD;
 1257                 break;
 1258             case 4:
 1259                 return _CAL_TIR;
 1260                 break;
 1261             case 5:
 1262                 return _CAL_MORDAD;
 1263                 break;
 1264             case 6:
 1265                 return _CAL_SHAHRIVAR;
 1266                 break;
 1267             case 7:
 1268                 return _CAL_MEHR;
 1269                 break;
 1270             case 8:
 1271                 return _CAL_ABAN;
 1272                 break;
 1273             case 9:
 1274                 return _CAL_AZAR;
 1275                 break;
 1276             case 10:
 1277                 return _CAL_DEY;
 1278                 break;
 1279             case 11:
 1280                 return _CAL_BAHMAN;
 1281                 break;
 1282             case 12:
 1283                 return _CAL_ESFAND;
 1284                 break;
 1285         }
 1286     }else{
 1287         switch($month_id) {
 1288             case 1:
 1289                 return _CAL_JANUARY;
 1290                 break;
 1291             case 2:
 1292                 return _CAL_FEBRUARY;
 1293                 break;
 1294             case 3:
 1295                 return _CAL_MARCH;
 1296                 break;
 1297             case 4:
 1298                 return _CAL_APRIL;
 1299                 break;
 1300             case 5:
 1301                 return _CAL_MAY;
 1302                 break;
 1303             case 6:
 1304                 return _CAL_JUNE;
 1305                 break;
 1306             case 7:
 1307                 return _CAL_JULY;
 1308                 break;
 1309             case 8:
 1310                 return _CAL_AUGUST;
 1311                 break;
 1312             case 9:
 1313                 return _CAL_SEPTEMBER;
 1314                 break;
 1315             case 10:
 1316                 return _CAL_OCTOBER;
 1317                 break;
 1318             case 11:
 1319                 return _CAL_NOVEMBER;
 1320                 break;
 1321             case 12:
 1322                 return _CAL_DECEMBER;
 1323                 break;
 1324         }
 1325     }
 1326 }
 1327 
 1328 /**
 1329  * This function is to convert date() function outputs into local values
 1330  *
 1331  * @copyright   http://www.impresscms.org/ The ImpressCMS Project
 1332  * @since       1.2
 1333  * @author     Sina Asghari (aka stranger) <pesian_stranger@users.sourceforge.net>
 1334  * @param int $type The type of date string?
 1335  * @param string $maket The date string type
 1336  * @return mixed The converted date string
 1337  * @todo Move to a static class method - Date or Calendar
 1338  */
 1339 function ext_date($time)
 1340 {
 1341     icms_loadLanguageFile('core', 'calendar');
 1342     /*      $string = str_replace(
 1343         array(_CAL_AM, _CAL_PM, _CAL_AM_LONG, _CAL_PM_LONG, _CAL_SAT, _CAL_SUN, _CAL_MON, _CAL_TUE, _CAL_WED, _CAL_THU, _CAL_FRI, _CAL_SATURDAY, _CAL_SUNDAY, _CAL_MONDAY, _CAL_TUESDAY, _CAL_WEDNESDAY, _CAL_THURSDAY, _CAL_FRIDAY),
 1344         array('Am', 'Pm', 'AM', 'PM', 'Sat', 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'),
 1345         $string);
 1346         */
 1347     $trans = array( 'am'    => _CAL_AM,
 1348                     'pm'    => _CAL_PM,
 1349                     'AM'    => _CAL_AM_CAPS,
 1350                     'PM'    => _CAL_PM_CAPS,
 1351                     'Monday'    => _CAL_MONDAY,
 1352                     'Tuesday'   => _CAL_TUESDAY,
 1353                     'Wednesday' => _CAL_WEDNESDAY,
 1354                     'Thursday'  => _CAL_THURSDAY,
 1355                     'Friday'    => _CAL_FRIDAY,
 1356                     'Saturday'  => _CAL_SATURDAY,
 1357                     'Sunday'    => _CAL_SUNDAY,
 1358                     'Mon'       => _CAL_MON,
 1359                     'Tue'      => _CAL_TUE,
 1360                     'Wed'        => _CAL_WED,
 1361                     'Thu'         => _CAL_THU,
 1362                     'Fri'       => _CAL_FRI,
 1363                     'Sat'         => _CAL_SAT,
 1364                     'Sun'       => _CAL_SUN,
 1365                     'January'   => _CAL_JANUARY,
 1366                     'February'  => _CAL_FEBRUARY,
 1367                     'March'     => _CAL_MARCH,
 1368                     'April'     => _CAL_APRIL,
 1369                     'May'       => _CAL_MAY,
 1370                     'June'      => _CAL_JUNE,
 1371                     'July'      => _CAL_JULY,
 1372                     'August'    => _CAL_AUGUST,
 1373                     'September' => _CAL_SEPTEMBER,
 1374                     'October'   => _CAL_OCTOBER,
 1375                     'November'  => _CAL_NOVEMBER,
 1376                     'December'  => _CAL_DECEMBER,
 1377                     'Jan'       => _CAL_JAN,
 1378                     'Feb'       => _CAL_FEB,
 1379                     'Mar'       => _CAL_MAR,
 1380                     'Apr'       => _CAL_APR,
 1381                     'May'       => _CAL_MAY,
 1382                     'Jun'       => _CAL_JUN,
 1383                     'Jul'       => _CAL_JUL,
 1384                     'Aug'       => _CAL_AUG,
 1385                     'Sep'        => _CAL_SEP,
 1386                     'Oct'       => _CAL_OCT,
 1387                     'Nov'       => _CAL_NOV,
 1388                     'Dec'       => _CAL_DEC );
 1389 
 1390     $timestamp = strtr( $time, $trans );
 1391     return $timestamp;
 1392 }
 1393 
 1394 /**
 1395  * Function to display formatted times in user timezone
 1396  *
 1397  * @param string  $time  String with time
 1398  * @param string  $format  The time format based on PHP function format parameters
 1399  * @param string  $timeoffset  The time offset string
 1400  * @return string  $usertimestamp  The generated user timestamp
 1401  * @todo Move to a static class method - Date or Calendar
 1402  */
 1403 function formatTimestamp($time, $format = "l", $timeoffset = null)
 1404 {
 1405     global $icmsConfig;
 1406 
 1407     $format_copy = $format;
 1408     $format = strtolower($format);
 1409 
 1410     if ($format == "rss" || $format == "r"){
 1411         $TIME_ZONE = "";
 1412         if (!empty($GLOBALS['icmsConfig']['server_TZ'])){
 1413             $server_TZ = abs( (int) ($GLOBALS['icmsConfig']['server_TZ'] * 3600.0));
 1414             $prefix = ($GLOBALS['icmsConfig']['server_TZ'] < 0) ?  " -" : " +";
 1415             $TIME_ZONE = $prefix.date("Hi", $server_TZ);
 1416         }
 1417         $date = gmdate("D, d M Y H:i:s", (int) ($time)) . $TIME_ZONE;
 1418         return $date;
 1419     }
 1420 
 1421     if ( ($format == "elapse" || $format == "e") && $time < time() ) {
 1422         $elapse = time() - $time;
 1423         if ( $days = floor( $elapse / (24 * 3600) ) ) {
 1424             $num = $days > 1 ? sprintf(_DAYS, $days) : _DAY;
 1425         } elseif ( $hours = floor( ( $elapse % (24 * 3600) ) / 3600 ) ) {
 1426             $num = $hours > 1 ? sprintf(_HOURS, $hours) : _HOUR;
 1427         } elseif ( $minutes = floor( ( $elapse % 3600 ) / 60 ) ) {
 1428             $num = $minutes > 1 ? sprintf(_MINUTES, $minutes) : _MINUTE;
 1429         } else {
 1430             $seconds = $elapse % 60;
 1431             $num = $seconds > 1 ? sprintf(_SECONDS, $seconds) : _SECOND;
 1432         }
 1433         $ret = sprintf(_ELAPSE, icms_conv_nr2local($num));
 1434         return $ret;
 1435     }
 1436 
 1437     // disable user timezone calculation and use default timezone,
 1438     // for cache consideration
 1439     if ($timeoffset === null) {
 1440         $timeoffset = ($icmsConfig['default_TZ'] == '') ? '0.0' : $icmsConfig['default_TZ'];
 1441     }
 1442 
 1443     $usertimestamp = xoops_getUserTimestamp($time, $timeoffset);
 1444 
 1445     switch ($format) {
 1446         case 'daynumber':
 1447             $datestring = 'd';
 1448             break;
 1449         case 'D':
 1450             $datestring = 'D';
 1451             break;
 1452         case 'F':
 1453             $datestring = 'F';
 1454             break;
 1455         case 'hs':
 1456             $datestring = 'h';
 1457             break;
 1458         case 'H':
 1459             $datestring = 'H';
 1460             break;
 1461         case 'gg':
 1462             $datestring = 'g';
 1463             break;
 1464         case 'G':
 1465             $datestring = 'G';
 1466             break;
 1467         case 'i':
 1468             $datestring = 'i';
 1469             break;
 1470         case 'j':
 1471             $datestring = 'j';
 1472             break;
 1473         case 'l':
 1474             $datestring = _DATESTRING;
 1475             break;
 1476         case 'm':
 1477             $datestring = _MEDIUMDATESTRING;
 1478             break;
 1479         case 'monthnr':
 1480             $datestring = 'm';
 1481             break;
 1482         case 'mysql':
 1483             $datestring = 'Y-m-d H:i:s';
 1484             break;
 1485         case 'month':
 1486             $datestring = 'M';
 1487             break;
 1488         case 'n':
 1489             $datestring = 'n';
 1490             break;
 1491         case 's':
 1492             $datestring = _SHORTDATESTRING;
 1493             break;
 1494         case 'seconds':
 1495             $datestring = 's';
 1496             break;
 1497         case 'suffix':
 1498             $datestring = 'S';
 1499             break;
 1500         case 't':
 1501             $datestring = 't';
 1502             break;
 1503         case 'w':
 1504             $datestring = 'w';
 1505             break;
 1506         case 'shortyear':
 1507             $datestring = 'y';
 1508             break;
 1509         case 'Y':
 1510             $datestring = 'Y';
 1511             break;
 1512         case 'c':
 1513         case 'custom':
 1514             static $current_timestamp, $today_timestamp, $monthy_timestamp;
 1515             if (!isset($current_timestamp)) {
 1516                 $current_timestamp = xoops_getUserTimestamp(time(), $timeoffset);
 1517             }
 1518             if (!isset($today_timestamp)) {
 1519                 $today_timestamp = mktime(0, 0, 0, date("m", $current_timestamp), date("d", $current_timestamp), date("Y", $current_timestamp));
 1520             }
 1521 
 1522             if ( abs($elapse_today = $usertimestamp - $today_timestamp) < 24*60*60) {
 1523                 $datestring = ($elapse_today > 0) ? _TODAY : _YESTERDAY;
 1524             } else {
 1525                 if (!isset($monthy_timestamp)) {
 1526                     $monthy_timestamp[0] = mktime(0, 0, 0, 0, 0, date("Y", $current_timestamp));
 1527                     $monthy_timestamp[1] = mktime(0, 0, 0, 0, 0, date("Y", $current_timestamp) + 1);
 1528                 }
 1529                 if ($usertimestamp >= $monthy_timestamp[0] && $usertimestamp < $monthy_timestamp[1]) {
 1530                     $datestring = _MONTHDAY;
 1531                 } else{
 1532                     $datestring = _YEARMONTHDAY;
 1533                 }
 1534             }
 1535             break;
 1536 
 1537         default:
 1538             if ($format != '') {
 1539                 $datestring = $format_copy;
 1540             } else {
 1541                 $datestring = _DATESTRING;
 1542             }
 1543             break;
 1544     }
 1545 
 1546     $basecheck = $icmsConfig['use_ext_date'] == true && defined ('_CALENDAR_TYPE') && $format != 'mysql';
 1547     if($basecheck && file_exists(ICMS_ROOT_PATH.'/language/'.$icmsConfig['language'].'/local.date.php'))
 1548     {
 1549         include_once ICMS_ROOT_PATH.'/language/'.$icmsConfig['language'].'/local.date.php';
 1550         return ucfirst(local_date($datestring,$usertimestamp));
 1551     }elseif ($basecheck && _CALENDAR_TYPE != "jalali" && $icmsConfig['language'] != 'english'){
 1552         return ucfirst(icms_conv_nr2local(ext_date(date($datestring,$usertimestamp))));
 1553     }elseif ($basecheck && _CALENDAR_TYPE == "jalali"){
 1554         include_once 'jalali.php';
 1555         return ucfirst(icms_conv_nr2local(jdate($datestring,$usertimestamp)));
 1556     }else{
 1557         return ucfirst(date($datestring,$usertimestamp));
 1558     }
 1559 }
 1560 
 1561 /**
 1562  * Gets module handler instance
 1563  *
 1564  * @param string $name  The name of the module
 1565  * @param string $module_dir    The module directory where to get the module class
 1566  * @param string $module_basename   The basename of the module
 1567  * @param bool $optional    Is the module optional? Is it bad when the module cannot be loaded?
 1568  * @return object The module handler instance
 1569  */
 1570 function &icms_getModuleHandler($name = null, $module_dir = null, $module_basename = null, $optional = false) {
 1571     static $handlers;
 1572     // if $module_dir is not specified
 1573     if (!isset($module_dir)) {
 1574         //if a module is loaded
 1575         if (isset($GLOBALS['icmsModule']) && is_object($GLOBALS['icmsModule'])) {
 1576             $module_dir = $GLOBALS['icmsModule']->getVar('dirname');
 1577         } else {
 1578             trigger_error(_CORE_NOMODULE, E_USER_ERROR);
 1579         }
 1580     } else {
 1581         $module_dir = trim($module_dir);
 1582     }
 1583     $module_basename = isset($module_basename) ? trim($module_basename) : $module_dir;
 1584     $name = (!isset($name)) ? $module_dir : trim($name);
 1585     if (!isset($handlers[$module_dir][$name])) {
 1586         $class = 'mod_' . $module_dir . '_' . ucfirst($name) . 'Handler';
 1587         if (class_exists($class)) {
 1588             $handlers[$module_dir][$name] = new $class(icms::$xoopsDB);
 1589         } else {
 1590             if($module_dir != 'system') {
 1591                 $hnd_file = ICMS_ROOT_PATH . "/modules/{$module_dir}/class/{$name}.php";
 1592             } else {
 1593                 $hnd_file = ICMS_ROOT_PATH . "/modules/{$module_dir}/admin/{$name}/class/{$name}.php";
 1594             }
 1595             if (file_exists($hnd_file)) {include_once $hnd_file;}
 1596             $class = ucfirst(strtolower($module_basename)) . ucfirst($name) . 'Handler';
 1597             if (class_exists($class)) {
 1598                 $handlers[$module_dir][$name] = new $class(icms::$xoopsDB);
 1599             }
 1600         }
 1601     }
 1602     if (!isset($handlers[$module_dir][$name]) && !$optional) {
 1603         trigger_error(sprintf(_CORE_MODULEHANDLER_NOTAVAILABLE, $module_dir, $name), E_USER_ERROR);
 1604     }
 1605     if (isset($handlers[$module_dir][$name])) {return $handlers[$module_dir][$name];}
 1606     $inst = false;
 1607     return $inst;
 1608 }
 1609 
 1610 
 1611 /**
 1612  * Get module admin link
 1613  *
 1614  * @param string $moduleName dirname of the moodule
 1615  * @return string URL of the admin side of the module
 1616  * @todo Move to a static class method - HTTP or URI
 1617  */
 1618 function icms_getModuleAdminLink($moduleName=false) {
 1619     global $icmsModule;
 1620     if (!$moduleName && (isset ($icmsModule) && is_object($icmsModule))) {
 1621         $moduleName = $icmsModule->getVar('dirname');
 1622     }
 1623     $ret = '';
 1624     if ($moduleName) {
 1625         $ret = "<a href='" . ICMS_URL . "/modules/$moduleName/admin/index.php'>" . _CO_ICMS_ADMIN_PAGE . "</a>";
 1626     }
 1627     return $ret;
 1628 }
 1629 
 1630 /**
 1631  * Finds the width and height of an image (can also be a flash file)
 1632  *
 1633  * @credit phppp
 1634  *
 1635  * @var string $url path of the image file
 1636  * @var string $width reference to the width
 1637  * @var string $height reference to the height
 1638  * @return bool false if impossible to find dimension
 1639  * @todo Move to a static class method - Image
 1640  */
 1641 function icms_getImageSize($url, & $width, & $height) {
 1642     if (empty ($width) || empty ($height)) {
 1643         if (!$dimension = @ getimagesize($url)) {
 1644             return false;
 1645         }
 1646         if (!empty ($width)) {
 1647             $height = $dimension[1] * $width / $dimension[0];
 1648         }
 1649         elseif (!empty ($height)) {
 1650             $width = $dimension[0] * $height / $dimension[1];
 1651         } else {
 1652             list ($width, $height) = array (
 1653             $dimension[0],
 1654             $dimension[1]
 1655             );
 1656         }
 1657         return true;
 1658     } else {
 1659         return true;
 1660     }
 1661 }
 1662 
 1663 /**
 1664  * Resizes an image to maxheight and maxwidth
 1665  *
 1666  * @param string $src   The image file to resize
 1667  * @param string $maxWidth  The maximum width to resize the image to
 1668  * @param string $maxHeight The maximum height to resize the image to
 1669  * @return array The resized image array
 1670  * @todo Move to a static class method - Image
 1671  */
 1672 function icms_imageResize($src, $maxWidth, $maxHeight) {
 1673     $width = '';
 1674     $height = '';
 1675     $type = '';
 1676     $attr = '';
 1677     if (file_exists($src)) {
 1678         list ($width, $height, $type, $attr) = getimagesize($src);
 1679         if ($width > $maxWidth) {
 1680             $originalWidth = $width;
 1681             $width = $maxWidth;
 1682             $height = $width * $height / $originalWidth;
 1683         }
 1684         if ($height > $maxHeight) {
 1685             $originalHeight = $height;
 1686             $height = $maxHeight;
 1687             $width = $height * $width / $originalHeight;
 1688         }
 1689         $attr = " width='$width' height='$height'";
 1690     }
 1691     return array (
 1692     $width,
 1693     $height,
 1694     $type,
 1695     $attr
 1696     );
 1697 }
 1698 
 1699 /**
 1700  * Generates the module name with either a link or not
 1701  *
 1702  * @param bool $withLink    Generate the modulename with in an anchor link?
 1703  * @param bool $forBreadCrumb   Is the module name for the breadcrumbs?
 1704  * @param mixed $moduleName The passed modulename or false if no modulename was passed
 1705  * @return array
 1706  * @todo Move to a static class method - Module
 1707  */
 1708 function icms_getModuleName($withLink = true, $forBreadCrumb = false, $moduleName = false) {
 1709     if (!$moduleName) {
 1710         global $icmsModule;
 1711         $moduleName = $icmsModule->getVar('dirname');
 1712     }
 1713     $icmsModule = icms_getModuleInfo($moduleName);
 1714     $icmsModuleConfig = icms_getModuleConfig($moduleName);
 1715     if (!isset ($icmsModule)) {
 1716         return '';
 1717     }
 1718 
 1719     if (!$withLink) {
 1720         return $icmsModule->getVar('name');
 1721     } else {
 1722         $seoMode = icms_getModuleModeSEO($moduleName);
 1723         if ($seoMode == 'rewrite') {
 1724             $seoModuleName = icms_getModuleNameForSEO($moduleName);
 1725             $ret = ICMS_URL . '/' . $seoModuleName . '/';
 1726         } elseif ($seoMode == 'pathinfo') {
 1727             $ret = ICMS_URL . '/modules/' . $moduleName . '/seo.php/' . $seoModuleName . '/';
 1728         } else {
 1729             $ret = ICMS_URL . '/modules/' . $moduleName . '/';
 1730         }
 1731         return '<a href="' . $ret . '">' . $icmsModule->getVar('name') . '</a>';
 1732     }
 1733 }
 1734 
 1735 /**
 1736  * Converts size to human readable text
 1737  *
 1738  * @param int $size The size to convert
 1739  * @return string The converted size
 1740  * @todo Move to a static class method - String
 1741  */
 1742 function icms_convert_size($size){
 1743     if ($size >= 1073741824){
 1744         $ret = round(((($size/1024)/1024)/1024),1).' '._CORE_GIGABYTES_SHORTEN;
 1745     }elseif($size >= 1048576 && $size < 1073741824){
 1746         $ret = round((($size/1024)/1024),1).' '._CORE_MEGABYTES_SHORTEN;
 1747     }elseif($size >= 1024 && $size < 1048576){
 1748         $ret = round(($size/1024),1).' '._CORE_KILOBYTES_SHORTEN;
 1749     }else{
 1750         $ret = ($size).' '._CORE_BYTES;
 1751     }
 1752     return icms_conv_nr2local($ret);
 1753 }
 1754 
 1755 /**
 1756  * Generates a random string
 1757  *
 1758  * @param int $numchar  How many characters should the string consist of?
 1759  * @return string The generated random string
 1760  * @todo Move to a static class method -
 1761  */
 1762 function icms_random_str($numchar){
 1763     $letras = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,x,w,y,z,1,2,3,4,5,6,7,8,9,0";
 1764     $array = explode(",", $letras);
 1765     shuffle($array);
 1766     $senha = implode($array, "");
 1767     return substr($senha, 0, $numchar);
 1768 }
 1769 
 1770 /**
 1771  * Generates a random string
 1772  *
 1773  * @param int $currentoption    What current admin option are we in?
 1774  * @param string $breadcrumb    The breadcrumb if it is passed, otherwise empty string
 1775  * @todo Move to a static class method - module
 1776  */
 1777 function icms_adminMenu($currentoption = 0, $breadcrumb = '') {
 1778     global $icmsModule;
 1779     $icmsModule->displayAdminMenu( $currentoption, $icmsModule -> name() . ' | ' . $breadcrumb );
 1780 }
 1781 
 1782 /**
 1783  * Loads common language file
 1784  */
 1785 function icms_loadCommonLanguageFile() {
 1786     icms_loadLanguageFile('system', 'common');
 1787 }
 1788 
 1789 /**
 1790  * Gets module name in SEO format
 1791  *
 1792  * @param mixed $moduleName Modulename if it is passed, otherwise false
 1793  * @return string The modulename in SEO format
 1794  * @todo Move to a static class method - Module
 1795  */
 1796 function icms_getModuleNameForSEO($moduleName = false) {
 1797     $icmsModule = & icms_getModuleInfo($moduleName);
 1798     $icmsModuleConfig = & icms_getModuleConfig($moduleName);
 1799     if (isset ($icmsModuleConfig['seo_module_name'])) {
 1800         return $icmsModuleConfig['seo_module_name'];
 1801     }
 1802     $ret = icms_getModuleName(false, false, $moduleName);
 1803     return (strtolower($ret));
 1804 }
 1805 
 1806 /**
 1807  * Determines if the module is in SEO mode
 1808  *
 1809  * @param mixed $moduleName Modulename if it is passed, otherwise false
 1810  * @return bool Is the module in SEO format?
 1811  * @todo Move to a static class method - Module
 1812  */
 1813 function icms_getModuleModeSEO($moduleName = false) {
 1814     $icmsModule = & icms_getModuleInfo($moduleName);
 1815     $icmsModuleConfig = & icms_getModuleConfig($moduleName);
 1816     return isset ($icmsModuleConfig['seo_mode']) ? $icmsModuleConfig['seo_mode'] : false;
 1817 }
 1818 
 1819 /**
 1820  * Gets the include ID if the module is in SEO format (otherwise nothing)
 1821  *
 1822  * @param mixed $moduleName Modulename if it is passed, otherwise false
 1823  * @return mixed The module include ID otherwise nothing
 1824  * @todo Move to a static class method - Module
 1825  */
 1826 function icms_getModuleIncludeIdSEO($moduleName = false) {
 1827     $icmsModule = & icms_getModuleInfo($moduleName);
 1828     $icmsModuleConfig = & icms_getModuleConfig($moduleName);
 1829     return !empty ($icmsModuleConfig['seo_inc_id']);
 1830 }
 1831 
 1832 /**
 1833  * Gets environment key from the $_SERVER or $_ENV superglobal
 1834  *
 1835  * @param string  $key  The key to get
 1836  * @return string  $ret  The retrieved key
 1837  * @todo Move to a static class method - HTTP
 1838  */
 1839 function icms_getenv($key) {
 1840     $ret = '';
 1841     $ret = isset ($_SERVER[$key]) ? $_SERVER[$key] : (isset ($_ENV[$key]) ? $_ENV[$key] : '');
 1842     return $ret;
 1843 }
 1844 
 1845 /**
 1846  * Gets the status of a module to see if it's active or not.
 1847  *
 1848  * @param string $module_name  The module's name to get
 1849  * @param bool True if module exists and is active, otherwise false
 1850  * @todo Move to a static class method - Module
 1851  */
 1852 function icms_get_module_status($module_name){
 1853     $module_handler = icms::handler('icms_module');
 1854     $this_module = $module_handler->getByDirname($module_name);
 1855     if($this_module && $this_module->getVar('isactive')){
 1856         return true;
 1857     }
 1858     return false;
 1859 }
 1860 
 1861 /**
 1862  * Wrap a long term or word
 1863  *
 1864  * @author  <admin@jcink.com>
 1865  * @param   string  $string The string
 1866  * @param   string  $width    The length
 1867  * @return   bool   Returns a long term, in several small parts with the length of $width
 1868  * @todo Move to a static class method - String
 1869  */
 1870 function one_wordwrap($string,$width=false){
 1871     $width = $width ? $width : '15';
 1872     $new_string = '';
 1873     $s=explode(" ", $string);
 1874     foreach ($s as $k=>$v) {
 1875         $cnt=strlen($v);
 1876         if($cnt>$width) $v=icms_wordwrap($v, $width, ' ', true);
 1877         $new_string.="$v ";
 1878     }
 1879     return $new_string;
 1880 }
 1881 
 1882 /**
 1883  * Adds required jQuery files to header for Password meter.
 1884  *
 1885  * @param   string  $password_fieldclass    element id for the password field
 1886  * @param   string  $username_fieldid   element id for the username field
 1887  * @todo Move to a static class method - Password
 1888  */
 1889 function icms_PasswordMeter($password_fieldclass = "password_adv", $username_fieldid = "uname"){
 1890     global $xoTheme, $icmsConfigUser;
 1891     $xoTheme->addScript(ICMS_URL.'/libraries/jquery/jquery.js', array('type' => 'text/javascript'));
 1892     $xoTheme->addScript(ICMS_URL.'/libraries/jquery/password_strength_plugin.js', array('type' => 'text/javascript'));
 1893     $xoTheme->addScript('', array('type' => 'text/javascript'), '
 1894                 $(document).ready( function() {
 1895                     $.fn.shortPass = "' . _CORE_PASSLEVEL1 . '";
 1896                     $.fn.badPass = "' . _CORE_PASSLEVEL2 . '";
 1897                     $.fn.goodPass = "' . _CORE_PASSLEVEL3 . '";
 1898                     $.fn.strongPass = "' . _CORE_PASSLEVEL4 . '";
 1899                     $.fn.samePassword = "' . _CORE_UNAMEPASS_IDENTIC . '";
 1900                     $.fn.resultStyle = "";
 1901                 $(".' . $password_fieldclass . '").passStrength({
 1902                     minPass: ' . $icmsConfigUser['minpass'] . ',
 1903                     strongnessPass: ' . $icmsConfigUser['pass_level'] . ',
 1904                     shortPass:      "top_shortPass",
 1905                     badPass:        "top_badPass",
 1906                     goodPass:       "top_goodPass",
 1907                     strongPass:     "top_strongPass",
 1908                     baseStyle:      "top_testresult",
 1909                     userid:         "#' . $username_fieldid . '",
 1910                     messageloc:     0
 1911                 });
 1912             });
 1913 ');
 1914 }
 1915 
 1916 /**
 1917  * Build criteria automatically from an array of key=>value
 1918  *
 1919  * @param array $criterias array of fieldname=>value criteria
 1920  * @return object (@link icms_db_criteria_Compo) the icms_db_criteria_Compo object
 1921  * @todo Move to a static class method - Criteria
 1922  */
 1923 function icms_buildCriteria($criterias) {
 1924     $criteria = new icms_db_criteria_Compo();
 1925     foreach($criterias as $k=>$v) {
 1926         $criteria->add(new icms_db_criteria_Item($k, $v));
 1927     }
 1928     return $criteria;
 1929 }
 1930 
 1931 /**
 1932  * Build a breadcrumb
 1933  *
 1934  * @param array $items of the breadcrumb to be displayed
 1935  * @return str HTML code of the breadcrumb to be inserted in another template
 1936  * @todo Move to a static class method - Breadcrumb
 1937  */
 1938 function icms_getBreadcrumb($items) {
 1939     $icmsBreadcrumb = new icms_view_Breadcrumb($items);
 1940     return $icmsBreadcrumb->render(TRUE);
 1941 }
 1942 /**
 1943  * Build a template assignement
 1944  *
 1945  * @param array $items to build the smarty to be used in templates
 1946  * @return smarty value for each item
 1947  * @todo Move to a static class method - Template
 1948  */
 1949 function icms_makeSmarty($items) {
 1950     global $icmsTpl;
 1951     if (!isset($icmsTpl) || !is_array($items))return false;
 1952     foreach ($items as $item => $value){
 1953         $icmsTpl->assign($item, $value);
 1954     }
 1955     return true;
 1956 }
 1957 
 1958 /**
 1959  * Is a module being installed, updated or uninstalled
 1960  * Used for setting module configuration default values or options
 1961  *
 1962  * The function should be in functions.admin.php, however it requires extra inclusion in xoops_version.php if so
 1963  *
 1964  * @param   string  $dirname    dirname of current module
 1965  * @return  bool
 1966  * @todo Move to a static class method - Module
 1967  */
 1968 function icms_moduleAction($dirname = 'system')
 1969 {
 1970     global $icmsModule;
 1971     $ret = @(
 1972     // action module 'system'
 1973     !empty($icmsModule) && 'system' == $icmsModule->getVar('dirname', 'n')
 1974     &&
 1975     // current dirname
 1976     ($dirname == $_POST['dirname'] || $dirname == $_POST['module'])
 1977     &&
 1978     // current op
 1979     ('update_ok' == $_POST['op'] || 'install_ok' == $_POST['op'] || 'uninstall_ok' == $_POST['op'])
 1980     &&
 1981     // current action
 1982         'modulesadmin' == $_POST['fct']
 1983     );
 1984     return $ret;
 1985 }
 1986 
 1987 /**
 1988  * Get localized string if it is defined
 1989  *
 1990  * @param   string  $name   string to be localized
 1991  */
 1992 if (!function_exists("mod_constant")) {
 1993     function mod_constant($name)
 1994     {
 1995         global $icmsModule;
 1996         if (!empty($GLOBALS["VAR_PREFIXU"]) && @defined($GLOBALS["VAR_PREFIXU"]."_".strtoupper($name))) {
 1997             return CONSTANT($GLOBALS["VAR_PREFIXU"]."_".strtoupper($name));
 1998         } elseif (!empty($icmsModule) && @defined(strtoupper($icmsModule->getVar("dirname", "n")."_".$name))) {
 1999             return CONSTANT(strtoupper($icmsModule->getVar("dirname", "n")."_".$name));
 2000         } elseif (defined(strtoupper($name))) {
 2001             return CONSTANT(strtoupper($name));
 2002         } else {
 2003             return str_replace("_", " ", strtolower($name));
 2004         }
 2005     }
 2006 }
 2007 /**
 2008  *
 2009  * Enter description here ...
 2010  * @param unknown_type $id
 2011  * @param unknown_type $title
 2012  * @param unknown_type $dsc
 2013  * @todo Move to a static class method
 2014  */
 2015 function icms_collapsableBar($id = '', $title = '', $dsc = '') {
 2016     global $icmsModule;
 2017     echo "<h3 style=\"color: #2F5376; font-weight: bold; font-size: 14px; margin: 6px 0 0 0; \"><a href='javascript:;' onclick=\"togglecollapse('" . $id . "'); toggleIcon('" . $id . "_icon')\";>";
 2018     echo "<img id='" . $id . "_icon' src=" . ICMS_URL . "/images/close12.gif alt='' /></a>&nbsp;" . $title . "</h3>";
 2019     echo "<div id='" . $id . "'>";
 2020     if ($dsc != '') {
 2021         echo "<span style=\"color: #567; margin: 3px 0 12px 0; font-size: small; display: block; \">" . $dsc . "</span>";
 2022     }
 2023 }
 2024 
 2025 /**
 2026  *
 2027  * Enter description here ...
 2028  * @param $id
 2029  * @param $title
 2030  * @param $dsc
 2031  * @todo Move to a static class method
 2032  */
 2033 function icms_ajaxCollapsableBar($id = '', $title = '', $dsc = '') {
 2034     global $icmsModule;
 2035     $onClick = "ajaxtogglecollapse('$id')";
 2036     //$onClick = "togglecollapse('$id'); toggleIcon('" . $id . "_icon')";
 2037     echo '<h3 style="border: 1px solid; color: #2F5376; font-weight: bold; font-size: 14px; margin: 6px 0 0 0; " onclick="' . $onClick . '">';
 2038     echo "<img id='" . $id . "_icon' src=" . ICMS_URL . "/images/close12.gif alt='' /></a>&nbsp;" . $title . "</h3>";
 2039     echo "<div id='" . $id . "'>";
 2040     if ($dsc != '') {
 2041         echo "<span style=\"color: #567; margin: 3px 0 12px 0; font-size: small; display: block; \">" . $dsc . "</span>";
 2042     }
 2043 }
 2044 
 2045 /**
 2046  *
 2047  * Enter description here ...
 2048  * @param unknown_type $name
 2049  * @todo Move to a static class method
 2050  */
 2051 function icms_openclose_collapsable($name) {
 2052     $path = icms::$urls['phpself'];
 2053     $cookie_name = $path . '_icms_collaps_' . $name;
 2054     $cookie_name = str_replace('.', '_', $cookie_name);
 2055     $cookie = icms_getCookieVar($cookie_name, '');
 2056     if ($cookie == 'none') {
 2057         echo '
 2058                 <script type="text/javascript"><!--
 2059                 togglecollapse("' . $name . '"); toggleIcon("' . $name . '_icon");
 2060                     //-->
 2061                 </script>
 2062                 ';
 2063     }
 2064     /*  if ($cookie == 'none') {
 2065      echo '
 2066      <script type="text/javascript"><!--
 2067      hideElement("' . $name . '");
 2068      //-->
 2069      </script>
 2070      ';
 2071         }
 2072         */
 2073 }
 2074 /**
 2075  * @todo Move to a static class method
 2076  * Enter description here ...
 2077  * @param unknown_type $name
 2078  */
 2079 function icms_close_collapsable($name) {
 2080     echo "</div>";
 2081     icms_openclose_collapsable($name);
 2082     echo "<br />";
 2083 }
 2084 
 2085 /**
 2086  * @todo Move to a static class method - user
 2087  * Enter description here ...
 2088  * @param $email
 2089  */
 2090 function icms_getUnameFromUserEmail($email = '')
 2091 {
 2092     $db = icms_db_Factory::instance();
 2093     if($email !== '')
 2094     {
 2095         $sql = $db->query("SELECT uname, email FROM ".$db->prefix('users')." WHERE email = '".@htmlspecialchars($email,
 2096         ENT_QUOTES, _CHARSET)."'");
 2097         list($uname, $email) = $db->fetchRow($sql);
 2098     }
 2099     else
 2100     {
 2101         redirect_header('user.php',2,_US_SORRYNOTFOUND);
 2102     }
 2103     return $uname;
 2104 }
 2105 
 2106 /**
 2107  * Check if the module currently uses WYSIWYG and decied wether to do_br or not
 2108  *
 2109  * @return bool true | false
 2110  * @todo Move to a static class method - text area?
 2111  */
 2112 function icms_need_do_br($moduleName=false) {
 2113     global $icmsConfig, $icmsModule;
 2114 
 2115     if (!$moduleName) {
 2116         global $icmsModule;
 2117         $theModule = $icmsModule;
 2118         $moduleName = $theModule->getVar('dirname');
 2119     } else {
 2120         $theModule = icms_getModuleInfo($moduleName);
 2121     }
 2122 
 2123     $groups = icms::$user->getGroups();
 2124 
 2125     $editor_default = $icmsConfig['editor_default'];
 2126     $gperm_handler = icms::handler('icms_member_groupperm');
 2127     if (file_exists(ICMS_EDITOR_PATH . "/" . $editor_default . "/xoops_version.php") && $gperm_handler->checkRight('use_wysiwygeditor', $theModule->getVar('mid'), $groups)) {
 2128         return false;
 2129     } else {
 2130         return true;
 2131     }
 2132 }