home *** CD-ROM | disk | FTP | other *** search
/ Cricao de Sites - 650 Layouts Prontos / WebMasters.iso / CMS / xoops-2.0.18.1.exe / xoops-2.0.18.1 / htdocs / include / functions.php < prev    next >
Encoding:
PHP Script  |  2008-01-29  |  26.8 KB  |  741 lines

  1. <?php
  2. // $Id: functions.php 1282 2008-01-29 04:26:44Z phppp $
  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. // ################## Various functions from here ################
  29.  
  30. function xoops_header($closehead=true)
  31. {
  32.     global $xoopsConfig, $xoopsTheme, $xoopsConfigMetaFooter;
  33.     $myts =& MyTextSanitizer::getInstance();
  34.  
  35.     if (!headers_sent()) {
  36.         header('Content-Type:text/html; charset='._CHARSET);
  37.         header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
  38.         header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  39.         header('Cache-Control: no-store, no-cache, max-age=1, s-maxage=1, must-revalidate, post-check=0, pre-check=0');
  40.         header("Pragma: no-cache");
  41.     }
  42.     echo "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>";
  43.     echo '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="'._LANGCODE.'" lang="'._LANGCODE.'">
  44.     <head>
  45.     <meta http-equiv="content-type" content="text/html; charset='._CHARSET.'" />
  46.     <meta http-equiv="content-language" content="'._LANGCODE.'" />
  47.     <meta name="robots" content="'.htmlspecialchars($xoopsConfigMetaFooter['meta_robots']).'" />
  48.     <meta name="keywords" content="'.htmlspecialchars($xoopsConfigMetaFooter['meta_keywords']).'" />
  49.     <meta name="description" content="'.htmlspecialchars($xoopsConfigMetaFooter['meta_desc']).'" />
  50.     <meta name="rating" content="'.htmlspecialchars($xoopsConfigMetaFooter['meta_rating']).'" />
  51.     <meta name="author" content="'.htmlspecialchars($xoopsConfigMetaFooter['meta_author']).'" />
  52.     <meta name="copyright" content="'.htmlspecialchars($xoopsConfigMetaFooter['meta_copyright']).'" />
  53.     <meta name="generator" content="XOOPS" />
  54.     <title>'.htmlspecialchars($xoopsConfig['sitename']).'</title>
  55.     <script type="text/javascript" src="'.XOOPS_URL.'/include/xoops.js"></script>
  56.     ';
  57.     $themecss = getcss($xoopsConfig['theme_set']);
  58.     echo '<link rel="stylesheet" type="text/css" media="all" href="'.XOOPS_URL.'/xoops.css" />';
  59.     if ($themecss) {
  60.         echo '<link rel="stylesheet" type="text/css" media="all" href="'.$themecss.'" />';
  61.         //echo '<style type="text/css" media="all"><!-- @import url('.$themecss.'); --></style>';
  62.     }
  63.     if ($closehead) {
  64.         echo '</head><body>';
  65.     }
  66. }
  67.  
  68. function xoops_footer()
  69. {
  70.     echo '</body></html>';
  71.     ob_end_flush();
  72. }
  73.  
  74. function xoops_error($msg, $title='')
  75. {
  76.     echo '
  77.     <div class="errorMsg">';
  78.     if ($title != '') {
  79.         echo '<h4>'.$title.'</h4>';
  80.     }
  81.     if (is_array($msg)) {
  82.         foreach ($msg as $m) {
  83.             echo $m.'<br />';
  84.         }
  85.     } else {
  86.         echo $msg;
  87.     }
  88.     echo '</div>';
  89. }
  90.  
  91. function xoops_result($msg, $title='')
  92. {
  93.     echo '
  94.     <div class="resultMsg">';
  95.     if ($title != '') {
  96.         echo '<h4>'.$title.'</h4>';
  97.     }
  98.     if (is_array($msg)) {
  99.         foreach ($msg as $m) {
  100.             echo $m.'<br />';
  101.         }
  102.     } else {
  103.         echo $msg;
  104.     }
  105.     echo '</div>';
  106. }
  107.  
  108. function xoops_confirm($hiddens, $action, $msg, $submit='', $addtoken = true)
  109. {
  110.     $submit = ($submit != '') ? trim($submit) : _SUBMIT;
  111.     echo '
  112.     <div class="confirmMsg">
  113.       <h4>'.$msg.'</h4>
  114.       <form method="post" action="'.$action.'">
  115.     ';
  116.     foreach ($hiddens as $name => $value) {
  117.         if (is_array($value)) {
  118.             foreach ($value as $caption => $newvalue) {
  119.                 echo '<input type="radio" name="'.$name.'" value="'.htmlspecialchars($newvalue).'" /> '.$caption;
  120.             }
  121.             echo '<br />';
  122.         } else {
  123.             echo '<input type="hidden" name="'.$name.'" value="'.htmlspecialchars($value).'" />';
  124.         }
  125.     }
  126.     if ($addtoken != false) {
  127.         echo $GLOBALS['xoopsSecurity']->getTokenHTML();
  128.     }
  129.     echo '
  130.         <input type="submit" name="confirm_submit" value="'.$submit.'" /> <input type="button" name="confirm_back" value="'._CANCEL.'" onclick="javascript:history.go(-1);" />
  131.       </form>
  132.     </div>
  133.     ';
  134. }
  135.  
  136. /**
  137. * Deprecated, use {@link XoopsSecurity} class instead
  138. **/
  139. function xoops_refcheck($docheck=1)
  140. {
  141.     return $GLOBALS['xoopsSecurity']->checkReferer($docheck);
  142. }
  143.  
  144. function xoops_getUserTimestamp($time, $timeoffset="")
  145. {
  146.     global $xoopsConfig, $xoopsUser;
  147.     if ($timeoffset == '') {
  148.         if ($xoopsUser) {
  149.             $timeoffset = $xoopsUser->getVar("timezone_offset");
  150.         } else {
  151.             $timeoffset = $xoopsConfig['default_TZ'];
  152.         }
  153.     }
  154.     $usertimestamp = intval($time) + (floatval($timeoffset) - $xoopsConfig['server_TZ'])*3600;
  155.     return $usertimestamp;
  156. }
  157.  
  158.  
  159.  
  160. /*
  161.  * Function to display formatted times in user timezone
  162.  */
  163. function formatTimestamp($time, $format="l", $timeoffset="")
  164. {
  165.     global $xoopsConfig, $xoopsUser;
  166.     $usertimestamp = xoops_getUserTimestamp($time, $timeoffset);
  167.     switch (strtolower($format)) {
  168.     case 's':
  169.         $datestring = _SHORTDATESTRING;
  170.         break;
  171.     case 'm':
  172.         $datestring = _MEDIUMDATESTRING;
  173.         break;
  174.     case 'mysql':
  175.         $datestring = "Y-m-d H:i:s";
  176.         break;
  177.     case 'rss':
  178.         $datestring = "r";
  179.         break;
  180.     case 'l':
  181.         $datestring = _DATESTRING;
  182.         break;
  183.     default:
  184.         if ($format != '') {
  185.             $datestring = $format;
  186.         } else {
  187.             $datestring = _DATESTRING;
  188.         }
  189.         break;
  190.     }
  191.     return ucfirst(date($datestring, $usertimestamp));
  192. }
  193.  
  194. /*
  195.  * Function to calculate server timestamp from user entered time (timestamp)
  196.  */
  197. function userTimeToServerTime($timestamp, $userTZ=null)
  198. {
  199.     global $xoopsConfig;
  200.     if (!isset($userTZ)) {
  201.         $userTZ = $xoopsConfig['default_TZ'];
  202.     }
  203.     $timestamp = $timestamp - (($userTZ - $xoopsConfig['server_TZ']) * 3600);
  204.     return $timestamp;
  205. }
  206.  
  207. function xoops_makepass() {
  208.     $makepass = '';
  209.     $syllables = array("er","in","tia","wol","fe","pre","vet","jo","nes","al","len","son","cha","ir","ler","bo","ok","tio","nar","sim","ple","bla","ten","toe","cho","co","lat","spe","ak","er","po","co","lor","pen","cil","li","ght","wh","at","the","he","ck","is","mam","bo","no","fi","ve","any","way","pol","iti","cs","ra","dio","sou","rce","sea","rch","pa","per","com","bo","sp","eak","st","fi","rst","gr","oup","boy","ea","gle","tr","ail","bi","ble","brb","pri","dee","kay","en","be","se");
  210.     srand((double)microtime()*1000000);
  211.     for ($count = 1; $count <= 4; $count++) {
  212.         if (rand()%10 == 1) {
  213.             $makepass .= sprintf("%0.0f",(rand()%50)+1);
  214.         } else {
  215.             $makepass .= sprintf("%s",$syllables[rand()%62]);
  216.         }
  217.     }
  218.     return $makepass;
  219. }
  220.  
  221. /*
  222.  * Functions to display dhtml loading image box
  223.  */
  224. function OpenWaitBox()
  225. {
  226.     echo "<div id='waitDiv' style='position:absolute;left:40%;top:50%;visibility:hidden;text-align: center;'>
  227.     <table cellpadding='6' border='2' class='bg2'>
  228.       <tr>
  229.         <td align='center'><b><big>" ._FETCHING."</big></b><br /><img src='".XOOPS_URL."/images/await.gif' alt='' /><br />" ._PLEASEWAIT."</td>
  230.       </tr>
  231.     </table>
  232.     </div>
  233.     <script type='text/javascript'>
  234.     <!--//
  235.     var DHTML = (document.getElementById || document.all || document.layers);
  236.     function ap_getObj(name) {
  237.         if (document.getElementById) {
  238.             return document.getElementById(name).style;
  239.         } else if (document.all) {
  240.             return document.all[name].style;
  241.         } else if (document.layers) {
  242.             return document.layers[name];
  243.         }
  244.     }
  245.     function ap_showWaitMessage(div,flag)  {
  246.         if (!DHTML) {
  247.             return;
  248.         }
  249.         var x = ap_getObj(div);
  250.         x.visibility = (flag) ? 'visible' : 'hidden';
  251.         if (!document.getElementById) {
  252.             if (document.layers) {
  253.                 x.left=280/2;
  254.             }
  255.         }
  256.         return true;
  257.     }
  258.     ap_showWaitMessage('waitDiv', 1);
  259.     //-->
  260.     </script>";
  261. }
  262.  
  263. function CloseWaitBox()
  264. {
  265.     echo "<script type='text/javascript'>
  266.     <!--//
  267.     ap_showWaitMessage('waitDiv', 0);
  268.     //-->
  269.     </script>
  270.     ";
  271. }
  272.  
  273. function checkEmail($email,$antispam = false)
  274. {
  275.     if (!$email || !preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+([\.][a-z0-9-]+)+$/i",$email)){
  276.         return false;
  277.     }
  278.     if ($antispam) {
  279.         $email = str_replace("@", " at ", $email);
  280.         $email = str_replace(".", " dot ", $email);
  281.     }
  282.     return $email;
  283. }
  284.  
  285. function formatURL($url)
  286. {
  287.     $url = trim($url);
  288.     if ($url != '') {
  289.         if ((!preg_match("/^http[s]*:\/\//i", $url)) && (!preg_match("/^ftp*:\/\//i", $url)) && (!preg_match("/^ed2k*:\/\//i", $url)) ) {
  290.             $url = 'http://'.$url;
  291.         }
  292.     }
  293.     return $url;
  294. }
  295.  
  296. /*
  297.  * Function to display banners in all pages
  298.  */
  299. function showbanner()
  300. {
  301.     echo xoops_getbanner();
  302. }
  303.  
  304. /*
  305.  * Function to get banner html tags for use in templates
  306.  */
  307. function xoops_getbanner()
  308. {
  309.     global $xoopsConfig;
  310.     $db =& Database::getInstance();
  311.     $bresult = $db->query("SELECT COUNT(*) FROM ".$db->prefix("banner"));
  312.     list ($numrows) = $db->fetchRow($bresult);
  313.     if ( $numrows > 1 ) {
  314.         $numrows = $numrows-1;
  315.         mt_srand((double)microtime()*1000000);
  316.         $bannum = mt_rand(0, $numrows);
  317.     } else {
  318.         $bannum = 0;
  319.     }
  320.     if ( $numrows > 0 ) {
  321.         $bresult = $db->query("SELECT * FROM ".$db->prefix("banner"), 1, $bannum);
  322.         list ($bid, $cid, $imptotal, $impmade, $clicks, $imageurl, $clickurl, $date, $htmlbanner, $htmlcode) = $db->fetchRow($bresult);
  323.         if ($xoopsConfig['my_ip'] == xoops_getenv('REMOTE_ADDR')) {
  324.             // EMPTY
  325.         } else {
  326.             $db->queryF(sprintf("UPDATE %s SET impmade = impmade+1 WHERE bid = %u", $db->prefix("banner"), $bid));
  327.         }
  328.         /* Check if this impression is the last one and print the banner */
  329.         if ( $imptotal == $impmade ) {
  330.             $newid = $db->genId($db->prefix("bannerfinish")."_bid_seq");
  331.             $sql = sprintf("INSERT INTO %s (bid, cid, impressions, clicks, datestart, dateend) VALUES (%u, %u, %u, %u, %u, %u)", $db->prefix("bannerfinish"), $newid, $cid, $impmade, $clicks, $date, time());
  332.             $db->queryF($sql);
  333.             $db->queryF(sprintf("DELETE FROM %s WHERE bid = %u", $db->prefix("banner"), $bid));
  334.         }
  335.         if ($htmlbanner){
  336.             $bannerobject = $htmlcode;
  337.         }else{
  338.             $bannerobject = '<div><a href="'.XOOPS_URL.'/banners.php?op=click&bid='.$bid.'" target="_blank">';
  339.             if (stristr($imageurl, '.swf')) {
  340.                 $bannerobject = $bannerobject
  341.                     .'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" width="468" height="60">'
  342.                     .'<param name="movie" value="'.$imageurl.'"></param>'
  343.                     .'<param name="quality" value="high"></param>'
  344.                     .'<embed src="'.$imageurl.'" quality="high" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="468" height="60">'
  345.                     .'</embed>'
  346.                     .'</object>';
  347.             } else {
  348.                 $bannerobject = $bannerobject.'<img src="'.$imageurl.'" alt="" />';
  349.             }
  350.  
  351.             $bannerobject = $bannerobject.'</a></div>';
  352.         }
  353.         return $bannerobject;
  354.     }
  355. }
  356.  
  357. /*
  358. * Function to redirect a user to certain pages
  359. */
  360. function redirect_header($url, $time = 3, $message = '', $addredirect = true, $allowExternalLink = false)
  361. {
  362.     global $xoopsConfig, $xoopsLogger, $xoopsUserIsAdmin;
  363.     if ( preg_match( "/[\\0-\\31]|about:|script:/i", $url) ) {
  364.         if (!preg_match('/^\b(java)?script:([\s]*)history\.go\(-[0-9]*\)([\s]*[;]*[\s]*)$/si', $url) ) {
  365.             $url = XOOPS_URL;
  366.         }
  367.     }
  368.     if ( !$allowExternalLink && $pos = strpos( $url, '://' ) ) {
  369.         $xoopsLocation = substr( XOOPS_URL, strpos( XOOPS_URL, '://' ) + 3 );
  370.         if (strcasecmp(substr($url, $pos + 3, strlen($xoopsLocation)), $xoopsLocation)) {
  371.             $url = XOOPS_URL;
  372.         }
  373.     }
  374.     if (defined('XOOPS_CPFUNC_LOADED')) {
  375.         $theme = 'default';
  376.     } else {
  377.         $theme = $xoopsConfig['theme_set'];
  378.     }
  379.  
  380.     require_once XOOPS_ROOT_PATH . '/class/template.php';
  381.     require_once XOOPS_ROOT_PATH . '/class/theme.php';
  382.  
  383.     $xoopsThemeFactory =& new xos_opal_ThemeFactory();
  384.     $xoopsThemeFactory->allowedThemes = $xoopsConfig['theme_set_allowed'];
  385.     $xoopsThemeFactory->defaultTheme = $theme;
  386.     $xoTheme =& $xoopsThemeFactory->createInstance(array("plugins" => array()));
  387.     $xoopsTpl =& $xoTheme->template;
  388.  
  389.     $xoopsTpl->assign( array(
  390.         'xoops_theme' => $theme,
  391.         'xoops_imageurl' => XOOPS_THEME_URL.'/'.$theme.'/',
  392.         'xoops_themecss'=> xoops_getcss($theme),
  393.         'xoops_requesturi' => htmlspecialchars( $_SERVER['REQUEST_URI'], ENT_QUOTES),
  394.         'xoops_sitename' => htmlspecialchars($xoopsConfig['sitename'], ENT_QUOTES),
  395.         'xoops_slogan' => htmlspecialchars($xoopsConfig['slogan'], ENT_QUOTES),
  396.         'xoops_dirname' => isset($xoopsModule) ? $xoopsModule->getVar( 'dirname' ) : 'system',
  397.         'xoops_banner' => $xoopsConfig['banners'] ? xoops_getbanner() : ' ',
  398.         'xoops_pagetitle' => isset($xoopsModule) && is_object($xoopsModule) ? $xoopsModule->getVar('name') : htmlspecialchars( $xoopsConfig['slogan'], ENT_QUOTES ),
  399.     ) );
  400.  
  401.     if ($xoopsConfig['debug_mode'] == 2 && $xoopsUserIsAdmin) {
  402.         $xoopsTpl->assign('time', 300);
  403.         $xoopsTpl->assign('xoops_logdump', $xoopsLogger->dump());
  404.     } else {
  405.         $xoopsTpl->assign('time', intval($time));
  406.     }
  407.     if (!empty($_SERVER['REQUEST_URI']) && $addredirect && strstr($url, 'user.php')) {
  408.         if (!strstr($url, '?')) {
  409.             $url .= '?xoops_redirect='.urlencode($_SERVER['REQUEST_URI']);
  410.         } else {
  411.             $url .= '&xoops_redirect='.urlencode($_SERVER['REQUEST_URI']);
  412.         }
  413.     }
  414.     if (defined('SID') && SID && (! isset($_COOKIE[session_name()]) || ($xoopsConfig['use_mysession'] && $xoopsConfig['session_name'] != '' && !isset($_COOKIE[$xoopsConfig['session_name']])))) {
  415.         if (!strstr($url, '?')) {
  416.             $url .= '?' . SID;
  417.         } else {
  418.             $url .= '&'.SID;
  419.         }
  420.     }
  421.     $url = preg_replace("/&/i", '&', htmlspecialchars($url, ENT_QUOTES));
  422.     $xoopsTpl->assign('url', $url);
  423.     $message = trim($message) != '' ? $message : _TAKINGBACK;
  424.     $xoopsTpl->assign('message', $message);
  425.     $xoopsTpl->assign('lang_ifnotreload', sprintf(_IFNOTRELOAD, $url));
  426.     $xoopsTpl->display('db:system_redirect.html');
  427.     exit();
  428. }
  429.  
  430. function xoops_getenv($key)
  431. {
  432.     $ret = '';
  433.     if ( array_key_exists( $key, $_SERVER) && isset($_SERVER[$key]) ) {
  434.         $ret = $_SERVER[$key];
  435.         return $ret;
  436.     }
  437.     if ( array_key_exists( $key, $_ENV) && isset($_ENV[$key]) ) {
  438.         $ret = $_ENV[$key];
  439.         return $ret;
  440.     }
  441.     return $ret;
  442. }
  443.  
  444. /*
  445.  * This function is deprecated. Do not use!
  446.  */
  447. function getTheme()
  448. {
  449.     return $GLOBALS['xoopsConfig']['theme_set'];
  450. }
  451.  
  452. /*
  453.  * Function to get css file for a certain theme
  454.  * This function will be deprecated.
  455.  */
  456. function getcss($theme = '')
  457. {
  458.     return xoops_getcss($theme);
  459. }
  460.  
  461. /*
  462.  * Function to get css file for a certain themeset
  463.  */
  464. function xoops_getcss($theme = '')
  465. {
  466.     if ($theme == '') {
  467.         $theme = $GLOBALS['xoopsConfig']['theme_set'];
  468.     }
  469.     $uagent = xoops_getenv('HTTP_USER_AGENT');
  470.     if (stristr($uagent, 'mac')) {
  471.         $str_css = 'styleMAC.css';
  472.     } elseif (preg_match("/MSIE ([0-9]\.[0-9]{1,2})/i", $uagent)) {
  473.         $str_css = 'style.css';
  474.     } else {
  475.         $str_css = 'styleNN.css';
  476.     }
  477.     if (is_dir(XOOPS_THEME_PATH.'/'.$theme)) {
  478.         if (file_exists(XOOPS_THEME_PATH.'/'.$theme.'/'.$str_css)) {
  479.             return XOOPS_THEME_URL.'/'.$theme.'/'.$str_css;
  480.         } elseif (file_exists(XOOPS_THEME_PATH.'/'.$theme.'/style.css')) {
  481.             return XOOPS_THEME_URL.'/'.$theme.'/style.css';
  482.         }
  483.     }
  484.     if (is_dir(XOOPS_THEME_PATH.'/'.$theme . '/css')) {
  485.         if (file_exists(XOOPS_THEME_PATH.'/'.$theme.'/css/'.$str_css)) {
  486.             return XOOPS_THEME_URL.'/'.$theme.'/css/'.$str_css;
  487.         } elseif (file_exists(XOOPS_THEME_PATH.'/'.$theme.'/css/style.css')) {
  488.             return XOOPS_THEME_URL.'/'.$theme.'/css/style.css';
  489.         }
  490.     }
  491.     return '';
  492. }
  493.  
  494. function &getMailer()
  495. {
  496.     global $xoopsConfig;
  497.     $inst = false;
  498.     include_once XOOPS_ROOT_PATH."/class/xoopsmailer.php";
  499.     if ( file_exists(XOOPS_ROOT_PATH."/language/".$xoopsConfig['language']."/xoopsmailerlocal.php") ) {
  500.         include_once XOOPS_ROOT_PATH."/language/".$xoopsConfig['language']."/xoopsmailerlocal.php";
  501.         if ( class_exists("XoopsMailerLocal") ) {
  502.             $inst =& new XoopsMailerLocal();
  503.         }
  504.     }
  505.     if ( !$inst ) {
  506.         $inst =& new XoopsMailer();
  507.     }
  508.     return $inst;
  509. }
  510.  
  511. function &xoops_gethandler($name, $optional = false )
  512. {
  513.     static $handlers;
  514.     $name = strtolower(trim($name));
  515.     if (!isset($handlers[$name])) {
  516.         if ( file_exists( $hnd_file = XOOPS_ROOT_PATH.'/kernel/'.$name.'.php' ) ) {
  517.             require_once $hnd_file;
  518.         }
  519.         $class = 'Xoops'.ucfirst($name).'Handler';
  520.         if (class_exists($class)) {
  521.             $handlers[$name] =& new $class($GLOBALS['xoopsDB']);
  522.         }
  523.     }
  524.     if (!isset($handlers[$name]) && !$optional ) {
  525.         trigger_error('Class <b>'.$class.'</b> does not exist<br />Handler Name: '.$name, E_USER_ERROR);
  526.     }
  527.     if ( isset($handlers[$name]) ) {
  528.         return $handlers[$name];
  529.     }
  530.     $inst = false;
  531.     return $inst;
  532. }
  533.  
  534. function &xoops_getmodulehandler($name = null, $module_dir = null, $optional = false)
  535. {
  536.     static $handlers;
  537.     // if $module_dir is not specified
  538.     if (!isset($module_dir)) {
  539.         //if a module is loaded
  540.         if (isset($GLOBALS['xoopsModule']) && is_object($GLOBALS['xoopsModule'])) {
  541.             $module_dir = $GLOBALS['xoopsModule']->getVar('dirname');
  542.         } else {
  543.             trigger_error('No Module is loaded', E_USER_ERROR);
  544.         }
  545.     } else {
  546.         $module_dir = trim($module_dir);
  547.     }
  548.     $name = (!isset($name)) ? $module_dir : trim($name);
  549.     if (!isset($handlers[$module_dir][$name])) {
  550.         if ( file_exists( $hnd_file = XOOPS_ROOT_PATH . "/modules/{$module_dir}/class/{$name}.php" ) ) {
  551.             include_once $hnd_file;
  552.         }
  553.         $class = ucfirst(strtolower($module_dir)).ucfirst($name).'Handler';
  554.         if (class_exists($class)) {
  555.             $handlers[$module_dir][$name] =& new $class($GLOBALS['xoopsDB']);
  556.         }
  557.     }
  558.     if (!isset($handlers[$module_dir][$name]) && !$optional) {
  559.         trigger_error('Handler does not exist<br />Module: '.$module_dir.'<br />Name: '.$name, E_USER_ERROR);
  560.     }
  561.     if ( isset($handlers[$module_dir][$name]) ) {
  562.         return $handlers[$module_dir][$name];
  563.     }
  564.     $inst = false;
  565.     return $inst;
  566.  
  567. }
  568.  
  569. function xoops_getrank($rank_id =0, $posts = 0)
  570. {
  571.     $db =& Database::getInstance();
  572.     $myts =& MyTextSanitizer::getInstance();
  573.     $rank_id = intval($rank_id);
  574.     $posts = intval($posts);
  575.     if ($rank_id != 0) {
  576.         $sql = "SELECT rank_title AS title, rank_image AS image FROM ".$db->prefix('ranks')." WHERE rank_id = ".$rank_id;
  577.     } else {
  578.         $sql = "SELECT rank_title AS title, rank_image AS image FROM ".$db->prefix('ranks')." WHERE rank_min <= ".$posts." AND rank_max >= ".$posts." AND rank_special = 0";
  579.     }
  580.     $rank = $db->fetchArray($db->query($sql));
  581.     $rank['title'] = $myts->makeTboxData4Show($rank['title']);
  582.     $rank['id'] = $rank_id;
  583.     return $rank;
  584. }
  585.  
  586.  
  587. /**
  588. * Returns the portion of string specified by the start and length parameters. If $trimmarker is supplied, it is appended to the return string. This function works fine with multi-byte characters if mb_* functions exist on the server.
  589. *
  590. * @param    string    $str
  591. * @param    int       $start
  592. * @param    int       $length
  593. * @param    string    $trimmarker
  594. *
  595. * @return   string
  596. */
  597. function xoops_substr($str, $start, $length, $trimmarker = '...')
  598. {
  599.     if ( !XOOPS_USE_MULTIBYTES ) {
  600.         return ( strlen($str) - $start <= $length ) ? substr( $str, $start, $length ) : substr( $str, $start, $length - strlen($trimmarker) ) . $trimmarker;
  601.     }
  602.     if (function_exists('mb_internal_encoding') && @mb_internal_encoding(_CHARSET)) {
  603.         $str2 = mb_strcut( $str , $start , $length - strlen( $trimmarker ) );
  604.         return $str2 . ( mb_strlen($str)!=mb_strlen($str2) ? $trimmarker : '' );
  605.     }
  606.     // phppp patch
  607.     $DEP_CHAR=127;
  608.     $pos_st=0;
  609.     $action = false;
  610.     for ( $pos_i = 0; $pos_i < strlen($str); $pos_i++ ) {
  611.         if ( ord( substr( $str, $pos_i, 1) ) > 127 ) {
  612.             $pos_i++;
  613.         }
  614.         if ($pos_i<=$start) {
  615.             $pos_st=$pos_i;
  616.         }
  617.         if ($pos_i>=$pos_st+$length) {
  618.             $action = true;
  619.             break;
  620.         }
  621.     }
  622.     return ($action) ? substr( $str, $pos_st, $pos_i - $pos_st - strlen($trimmarker) ) . $trimmarker : $str;
  623. }
  624.  
  625. // RMV-NOTIFY
  626. // ################ Notification Helper Functions ##################
  627.  
  628. // We want to be able to delete by module, by user, or by item.
  629. // How do we specify this??
  630.  
  631. function xoops_notification_deletebymodule ($module_id)
  632. {
  633.     $notification_handler =& xoops_gethandler('notification');
  634.     return $notification_handler->unsubscribeByModule ($module_id);
  635. }
  636.  
  637. function xoops_notification_deletebyuser ($user_id)
  638. {
  639.     $notification_handler =& xoops_gethandler('notification');
  640.     return $notification_handler->unsubscribeByUser ($user_id);
  641. }
  642.  
  643. function xoops_notification_deletebyitem ($module_id, $category, $item_id)
  644. {
  645.     $notification_handler =& xoops_gethandler('notification');
  646.     return $notification_handler->unsubscribeByItem ($module_id, $category, $item_id);
  647. }
  648.  
  649. // ################### Comment helper functions ####################
  650.  
  651. function xoops_comment_count($module_id, $item_id = null)
  652. {
  653.     $comment_handler =& xoops_gethandler('comment');
  654.     $criteria = new CriteriaCompo(new Criteria('com_modid', intval($module_id)));
  655.     if (isset($item_id)) {
  656.         $criteria->add(new Criteria('com_itemid', intval($item_id)));
  657.     }
  658.     return $comment_handler->getCount($criteria);
  659. }
  660.  
  661. function xoops_comment_delete($module_id, $item_id)
  662. {
  663.     if (intval($module_id) > 0 && intval($item_id) > 0) {
  664.         $comment_handler =& xoops_gethandler('comment');
  665.         $comments =& $comment_handler->getByItemId($module_id, $item_id);
  666.         if (is_array($comments)) {
  667.             $count = count($comments);
  668.             $deleted_num = array();
  669.             for ($i = 0; $i < $count; $i++) {
  670.                 if (false != $comment_handler->delete($comments[$i])) {
  671.                     // store poster ID and deleted post number into array for later use
  672.                     $poster_id = $comments[$i]->getVar('com_uid');
  673.                     if ($poster_id != 0) {
  674.                         $deleted_num[$poster_id] = !isset($deleted_num[$poster_id]) ? 1 : ($deleted_num[$poster_id] + 1);
  675.                     }
  676.                 }
  677.             }
  678.             $member_handler =& xoops_gethandler('member');
  679.             foreach ($deleted_num as $user_id => $post_num) {
  680.                 // update user posts
  681.                 $com_poster = $member_handler->getUser($user_id);
  682.                 if (is_object($com_poster)) {
  683.                     $member_handler->updateUserByField($com_poster, 'posts', $com_poster->getVar('posts') - $post_num);
  684.                 }
  685.             }
  686.             return true;
  687.         }
  688.     }
  689.     return false;
  690. }
  691.  
  692. // ################ Group Permission Helper Functions ##################
  693.  
  694. function xoops_groupperm_deletebymoditem($module_id, $perm_name, $item_id = null)
  695. {
  696.     // do not allow system permissions to be deleted
  697.     if (intval($module_id) <= 1) {
  698.         return false;
  699.     }
  700.     $gperm_handler =& xoops_gethandler('groupperm');
  701.     return $gperm_handler->deleteByModule($module_id, $perm_name, $item_id);
  702. }
  703.  
  704. function xoops_utf8_encode(&$text)
  705. {
  706.     if (XOOPS_USE_MULTIBYTES == 1) {
  707.         if (function_exists('mb_convert_encoding')) {
  708.             return mb_convert_encoding($text, 'UTF-8', 'auto');
  709.         }
  710.         return $text;
  711.     }
  712.     return utf8_encode($text);
  713. }
  714.  
  715. function xoops_convert_encoding(&$text)
  716. {
  717.     return xoops_utf8_encode($text);
  718. }
  719.  
  720. function xoops_getLinkedUnameFromId($userid)
  721. {
  722.     $userid = intval($userid);
  723.     if ($userid > 0) {
  724.         $member_handler =& xoops_gethandler('member');
  725.         $user =& $member_handler->getUser($userid);
  726.         if (is_object($user)) {
  727.             $linkeduser = '<a href="'.XOOPS_URL.'/userinfo.php?uid='.$userid.'">'. $user->getVar('uname').'</a>';
  728.             return $linkeduser;
  729.         }
  730.     }
  731.     return $GLOBALS['xoopsConfig']['anonymous'];
  732. }
  733.  
  734. function xoops_trim($text)
  735. {
  736.     if (function_exists('xoops_language_trim')) {
  737.         return xoops_language_trim($text);
  738.     }
  739.     return trim($text);
  740. }
  741. ?>