home *** CD-ROM | disk | FTP | other *** search
/ PCNet 2006 April / PCnet 2006-06.4.iso / shareware / nmsetup.exe / WebServer / web / _util.php < prev    next >
Encoding:
PHP Script  |  2006-05-01  |  19.8 KB  |  601 lines

  1. <?php
  2. ////////////////////////////////////////////////////////////////////////////////
  3. // <!--Copyright (c) 2005 Pure Networks Inc.  All rights reserved.-->
  4. ////////////////////////////////////////////////////////////////////////////////
  5. //
  6. // Build: 3.0.6121.0 (Stable)
  7. // $Revision: #3 $
  8. //
  9.  
  10. function goto($newLocation)
  11. {
  12.     // On Windows, the dirname($_SERVER['PHP_SELF'] can have a Windows style \ in the path.
  13.     // For cross platform compatibility and HTTP friendliness in Browsers that don't
  14.     // self correct this, we do a str_replace to change all instances of \ to /
  15.     $dirName = str_replace("\\", "/", dirname($_SERVER['PHP_SELF']));
  16.     header("location: http://" . $_SERVER['HTTP_HOST'] . $dirName . $newLocation);
  17.     exit();
  18. }
  19.  
  20. function gotoAbs($newLocation)
  21. {
  22.     // On Windows, the dirname($_SERVER['PHP_SELF'] can have a Windows style \ in the path.
  23.     // For cross platform compatibility and HTTP friendliness in Browsers that don't
  24.     // self correct this, we do a str_replace to change all instances of \ to /
  25.     header("location: http://" . $_SERVER['HTTP_HOST'] . $newLocation);
  26.     exit();
  27. }
  28.  
  29. function set_transfer_cookie()
  30. {
  31.     // We generally call this on pages that may need to be reached via session timeout
  32.     // or bookmarks.  We call it when we realize we have no session, and then check the
  33.     // cookie after login to ship them to the proper place.
  34.     $sURI = $_SERVER['REQUEST_URI'];
  35.     setcookie("transfer_url", $sURI,time()+(300),"/"); //give them 5 minutes to use the transfer url
  36. }
  37.  
  38. function clear_transfer_cookie()
  39. {
  40.     setcookie("transfer_url", "",0,"/");
  41. }
  42.  
  43. function logoff()
  44. {
  45.     log_activity("logout", "success", "");
  46.     setcookie("transfer_url", "", time() -3600,"/");
  47.     setcookie("browse_mode", "", time() -3600,"/");
  48.     
  49.     $_SESSION['user_is_logged_on'] = FALSE;
  50.     $_SESSION['session_id'] = "";
  51.  
  52.     // Unset all of the session variables.
  53.     $_SESSION = array();
  54.     
  55.     // Finally, destroy the session.
  56.     session_destroy();
  57. }
  58.  
  59.  
  60. // Call this function after initially logging onto the system
  61. function logon($nmRaManager)
  62. {
  63.     log_activity("logon", "success", "");
  64.     $_SESSION['user_is_logged_on'] = TRUE;
  65.     $_SESSION['time_last_used'] = time();
  66.  
  67.     // This is a useful debugging tool, not really used for anything
  68.     $_SESSION['time_last'] = date('c');
  69.     
  70.     // track a hash of the initial session's IP
  71.     $_SESSION['session_id'] = strtolower(md5(md5($_SERVER['REMOTE_ADDR'])));
  72.     
  73.     // set a cookie so we can bounce after browser close
  74.     setcookie("browse_mode", "active",0,"/"); // no time = expires at browser close
  75.     
  76.     $iCounter = $nmRaManager->SuccessfulLoginAttempts;
  77.     $nmRaManager->SuccessfulLoginAttempts = ($iCounter + 1);
  78. }
  79.  
  80. // Call this function every time the user hits a page (thus updating
  81. // session expire time).
  82. function logonUpdate()
  83. {
  84.     $_SESSION['time_last_used'] = time();
  85.  
  86.     // This is a useful debugging tool, not really used for anything
  87.     $_SESSION['time_last'] = date('c');
  88.     
  89.     // set a cookie so we can bounce after browser close
  90.     setcookie("browse_mode", "active",0,"/"); // no time = expires at browser close
  91. }
  92.  
  93. function is_user_logged_on()
  94. {
  95.     if (isset($_COOKIE['browse_mode']) and ($_COOKIE['browse_mode'] == "active"))
  96.     {
  97.         if (isset($_SESSION['user_is_logged_on']) and ($_SESSION['user_is_logged_on'] == TRUE))
  98.         {
  99.             // Also need to verify that the session hasn't expired
  100.             // We need the 'time_last_used', if that is not set then
  101.             // something is wrong, just bail
  102.             if (!isset($_SESSION['time_last_used']))
  103.             {
  104.                 logoff();
  105.                 return 0;
  106.             }
  107.             if (ini_get('session.cookie_lifetime') != 0)
  108.             {
  109.                 if ((time() - $_SESSION['time_last_used']) > ini_get('session.cookie_lifetime'))
  110.                 {
  111.                     // The user session has timed out, logoff
  112.                     logoff();
  113.                     return 0;
  114.                 }
  115.             }
  116.             // Update the session timestamp
  117.             logonUpdate();
  118.             return 1;
  119.         }
  120.         else
  121.         {
  122.             return 0;
  123.         }
  124.     }
  125.     else
  126.     {
  127.         return 0;
  128.     }
  129. }
  130.  
  131. function truncate_string($strString, $iCharsAllowed, $sEndChars, $sTruncSide, $bTruncateIE)
  132. {
  133.     // See if we're not in IE6, if we're not, we'll truncate
  134.     // If we're in IE6, we'll use the css text-overflow style to clip instead
  135.     if ((!stristr($_SERVER['HTTP_USER_AGENT'], "MSIE 6.0")) or $bTruncateIE)
  136.     {
  137.         // Truncate the passed string for non IE6 browsers (or IE as well if $bTruncateIE is true)
  138.         if (strlen($strString) > $iCharsAllowed)
  139.         {
  140.             if ($sTruncSide == "left")
  141.             {
  142.                 // reverse it so when we substr to the right, we're actually taking 
  143.                 // off the left side of the "real" string
  144.                 $strString = strrev($strString);
  145.             }
  146.             $strString = substr($strString, 0, $iCharsAllowed);
  147.             $strString .=$sEndChars;
  148.             if ($sTruncSide == "left")
  149.             {
  150.                 // reverse it back again so that the "real" string reads properly
  151.                 $strString = strrev($strString);
  152.             }
  153.         }
  154.     }
  155.     return $strString;
  156. }
  157.  
  158. function goto_logged_in_url()
  159. {
  160.     //see if we need to ship them elsewhere due to bookmark, etc...
  161.     if (isset($_COOKIE['transfer_url']))
  162.     {
  163.         header("location: http://" . $_SERVER['HTTP_HOST'] . $_COOKIE['transfer_url']);
  164.         exit();
  165.     }
  166.     else
  167.     {
  168.         //We've succeeded, let's go!
  169.         gotoAbs('/folders/private');
  170.         exit();
  171.     }
  172. }
  173.  
  174. function log_activity($sAction, $sResult, $sMessage)
  175. {
  176.     // format of the log is:
  177.     // [DATE(added by PHP)] Remote IP:PHP Page:Action:Result:[opt]error message/exception message/additional text
  178.     // Result is one of: success, failure, error, exception, info
  179.     error_log("[" . date("D M d H:i:s Y") . "] " . $_SERVER['PHP_SELF'] . ":" . $sAction . ":" . $sResult . ":" . $sMessage, 0);
  180. }
  181.  
  182. function getSerializedProperty ($sVarName)
  183. {
  184.     $sFile = session_save_path() . "/" . $sVarName;
  185.     if (file_exists($sFile))
  186.     {
  187.         $handle = fopen($sFile, 'rb');
  188.         // Read content from our opened file.
  189.         $sContents = fread($handle, filesize($sFile));
  190.         fclose($handle);
  191.     
  192.         if ($sContents == "")
  193.         {
  194.             log_activity("get serialized property for " . $sVarName, "failure", return_error_text(115, "", $arErrors));
  195.             return false;
  196.         }
  197.         else
  198.         {
  199.             $objVarObject = unserialize($sContents);
  200.             log_activity("get serialized property for " . $sVarName, "success", serialize($objVarObject));
  201.             return $objVarObject;
  202.         }
  203.     }
  204.     else
  205.     {
  206.         return false;
  207.     }
  208. }
  209.  
  210. function setSerializedProperty ($sVarName, $objVarObject)
  211. {
  212.     $sFile = session_save_path() . "/" . $sVarName;
  213.     // there were issues with PHP only writing to the size of the previous file in some cases, let's biff it and start afresh.
  214.     unlink($sFile);
  215.     $handle = fopen($sFile, wb);
  216.     // Write content to our newly opened file.
  217.     if (fwrite($handle, serialize($objVarObject)) === FALSE)
  218.     {
  219.         log_activity("set serialized property for " . $sVarName, "failure", return_error_text(115, "", $arErrors));
  220.         return false;
  221.     }
  222.     fclose($handle);
  223.     log_activity("set serialized property for " . $sVarName, "success", serialize($objVarObject));
  224.     return true;
  225. }
  226.  
  227. function deleteSerializedProperty ($sVarName)
  228. {
  229.     $sFile = session_save_path() . "/" . $sVarName;
  230.     // there were issues with PHP only writing to the size of the previous file in some cases, let's biff it and start afresh.
  231.     unlink($sFile);
  232.     fclose($handle);
  233.     log_activity("delete serialized property for " . $sVarName, "success", serialize($objVarObject));
  234.     return true;
  235. }
  236.  
  237. ///////////////////////////////////////////////////
  238. // Determines if string is valid (non empty/non null)
  239. ///////////////////////////////////////////////////
  240. function isValidString ($string)
  241. {
  242.     $bReturn = false;
  243.     if (isset($string) && $string != null && $string != "")
  244.     {
  245.         $bReturn = true;
  246.     }
  247.     return $bReturn;
  248. }
  249.  
  250. ///////////////////////////////////////////////////
  251. // return's page title -
  252. // uses welcome headline OR product name as base, with other bits -
  253. // folder and/or file name; action (upload/slideshow); etc...
  254. ///////////////////////////////////////////////////
  255. function returnPageTitle($sIntroHeadline, $sProductNameInformal, $nmSharedPlace, $sPath, $fileName)
  256. {
  257.     $sPageTitle = "";
  258.     $sSiteTitle = "";
  259.     if (isValidString($sIntroHeadline))
  260.     {
  261.         $sSiteTitle = $sIntroHeadline;
  262.     }
  263.     else
  264.     {
  265.         $sSiteTitle = $sProductNameInformal;
  266.     }
  267.  
  268.     // if we have multiple slashes, we've done a rewrite and need to chop off all the un-needed cruft, 
  269.     // otherwise, we use the .php as the determiner for where we are.
  270.     if (strripos($_SERVER['PHP_SELF'], "/") > 0 )
  271.     {
  272.         $sSelf = strrev(strrchr(strrev(substr($_SERVER['PHP_SELF'],1)), "/"));
  273.     }
  274.     else
  275.     {
  276.         $sSelf = $_SERVER['PHP_SELF'];
  277.     }
  278.  
  279.     switch ($sSelf)
  280.     {
  281.         case "folders/":
  282.         case "/places.php":
  283.             $sPageTitle = $sSiteTitle;
  284.             break;
  285.         case "folderview/":
  286.         case "/shareview.php":
  287.             $sPageTitle = $sSiteTitle . " - " . getFolderName($nmSharedPlace, $sPath);
  288.             break;
  289.         case "fileview/":
  290.         case "/image.php":
  291.             $sPageTitle = $sSiteTitle . " - " . getFolderName($nmSharedPlace, $sPath) . " - " . $fileName;
  292.             break;
  293.         case "slideshow/":
  294.         case "/slideshow.php":
  295.             $sPageTitle = "Slideshow - " . $sSiteTitle . " - " . getFolderName($nmSharedPlace, $sPath) ;
  296.             break;
  297.          case "/uploadform.php":
  298.             $sPageTitle = "Upload - " . $sSiteTitle;
  299.             break;
  300.          case "/upload.php":
  301.             $sPageTitle = $sSiteTitle . " - Upload Complete";
  302.             break;
  303.          case "/login":
  304.          case "/login.php":
  305.             $sPageTitle = "Sign In To: " . $sSiteTitle;
  306.             break;
  307.          case "/help":
  308.          case "help/":
  309.          case "/login.php":
  310.             $sPageTitle = $sSiteTitle . " - Help";
  311.             break;
  312.          case "error/":
  313.          case "/error.php":
  314.             $sPageTitle = $sSiteTitle . " - Error!";
  315.             break;
  316.          case "preferences/":
  317.             $sPageTitle = $sSiteTitle . " - Preferences";
  318.             break;
  319.          default:
  320.             $sPageTitle = $sSiteTitle;
  321.             break;
  322.     }
  323.     return $sPageTitle;
  324. }
  325.  
  326. function urlEncodeString($string)
  327. {
  328.     // | and : are illegal character vlaues for Windows filenames,
  329.     // so we can use them as a custom encode/decode mechanism
  330.     $sReturn = $string;
  331.     $sReturn = str_replace("\\", "*", $sReturn);
  332.     // encoding
  333.     $sReturn = str_replace("%", "%25", $sReturn);
  334.     $sReturn = str_replace("'", "%27", $sReturn);
  335.     $sReturn = str_replace("+", "%252B", $sReturn);
  336.     $sReturn = str_replace(" ", "%20", $sReturn);
  337.     $sReturn = str_replace("&", "%2526", $sReturn);
  338.     $sReturn = str_replace("#", "%23", $sReturn);
  339.     $sReturn = str_replace("{", "%7B", $sReturn);
  340.     $sReturn = str_replace("}", "%7D", $sReturn);
  341.     return $sReturn;
  342. }
  343.  
  344. function urlDecodeString($string)
  345. {
  346.     // | and : are illegal character vlaues for Windows filenames,
  347.     // so we can use them as a custom encode/decode mechanism
  348.     $sReturn = $string;
  349.     $sReturn = str_replace("|", "\\", $sReturn); // no longer used, but here for legacy support of bookmarks from when it was used.
  350.     $sReturn = str_replace("*", "\\", $sReturn);
  351.     // decoding
  352.     $sReturn = str_replace("%25", "%", $sReturn);
  353.     $sReturn = str_replace("%27", "'", $sReturn);
  354.     $sReturn = str_replace("%2B", "+", $sReturn);
  355.     $sReturn = str_replace("\\'", "'", $sReturn);
  356.     $sReturn = str_replace("%20", " ", $sReturn);
  357.     $sReturn = str_replace("%26", "&", $sReturn);
  358.     $sReturn = str_replace("%23", "#", $sReturn);
  359.     $sReturn = str_replace("%7B", "{", $sReturn);
  360.     $sReturn = str_replace("%7D", "}", $sReturn);
  361.     return $sReturn;
  362. }
  363.  
  364. ///////////////////////////////////////////////////
  365. // Converts bytes to a human readable string
  366. // @param int $bytes Number of bytes
  367. // @param int $precision Number of decimal places to include in return string
  368. // @return string formatted string rounded to $precision
  369. ///////////////////////////////////////////////////
  370. function bytesToHumanReadableUsage($bytes, $precision = 2)
  371. {
  372.     if (!is_numeric($bytes) || $bytes < 0) 
  373.     {
  374.         return null;
  375.     }
  376.     for ($level = 0; ($bytes >= 1024) && ($level < 6); $level++) 
  377.     {    
  378.         $bytes /= 1024;      
  379.     }
  380.     switch ($level)
  381.     {
  382.         case 0:
  383.             $suffix = 'Bytes';
  384.             break;
  385.         case 1:
  386.             $suffix = 'KB';
  387.             break;
  388.         case 2:
  389.             $suffix = 'MB';
  390.             break;
  391.         case 3:
  392.             $suffix = 'GB';
  393.             break;
  394.         case 4:
  395.             $suffix = 'TB';
  396.             break;
  397.         case 5:
  398.             $suffix = 'EB';
  399.             break;
  400.         default:
  401.             $suffix = '';
  402.             break;
  403.     }
  404.     return round($bytes, $precision) . ' ' . $suffix;
  405. }
  406.  
  407. ///////////////////////////////////////////////////
  408. // let's define the browser type for code branch logic
  409. ///////////////////////////////////////////////////
  410. $btBrowserType  =   "default";
  411. $sUserAgent =   strtolower(($_SERVER['HTTP_USER_AGENT']));
  412. if (stristr($sUserAgent,"mac_powerpc") AND stristr($sUserAgent, "msie 5"))
  413. {
  414.     $btBrowserType  =   "macosxie";
  415. }
  416. if ((stristr($sUserAgent, "windows ce;")))
  417. {
  418.     $btBrowserType  =   "pocketpc";
  419. }
  420. if ((stristr($sUserAgent, "msie")) AND (stristr($sUserAgent, "windows")))
  421. {
  422.     $btBrowserType  =   "ie";
  423. }
  424.  
  425. function getSitePreferences()
  426. {
  427.     global $sStyleFamily, $sStyleName;
  428.     $aPreferences = getSerializedProperty("prefs");
  429.     if ($aPreferences != false)
  430.     {
  431.         foreach ($aPreferences as $pref)
  432.         {
  433.             if ($pref[0] == "theme")
  434.             {
  435.                 $StyleFamilyName    = $pref[1];
  436.                 $iDividerPos        = strpos($StyleFamilyName, "/");
  437.                 $sStyleFamily       = substr($StyleFamilyName, 0, $iDividerPos);
  438.                 $sStyleName         = substr($StyleFamilyName, ($iDividerPos + 1));
  439.             }
  440.             elseif(isValidString($pref[1]))
  441.             {
  442.                 global $ObjectsPerPage, $iMidSizeWidth, $iMidSizeHeight, $iSlideshowWidth, $iSlideshowHeight, $iRefreshInterval, $bRssFeedsEnabled;
  443.                 switch ($pref[0])
  444.                 {
  445.                     case "ObjectsPerPage":
  446.                         $ObjectsPerPage = $pref[1];
  447.                         break;
  448.                     case "iMidSizeWidth":
  449.                         $iMidSizeWidth = $pref[1];
  450.                         break;
  451.                     case "iMidSizeHeight":
  452.                         $iMidSizeHeight = $pref[1];
  453.                         break;
  454.                     case "iSlideshowWidth":
  455.                         $iSlideshowWidth = $pref[1];
  456.                         break;
  457.                     case "iSlideshowHeight":
  458.                         $iSlideshowHeight = $pref[1];
  459.                         break;
  460.                     case "iRefreshInterval":
  461.                         $iRefreshInterval = $pref[1];
  462.                         break;
  463.                     case "bRssFeedsEnabled":
  464.                         switch ($pref[1])
  465.                         {
  466.                             case "on":
  467.                                 $bRssFeedsEnabled = true;
  468.                                 break;
  469.                             case "off":
  470.                                 $bRssFeedsEnabled = false;
  471.                                 break;
  472.                         }
  473.                         break;
  474.                 }
  475.             }
  476.         }
  477.     }
  478. }
  479.  
  480. function setSitePreferences($aPreferences)
  481. {
  482.     $bPreferencesSet = setSerializedProperty ("prefs", $aPreferences);
  483.     if ($bPreferencesSet)
  484.     {
  485.         return true;
  486.     }
  487.     else
  488.     {
  489.         return false;
  490.     }
  491. }
  492.  
  493. function convertUrlsToHyperlinks($sSearch)
  494. {
  495.     $sAllowedDomains    = ".com;.org;.net;.edu";
  496.     $sReturn            = "";
  497.     $sPattern           = " ";
  498.     $arWords            = split($sPattern, $sSearch);
  499.     $arDomains          = split(";",$sAllowedDomains);
  500.  
  501.     foreach ($arDomains as $domain)
  502.     {
  503.         $i = 0;
  504.         foreach($arWords as $word)
  505.         {
  506.             if (strpos($word,$domain) !== false )
  507.             {
  508.                 // we found a URL, let's see if it has http:// in it
  509.                 if (strpos($word,"http") === false )
  510.                 {
  511.                     $arWords[$i] = "<a target=\"_blank\" href=\"http://" . $word . "\">" . $word . "</a>";
  512.                 }
  513.                 else
  514.                 {
  515.                     $arWords[$i] = "<a target=\"_blank\" href=\"" . $word . "\">" . $word . "</a>";
  516.                 }
  517.             }
  518.             $i++;
  519.         }
  520.         $i++;
  521.     }
  522.     
  523.     $i = 0;
  524.     foreach($arWords as $word)
  525.     {
  526.         if ($i == 0)
  527.         {
  528.             $sReturn = $word;
  529.         }
  530.         else
  531.         {
  532.             $sReturn .= " " . $word;
  533.         }
  534.         $i++;
  535.     }
  536.     
  537.     return $sReturn;
  538. }
  539.  
  540. function isIpAddressPrivate($sIPAddress = "")
  541. {
  542.     ////////////////////////////////////////////////////////////////////////////////
  543.     // For the sake of determining if you are viewing the site as a private IP      
  544.     // address (instead of by domain name) we will define the following blocks as   
  545.     // private (per IANA in RFC 1597.)  If you are using a private IP to access your
  546.     // site, we can safely assume you are internal to the network it is on and will 
  547.     // need things like the feed to use the internal IP address as well.            
  548.     ////////////////////////////////////////////////////////////////////////////////
  549.     //  10.0.0.0    - 10.255.255.255                                                
  550.     //  127.0.0.1   - 127.0.0.1                                                     
  551.     //  172.16.0.0  - 172.31.255.255                                                
  552.     //  192.168.0.0 - 192.168.255.255                                               
  553.     ////////////////////////////////////////////////////////////////////////////////
  554.     
  555.     $lTestedIpAddress   = ip2long($sIPAddress);
  556.     $bReturn            = false;
  557.     
  558.     $lRangeStart10Dot = ip2long("10.0");
  559.     $lRangeEnd10Dot = ip2long("10.255.255.255");
  560.     if ($lTestedIpAddress > $lRangeStart10Dot &&  $lTestedIpAddress < $lRangeEnd10Dot)
  561.     {
  562.         $bReturn = true;
  563.     }
  564.     
  565.     $lRangeLoopback = ip2long("127.0.0.1");
  566.     if ($lTestedIpAddress == $lRangeLoopback)
  567.     {
  568.         $bReturn = true;
  569.     }
  570.     
  571.     $lRangeStart172Dot = ip2long("172.16.0");
  572.     $lRangeEnd172Dot = ip2long("172.31.255.255");
  573.     if ($lTestedIpAddress > $lRangeStart172Dot &&  $lTestedIpAddress < $lRangeEnd172Dot)
  574.     {
  575.         $bReturn = true;
  576.     }
  577.     
  578.     $lRangeStart192Dot = ip2long("192.168.0");
  579.     $lRangeEnd192Dot = ip2long("192.168.255.255");
  580.     if ($lTestedIpAddress > $lRangeStart192Dot &&  $lTestedIpAddress < $lRangeEnd192Dot)
  581.     {
  582.         $bReturn = true;
  583.     }
  584.     
  585.     return $bReturn;
  586. }
  587.  
  588. function isPhotoFile($sFileNameOrPath)
  589. {
  590.     global $sincPhotoFileExtensions;
  591.     $bReturn        = false;
  592.     $sFileExtension  = strtolower(strrchr($sFileNameOrPath, "."));
  593.     
  594.     if (stristr($sincPhotoFileExtensions, $sFileExtension))
  595.     {
  596.         $bReturn = true;
  597.     }
  598.     
  599.     return $bReturn;
  600. }
  601. ?>