Location: PHPKode > projects > Phpman > phpman-2.0a_RC2/includes/phpman.php
<?php
/**
* Common functions file
* @package phpman
* @copyright (C) 2004 Samuel Suter
* @author Samuel Suter <hide@address.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
* @version 1.0
**/

/**
* encrypt a string
* @param string $input
* @return string encrypted password
*/
function mlsCrypt($input) {
	$crypt = md5($input);
	return $crypt;
}

function debugarray($array) {
	echo "<pre>";
	echo print_r($array);
	echo "</pre>";
}

/**
* Get an array of pages
* @param integer $root_ID
* @param integer $parent_ID Print only children of given parent
* @param string $get_lang Fetch given language title and content too
* @param integer $samelevel Print only pages with the same level als page_ID $samelevel
* @param boolean $noroot Don't print root page if set to TRUE
* @return array Array with all pages
*/
function get_pages_array($root_ID,$parent_ID = 0,$get_lang = '',$samelevel = 0,$noroot = FALSE,$page_ID = 0) {
	global $database;
	if($samelevel) {
		$query = "SELECT a1.page_ID,COUNT(*) AS `level` FROM `#__pages` AS a1, `#__pages` AS a2 WHERE  a1.page_ID='".$samelevel."' AND a1.root_ID='".$root_ID."' AND a2.root_ID='".$root_ID."' AND a1.lft BETWEEN a2.lft AND a2.rgt GROUP BY a1.lft";
		$database->setQuery($query);
		$same_data = $database->loadRowAssoc();
		$valid_level = $same_data["level"];
	}
	if($get_lang) {
		$query = "SELECT t1.*,t3.isocode from `#__pages_lang` AS t1 INNER JOIN `#__pages` AS t2 ON t1.page_ID=t2.page_ID INNER JOIN `#__languages` AS t3 ON t1.language_ID=t3.language_ID WHERE t2.root_ID='".$root_ID."' AND t3.isocode='".$get_lang."'";
		$database->setQuery($query);
		
		$lang_data = $database->loadRowsCustom2("isocode","page_ID");
		$lang_data = $lang_data[$get_lang];
		
		$query = "SELECT t1.*,t3.isocode from `#__pages_lang` AS t1 INNER JOIN `#__pages` AS t2 ON t1.page_ID=t2.page_ID INNER JOIN `#__languages` AS t3 ON t1.language_ID=t3.language_ID WHERE t2.root_ID='".$root_ID."' AND t3.isocode='"._mlsLang."'";
		$database->setQuery($query);
		$lang_data2 = $database->loadRowsCustom2("isocode","page_ID");
		$lang_data2 = $lang_data2[_mlsLang];
	}
	if(!$parent_ID) {
		$database->setQuery("SELECT a1.page_ID,a1.name,a1.lft,a1.rgt,COUNT(*) AS `level`,a1.numbering FROM `#__pages` AS a1, `#__pages` AS a2 WHERE a1.root_ID='".$root_ID."' AND a2.root_ID='".$root_ID."' AND a1.lft BETWEEN a2.lft AND a2.rgt GROUP BY a1.lft");
	} else {
		$database->setQuery("SELECT `lft`,`rgt` FROM `#__pages` WHERE `page_ID`='".$parent_ID."'");
		$data_parent = $database->loadRowAssoc();
		$database->setQuery("SELECT a1.page_ID,a1.name,a1.lft,a1.rgt,COUNT(*) AS `level`,a1.numbering FROM `#__pages` AS a1, `#__pages` AS a2 WHERE a1.root_ID='".$root_ID."' AND a2.root_ID='".$root_ID."' AND a1.lft BETWEEN a2.lft AND a2.rgt GROUP BY a1.lft");
	}
	$rows = $database->loadRowsAssoc();
	$ret = array();
	$iCount = 0;
	foreach($rows as $row) {
		$level = $row["level"];
		
		////Store number in array
		if($pages[$level] == "") {
			//if this is the first page in this level, number is '1'
			$pages[$level] = 1;
		} else {
			//else increment the number
			$pages[$level] = $pages[$level] + 1;
		}
		
		//// START numbering ////
		$segments = $level - 1;
		$number = "";
		$temp_level = $level;
		for($i = 0; $i < $segments; $i++) {
			if($i == $segments - 1) {
				if($row["numbering"] == "roman") {
					$number .= ArabicToRoman($pages[$level]) . ".";
				} else {					
					$number .= $pages[$level] . ".";
				}
			} else {
				$temp_level = $temp_level - 1;
				if($row["numbering"] == "roman") {
					$number = ArabicToRoman($pages[$temp_level]) . "." . $number;
				} else {					
					$number = $pages[$temp_level] . "." . $number;
				}
			}
		}
		$number = substr($number,0,strlen($number) - 1);
		
		if($prev_level == $level) {
			$prev_level = $prev_level - 1;
		} elseif($prev_level > $level) {
			$pages[$prev_level] = 0;
		}
		//// END numbering ////
		
		
		$nbsp = "";
		for($i = 0; $i < $level - 1; $i++) {
			$nbsp .= "&nbsp;&nbsp;&nbsp;";
		}
		
		$show = 0;
		if(!isset($data_parent) OR ($row["lft"] > $data_parent["lft"] AND $row["rgt"] < $data_parent["rgt"])) {
			if($row["page_ID"] == $root_ID AND $noroot == TRUE) {
				$show = 0;
			} elseif($data_parent AND !$valid_level) {
				/** parent given, but no valid level yet SHOW */
				$valid_level = $row["level"];
				$show = 1;
			} elseif(!$data_parent AND !$valid_level) {
				/** no parent, no level given SHOW */
				$show = 1;
			} elseif($data_parent AND $row["level"] == $valid_level) {
				/** parent and level given SHOW */
				
				$show = 1;
			} elseif($row["level"] == $valid_level) {
				/** level match SHOW */
				$show = 1;
			} else {
				$show = 0;
			}
			if($show == 1) {
				$ret[$iCount]["page_ID"] = $row["page_ID"];
				$ret[$iCount]["name"] = $row["name"];
				$ret[$iCount]["lft"] = $row["lft"];
				$ret[$iCount]["rgt"] = $row["rgt"];
				$ret[$iCount]["level"] = $row["level"];
				$ret[$iCount]["spaces"] = $nbsp;
				$ret[$iCount]["number"] = $number;
				if($lang_data OR $lang_data2) {
					if($lang_data[$row["page_ID"]]["title"] == "") {
						$ret[$iCount]["title"] = $lang_data2[$row["page_ID"]]["title"];
					} else {
						$ret[$iCount]["title"] = $lang_data[$row["page_ID"]]["title"];
					}
					if($lang_data[$row["page_ID"]]["content"] == "") {
						$ret[$iCount]["content"] = $lang_data2[$row["page_ID"]]["content"];
					} else {
						$ret[$iCount]["content"] = $lang_data[$row["page_ID"]]["content"];
					}
				}
				
				
				if($page_ID AND $row["page_ID"] == $page_ID) {
					/** this is the page given */
					$ret2 = $ret[$iCount];
				}
				$iCount++;
			}
			
		}
		$prev_level = $level;
	}
	if($ret2) {
		return $ret2;
	} else {
		return $ret;
	}
};

/**
* Get the specified language version of a page
* @param integer $page_ID
* @param string $isocode
* @return array Page-data and language-data
*/
function getPageLang($page_ID,$isocode) {
	global $database;
	$table = new mlsDBTable("#__pages","page_ID",$database);
	$temp = $table->load($page_ID);
	$ext_page_data = get_pages_array($temp["root_ID"],0,$isocode,0,FALSE,$page_ID);
	$query = "SELECT t1.*,t2.* FROM `#__pages` AS t1 INNER JOIN `#__pages_lang` AS t2 ON t1.page_ID=t2.page_ID INNER JOIN `#__languages` AS t3 ON t2.language_ID=t3.language_ID WHERE t1.page_ID='".$page_ID."' AND t3.isocode='".$isocode."'";
	$database->setQuery($query);
	
	$data = $database->loadRowAssoc();
	if(count($data) < 1) {
		$query = "SELECT t1.*,t2.* FROM `#__pages` AS t1 INNER JOIN `#__pages_lang` AS t2 ON t1.page_ID=t2.page_ID INNER JOIN `#__languages` AS t3 ON t2.language_ID=t3.language_ID WHERE t1.page_ID='".$page_ID."' AND t3.isocode='"._mlsLang."'";
		$database->setQuery($query);
		$data = $database->loadRowAssoc();
		if(count($data) < 1) {
			$query = "SELECT t1.* FROM `#__pages` AS t1 WHERE t1.page_ID='".$page_ID."'";
			$database->setQuery($query);
			$data = $database->loadRowAssoc();
		}
	}
	$data["number"] = $ext_page_data["number"];
	$data["level"] = $ext_page_data["level"];
	return $data;
};

/**
* Get the specified language version of a manual
* @param integer $manual_ID
* @param string $isocode
* @return array Page-data and language-data
*/
function getManualLang($manual_ID,$isocode) {
	global $database;
	$query = "SELECT t1.*,t2.* FROM `#__manuals` AS t1 INNER JOIN `#__manuals_lang` AS t2 ON t1.manual_ID=t2.manual_ID INNER JOIN `#__languages` AS t3 ON t2.language_ID=t3.language_ID WHERE t1.manual_ID='".$manual_ID."' AND t3.isocode='".$isocode."'";
	$database->setQuery($query);
	$data = $database->loadRowAssoc();
	if(count($data) < 1) {
		$query = "SELECT t1.*,t2.* FROM `#__manuals` AS t1 INNER JOIN `#__manuals_lang` AS t2 ON t1.manual_ID=t2.manual_ID INNER JOIN `#__languages` AS t3 ON t2.language_ID=t3.language_ID WHERE t1.manual_ID='".$manual_ID."' AND t3.isocode='"._mlsLang."'";
		$database->setQuery($query);
		$data = $database->loadRowAssoc();
	}
	return $data;
};

/**
* Parser for the page code
* @param string $content
* @return string HTML version of $content
*/
function parse_page($content) {
	
	$content = ereg_replace("<", "&lt;", $content);
	$content = ereg_replace(">", "&gt;", $content);
	
	$content = nl2br($content);
	
	
	$content = eregi_replace("\[code\]", "[CODE]", $content);
	$content = eregi_replace("\[/code\]", "[/CODE]", $content);
	
	$content = eregi_replace("\[html\]", "[HTML]", $content);
	$content = eregi_replace("\[/html\]", "[/HTML]", $content);
	
	//// [CODE] bearbeiten
	$offset = 0;
	$i = 0;
	$code = "";
	while($i < strlen($content)) {
		$pos = strpos($content,"[CODE]",$i);
		if($pos !== false) {
			//// Solange noch [CODE] in der message steht
			//Positionen und string vor- und nachher rausfinden
			$code_pos_start = strpos($content,"[CODE]",$offset);
			$vorher = substr($content,0,$code_pos_start);
			$code_pos_end = strpos($content,"[/CODE]",$offset);
			$nachher = substr($content,$code_pos_end + 7,strlen($content));
			
			//String zwischen [CODE] und [/CODE]
			$substring = substr($content,$code_pos_start,$code_pos_end - $code_pos_start + 7);
			
			//substring HTML-Formatieren
			$code = substr($substring,6,strlen($substring) - 13);
			$code = "<?php\n\r" . $code . "\n\r?>";
			$code = ereg_replace("<br />", "", $code);
			$code = ereg_replace("&lt;", "<", $code);
			$code = ereg_replace("&gt;", ">", $code);
			$code2 = highlight_string($code,TRUE);
			$code = "<BLOCKQUOTE><DIV STYLE=\"COLOR: #000000; BACKGROUND-COLOR: #CCCCCC; BORDER-COLOR: #000000; BORDER: 1px solid; PADDING: 2px\"><PRE><b>Code:</b>$code2</PRE></DIV></BLOCKQUOTE>";;
			
			//Wieder zusammenfügen
			$content = $vorher . $code . $nachher;
		}
		$i++;
	}
	
	
	//// [HTML] bearbeiten
	$offset = 0;
	$i = 0;
	$html = "";
	while($i < strlen($content)) {
		$pos = strpos($content,"[HTML]",$i);
		if($pos !== false) {
			//// Solange noch [HTML] in der message steht
			//Positionen und string vor- und nachher rausfinden
			$html_pos_start = strpos($content,"[HTML]",$offset);
			$vorher = substr($content,0,$html_pos_start);
			$html_pos_end = strpos($content,"[/HTML]",$offset);
			$nachher = substr($content,$html_pos_end + 7,strlen($content));
			
			//String zwischen [HTML] und [/HTML]
			$substring = substr($content,$html_pos_start,$html_pos_end - $html_pos_start + 7);
			
			//substring HTML-Formatieren
			$html = substr($substring,6,strlen($substring) - 13);
			$html = ereg_replace("<br />", "", $html);
			$html = ereg_replace("&lt;", "<", $html);
			$html = ereg_replace("&gt;", ">", $html);
			
			//Wieder zusammenfügen
			$content = $vorher . $html . $nachher;
		}
		$i++;
	}
	return $content;
};

function html_get_img_url($str) {
	preg_match_all("/<map [^>]+>.*<\/map>/is", $str, $matches, PREG_SET_ORDER);
	foreach($matches as $match) {
		$key = "<" . md5($match[0]) . ">";
		$search[] = $key;
		$replace[] = $match[0];
	}
	$str = str_replace($replace, $search, $str);
	// indicate where urls end if they have these trailing special chars
	$sentinals = array("'&(quot|#34);'i",                // Replace html entities
                       "'&(lt|#60);'i",
                       "'&(gt|#62);'i",
                       "'&(nbsp|#160);'i",
                       "'&(iexcl|#161);'i",
                       "'&(cent|#162);'i",
                       "'&(pound|#163);'i",
                       "'&(copy|#169);'i",
                       "'&#(\d+);'e");
	$str = preg_replace($sentinals, "^^sentinal^^\\0^^sentinal^^", $str);
	
	$vdom = "[:alnum:]";                // Valid domain chars
	$vurl = $vdom."_~-";                // Valid subdomain and path chars
	//$vura = "À-ßà-ÿ!#$%&*+,;=@.".$vurl; // Valid additional parameters (after '?') chars;
	$vura = "À-ßà-ÿ!#$%&*+,;=@./".$vurl; // Valid additional parameters (after '?') chars;
                                              // insert other local characters if needed
	$protocol = "[[:alpha:]]{3,10}://"; // Protocol exp
	$server = "([$vurl]+[.])*[$vdom]+"; // Server name exp
	$path = "(([$vurl]+([.][$vurl]+)*/)|([.]{1,2}/))*"; // Document path exp (/.../)
	$name = "[$vurl]+([.][$vurl]+)*";  // Document name exp
	$params = "[?][$vura]*";            // Additional parameters (for GET)
	
	$str = eregi_replace("$protocol$server(/$path($name)?)?($params)?",  "\\0", $str); // URL into links
	
	$str = str_replace("^^sentinal^^", '', $str);
	return str_replace($search, $replace, $str);
};

function html_activate_urls($str,$prefix1 = '<a href=\"', $suffix1 = '\">', $suffix2 = "</a>")
{
   // lift all links, images and image maps
   preg_match_all("/<a [^>]+>.*<\/a>/is", $str, $matches, PREG_SET_ORDER);
   foreach($matches as $match)
   {
       $key = "<" . md5($match[0]) . ">";
       $search[] = $key;
       $replace[] = $match[0];
   }

   preg_match_all("/<map [^>]+>.*<\/map>/is", $str, $matches, PREG_SET_ORDER);
   foreach($matches as $match)
   {
       $key = "<" . md5($match[0]) . ">";
       $search[] = $key;
       $replace[] = $match[0];
   }

   preg_match_all("/<img [^>]+>/is", $str, $matches, PREG_SET_ORDER);
   foreach($matches as $match)
   {
       $key = "<" . md5($match[0]) . ">";
       $search[] = $key;
       $replace[] = $match[0];
   }

   $str = str_replace($replace, $search, $str);

   // indicate where urls end if they have these trailing special chars
   $sentinals = array("'&(quot|#34);'i",                // Replace html entities
                       "'&(lt|#60);'i",
                       "'&(gt|#62);'i",
                       "'&(nbsp|#160);'i",
                       "'&(iexcl|#161);'i",
                       "'&(cent|#162);'i",
                       "'&(pound|#163);'i",
                       "'&(copy|#169);'i",
                       "'&#(\d+);'e");
   $str = preg_replace($sentinals, "^^sentinal^^\\0^^sentinal^^", $str);

   $vdom = "[:alnum:]";                // Valid domain chars
   $vurl = $vdom."_~-";                // Valid subdomain and path chars
   //$vura = "À-ßà-ÿ!#$%&*+,;=@.".$vurl; // Valid additional parameters (after '?') chars;
   $vura = "À-ßà-ÿ!#$%&*+,;=@./".$vurl; // Valid additional parameters (after '?') chars;
                                       // insert other local characters if needed
   $protocol = "[[:alpha:]]{3,10}://"; // Protocol exp
   $server = "([$vurl]+[.])*[$vdom]+"; // Server name exp
   $path = "(([$vurl]+([.][$vurl]+)*/)|([.]{1,2}/))*"; // Document path exp (/.../)
   $name = "[$vurl]+([.][$vurl]+)*";  // Document name exp
   $params = "[?][$vura]*";            // Additional parameters (for GET)

   $str = eregi_replace("$protocol$server(/$path($name)?)?($params)?",  $prefix1."\\0".$suffix1."\\0".$suffix2, $str); // URL into links

   $str = str_replace("^^sentinal^^", '', $str);
   return str_replace($search, $replace, $str);
}
function ArabicToRoman( $myArabicNum, $htmlelement = '', $htmlelement2 = '' ) {
    if( $myArabicNum != floor( $myArabicNum ) ) { return "not convertable, number is not an integer."; }
    if( $myArabicNum > 3999999 ) { return "not convertable, number exceeds 3999999."; }
    if( $myArabicNum <= 0 ) { return "not convertable, number must be greater than 0."; }
    //prepare roman numerals
    $ar_to_rom[1000000] = $htmlelement."M".$htmlelement2;
    $ar_to_rom[500000] = $htmlelement."D".$htmlelement2;
    $ar_to_rom[100000] = $htmlelement."C".$htmlelement2;
    $ar_to_rom[50000] = $htmlelement."L".$htmlelement2;
    $ar_to_rom[10000] = $htmlelement."X".$htmlelement2;
    $ar_to_rom[5000] = $htmlelement."V".$htmlelement2;
    $ar_to_rom[1000] = "M";
    $ar_to_rom[500] = "D";
    $ar_to_rom[100] = "C";
    $ar_to_rom[50] = "L";
    $ar_to_rom[10] = "X";
    $ar_to_rom[5] = "V";
    $ar_to_rom[1] = "I";
    $myRomanNum = '';
    for( $x = 1000000; $x >= 1; $x /= 10 ) {
        //start at M(bar) and work down in factors of 10 to 1.
        //45xxx, 49..9xx, 49..95xx, 99..95xx and 99..9xx can be done with only two
        //characters. This function optimises the output. Not doing this
        //would result in the use of 4+ characters instead
        switch( floor( $myArabicNum / $x ) ) {
            case 1 :
                $myRomanNum .= $ar_to_rom[$x];
                break;
            case 2 :
                $myRomanNum .= $ar_to_rom[$x].$ar_to_rom[$x];
                break;
            case 3 :
                $myRomanNum .= $ar_to_rom[$x].$ar_to_rom[$x].$ar_to_rom[$x];
                break;
            case 4 :
                //optimise for 45xx, 49..95xx and 99..9xx, work out the number of 9s in a row.
                $num_nines = 1; $i2 = 0; $subnum = '0.';
                for( $i = 1; substr( $myArabicNum, $i, 1 ) == '9'; $i++ ) { $num_nines *= 10; $i2 = $i; }
                for( $i = 1; $i <= $i2; $i++ ) { $subnum .= '9'; }
                if( substr( $myArabicNum, $i2+1, 1 ) == '5' ) {
                    //any number of nines in a row followed by a 5 (including no 9s)
                    $myRomanNum .= $ar_to_rom[$x / ( 2 * $num_nines )].$ar_to_rom[5 * $x];
                    $subnum .= '5';
                } else {
                    //any number of nines in a row (including no 9s)
                    $myRomanNum .= $ar_to_rom[$x / $num_nines].$ar_to_rom[5 * $x];
                }
                $myArabicNum -= $subnum * $x;
                break;
            case 5 :
                $myRomanNum .= $ar_to_rom[5 * $x];
                break;
            case 6 :
                $myRomanNum .= $ar_to_rom[5 * $x].$ar_to_rom[$x];
                break;
            case 7 :
                $myRomanNum .= $ar_to_rom[5 * $x].$ar_to_rom[$x].$ar_to_rom[$x];
                break;
            case 8 :
                $myRomanNum .= $ar_to_rom[5 * $x].$ar_to_rom[$x].$ar_to_rom[$x].$ar_to_rom[$x];
                break;
            case 9 :
                //optimise for 99..95xx and 99..9xx, work out the number of 9s in a row.
                $subnum = '0.'; $num_nines = 0.1; //trust me, it works
                for( $i = 0; substr( $myArabicNum, $i, 1 ) == '9'; $i++ ) { $num_nines *= 10; $i2 = $i + 1; }
                for( $i = 1; $i < $i2; $i++ ) { $subnum .= '9'; }
                if( substr( $myArabicNum, $i2, 1 ) == '5' ) {
                    //any number of nines in a row followed by a 5 (including only one 9)
                    $myRomanNum .= $ar_to_rom[$x / ( 2 * $num_nines )].$ar_to_rom[10 * $x];
                    $subnum .= '5';
                } else {
                    //any number of nines in a row (including only one 9)
                    $myRomanNum .= $ar_to_rom[$x / $num_nines].$ar_to_rom[10 * $x];
                }
                $myArabicNum -= $subnum * $x;
                break;
        }
        //take out the bit we just did and go round again with the remainder
        $myArabicNum %= $x;
    }
    return $myRomanNum;
}

/**
* Convert a string to act as filename (e.g. manual-title -> filename)
* @param string $input
* @return string
*/
function convertTitle($input) {
	$output = str_replace(" ","_",$input);
	$output = strtolower($output);
	return $output;
};

/**
* Format a HTML input string to fit for pdf output
* @param string $input
* @return string
*/
function formatHtml($input) {
	$output = html_entity_decode($input);
	$output = eregi_replace("\<b\>", "[bold]", $output);
	$output = eregi_replace("\</b\>", "[/bold]", $output);
	$output = eregi_replace("\<strong\>", "[bold]", $output);
	$output = eregi_replace("\</strong\>", "[/bold]", $output);
	$output = eregi_replace("\<i\>", "[italic]", $output);
	$output = eregi_replace("\</i\>", "[/italic]", $output);
	$output = eregi_replace("\<u\>", "[underline]", $output);
	$output = eregi_replace("\</u\>", "[/underline]", $output);
	
	$output = eregi_replace("\<p\>", "", $output);
	$output = eregi_replace("\</p\>", "\n\n", $output);
	$output = eregi_replace("\<br\>", "\n", $output);
	/** strip HTML */
	$output = ereg_replace("<([^>]+)>", "", $output);
	$output = html_activate_urls($output,'<c:alink:','>','</c:alink>');
	
	/** convert wanted html back */
	$output = eregi_replace("\[bold\]", "<b>", $output);
	$output = eregi_replace("\[/bold\]", "</b>", $output);
	$output = eregi_replace("\[italic\]", "<i>", $output);
	$output = eregi_replace("\[/italic\]", "</i>", $output);
	$output = eregi_replace("\[underline\]", "<u>", $output);
	$output = eregi_replace("\[/underline\]", "</u>", $output);
	return $output;
};

/**
* Get number of notes in a page
* @param integer $page_ID
* @return integer Number of notes
*/
function getNumNotes($page_ID) {
	global $database;
	$query = "SELECT * FROM `#__notes` WHERE `page_ID`='".$page_ID."'";
	$database->setQuery($query);
	$database->query();
	$notes = $database->getNumRows();
	
	return $notes;
}

function getmicrotime() {
	list($usec, $sec) = explode(" ",microtime()); 
	return ((float)$usec + (float)$sec); 
};
?>
Return current item: Phpman