Location: PHPKode > projects > PowerMovieList > powermovielist-0_14_beta/functions.php
<?php
/** powermovielist gerneral functions
 * $Id: functions.php,v 1.55 2006/01/21 13:44:07 niko Exp $
*/

//global definitions:

//avaliable $CFG[Prefix]prop.PropType values:
DEFINE("PML_PropType_Text", 0);
DEFINE("PML_PropType_Date", 1);
DEFINE("PML_PropType_Boolean", 2);
DEFINE("PML_PropType_ListBox", 3);
DEFINE("PML_PropType_ListBoxMulti", 4);
DEFINE("PML_PropType_Textfield", 5);
DEFINE("PML_PropType_Url", 6);
DEFINE("PML_PropType_UrlCached", 7);
DEFINE("PML_PropType_FileUpload", 8);
DEFINE("PML_PropType_UserRating", 9);
DEFINE("PML_PropType_DownloadLink", 10);
DEFINE("PML_PropType_StaticText", 11);
DEFINE("PML_PropType_DisplayNr", 13);
DEFINE("PML_PropType_AutoIncrement", 15);
DEFINE("PML_PropType_DownloadLinkFileUpload", 16);

//these prop-types are custom prop-types, for backwards-compatibility define them here
DEFINE("PML_PropType_DateAdded", 101);
DEFINE("PML_PropType_Clicks", 102);
DEFINE("PML_PropType_UserAdded", 103);
DEFINE("PML_PropType_Comments", 104);

//avaliable $CFG[Prefix]prop.ShowFilter values:
DEFINE("PML_ShowFilter_DontShow", 0);
DEFINE("PML_ShowFilter_Listbox", 1);
DEFINE("PML_ShowFilter_Search", 2);
DEFINE("PML_ShowFilter_Chars", 3);
DEFINE("PML_ShowFilter_SearchChars", 4);


//avaliable $CFG[Prefix]prop.ShowInPopUp values:
DEFINE("PML_PopUp_DontShow", 0);
DEFINE("PML_PopUp_Normal", 1);
DEFINE("PML_PopUp_ExtraField", 2);
DEFINE("PML_PopUp_Dowload", 3);
DEFINE("PML_PopUp_Cover", 4);

//avaliable $CFG[Prefix]prop.ShowOnCover values:
DEFINE("PML_Cover_DontShow", 0);
DEFINE("PML_Cover_Normal", 1);
DEFINE("PML_Cover_SideTitle", 2);
DEFINE("PML_Cover_SideLang", 3);
DEFINE("PML_Cover_SideFormat", 4);
DEFINE("PML_Cover_Pic", 5);
DEFINE("PML_Cover_Format", 6);
DEFINE("PML_Cover_Index", 7);

//avaliable DisplayText values for pml_propval
DEFINE("PML_DisplayText_Normal", 0);
DEFINE("PML_DisplayText_Short", 1);
DEFINE("PML_DisplayText_Html", 2);
DEFINE("PML_DisplayText_NotCached", 3);
DEFINE("PML_DisplayText_SortText", 4);

//avaliable ShowLinkType values for pml_prop
DEFINE("PML_ShowLinkType_Normal", 0);
DEFINE("PML_ShowLinkType_Newpage", 1);
DEFINE("PML_ShowLinkType_Image", 2);
DEFINE("PML_ShowLinkType_Link", 3);


//user-rights
DEFINE("PML_Rights_None", 0);
DEFINE("PML_Rights_View", 1);
DEFINE("PML_Rights_Loan", 2);
DEFINE("PML_Rights_Add", 3);
DEFINE("PML_Rights_Moderator", 4);
DEFINE("PML_Rights_ListAdmin", 5);
DEFINE("PML_Rights_SuperAdmin", 6);

//Request-login LoginStyles
DEFINE("PML_LoginStyle_AccessDenied", 0);
DEFINE("PML_LoginStyle_AccessDeniedList", 1);
DEFINE("PML_LoginStyle_LoginForm", 2);
DEFINE("PML_LoginStyle_WrongPass", 3);
DEFINE("PML_LoginStyle_UserNotFound", 4);
DEFINE("PML_LoginStyle_UserNotActivated", 5);
DEFINE("PML_LoginStyle_NoGuestAllowed", 6);
DEFINE("PML_LoginStyle_UserNoStatus", 7);


//delemiter in property field for download-links and cached-urls
DEFINE("PML_PropertyDelem", "|");

//LinkListTypes
DEFINE("PML_LinkListType_None", 0);
DEFINE("PML_LinkListType_Select", 1);
DEFINE("PML_LinkListType_Text", 2);
DEFINE("PML_LinkListType_Fav", 3);
DEFINE("PML_LinkListType_FavText", 4);


/*

- RequestLogin($LoginStyle=PML_LoginStyle_AccessDenied, $RequiredRights=PML_Rights_None)
  o when Style=PML_LoginStyle_LoginForm, display:
	login-link was clicked, just display "Login" the 2 textboxes and the submit
  o when Style=PML_LoginStyle_AccessDeniedList, display:
								   - title: Access denied to this list.
				   - txt: if not guest:
						  You need view-rights to access this list.
						  o Login with another account that has enough rights
					  o currently logged in as: $name
					  o logout-link
					   - txt: if guest:
						  Guest users don't have the rights to access this list.
					  o Login with an account that has the rights
					  o if GetRightsCode(0) > 0: register for a new account (this will then have enough rights)
					  -> login form <-
  o when Style=PML_LoginStyle_AccessDenied, display:     <---- STANDARD
		  - title: Access denied.
		  - txt: if not guest:
			 You don't have the rights to do this action. You need at least $rights, but you currently only have $rightscur.
		 o Login with another account.
		 o Contact the List-Admin of this list that he will give you more rights.
		 o currently logged in as: $name ($rights)
		 o logout-link
		  - txt: if guest:
			 Guests doesn't have the rights to do this action. You need to login with an account that has at least $rights.
		 -> login form <-
  o when Style=PML_LoginStyle_WrongPass, display:
		  - title: Wrong password.
		  - txt:
			 Wrong password entered. Please try again:
		 -> login form <-
  o when Style=PML_LoginStyle_UserNotFound, display:
		  - title: User not found.
		  - txt:
			 The entered user doesn't exist. Enter another username or create a new one.
		 -> login form <-
  o when Style=PML_LoginStyle_UserNotActivated, display:
		  - title: User not yet activated.
		  - txt:
			 This account isn't yet activated. When you register a new account, you will recive an activation-email where you have to click the activation-link to enable your account.
		 o send activation email again
		 o create a new account
		 -> login form <-
*/

function RequestLogin($LoginStyle=PML_LoginStyle_AccessDenied, $RequiredRights=PML_Rights_None) {
    global $CFG, $pmldb, $usr, $ActiveList, $usr,$ActiveUserRights, $ActiveUser, $ListUrl;
    switch($LoginStyle) {        
        case PML_LoginStyle_AccessDenied:
            if($ActiveUserRights >= $RequiredRights) //allready enough rights?
                return(true);
            
            if($ActiveUser['name']=="Guest") {
                PrintLoginForm($GLOBALS['strAccessDenied'], "$GLOBALS[strGuestsDoesntHaveRightsNeedLoginWithAtLeast] ".$GLOBALS['strUserRights'][$RequiredRights]);
            } else {
	            $message =  "$GLOBALS[strYouDontHaveTheRightsZouNeedAtLeast] ".$GLOBALS['strUserRights'][$RequiredRights].", $GLOBALS[strButYouCurrentlyOnlyHave] ".$GLOBALS['strUserRights'][$ActiveUserRights] . ".
                 <ul>
                    <li>$GLOBALS[strLoginWithAnotherAccount].
                    <li>$GLOBALS[strCurrentlyLoggedInAs]: $ActiveUser[name] [ <a href='logout.php'>$GLOBALS[strLogout]</a> ]
                    <li>$GLOBALS[strContactListAdminForMoreRights].                
                 </ul>\n";
                PrintLoginForm($GLOBALS['strAccessDenied'], $message, false);
            }
            include("bottom.html");
            exit;

            break;
        case PML_LoginStyle_AccessDeniedList:
            if($ActiveUserRights >= $RequiredRights) //allready enough rights?
                return(true);

            if($ActiveUser['name']=="Guest") {
				$message = "$GLOBALS[strGuestsDontHaveRightsToAccessThisList].
                <ul>
                  <li>$GLOBALS[strLoginWithAccountThatHasEnoughRights]\n";
                if($CFG['ListType']==0 && $CFG['ShowRegisterUser']) {
                    $strSql = "SELECT * FROM " . $CFG['Prefix'] . "userrights WHERE UserID=0 AND ListID=$ActiveList[ID]";
                    $result = pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
                    if(mysql_num_rows($result) > 0) {
                        $row = mysql_fetch_assoc($result);
                        if($row['Permissions'] > PML_Rights_None) {
                            $message .= "<li><a href='".$usr->GetRegisterUserLink()."'>$GLOBALS[strRegister]</a> $GLOBALS[strForANewAccount] ($GLOBALS[strThisWillHaveEnoughRights])\n";
                        }
                    }
                }				  
                $message .= "</ul>\n";
			    PrintLoginForm($GLOBALS['strAccessDeniedToThisList'], $message);
            } else {
                
				$message = "$GLOBALS[strYouNeedViewRightsToAccessThisList].\n";
                $message .= "<ul>\n";
                $message .= "  <li>$GLOBALS[strLoginWithAccountThatHasEnoughRights]\n";
                $message .= "  <li>$GLOBALS[strCurrentlyLoggedInAs]: $ActiveUser[name] [ <a href='logout.php'>$GLOBALS[strLogout]</a> ]\n";
                $message .= "</ul>\n";
                PrintLoginForm($GLOBALS['strAccessDeniedToThisList'], $message, false);
            }
            include("bottom.html");
            exit;
            
        case PML_LoginStyle_LoginForm:
        
            PrintLoginForm($GLOBALS['strLogin'], $GLOBALS['strPleaseEnterValidUserAndPass']);
            
            include("bottom.html");
            exit;
            
        case PML_LoginStyle_WrongPass:          
        
            PrintLoginForm($GLOBALS['strWrongPassword'], $GLOBALS['strWrongPasswordEnteredInfoText']);
            include("bottom.html");
            exit;
        
        case PML_LoginStyle_UserNotFound:
            
            $message = "      $GLOBALS[strEnteredUserWasNotFoundInDb]. $GLOBALS[strPleaseLoginAgain]";
            if($CFG['ListType']==0 && $CFG['ShowRegisterUser'])
                $message .= ", $GLOBALS[strOrRegisterANewOneByClickingTheRegisterLink]";
            $message .= ".\n";
            
            PrintLoginForm($GLOBALS['strUserNotFound'], $message);
            include("bottom.html");
            exit;
        
        case PML_LoginStyle_UserNotActivated:
            
            $message = "      $GLOBALS[strUserNotYetActivatedInfoText].<br><a href='activate.php".$GLOBALS['GlobalArg']."action=resend'>$GLOBALS[strClickHereToResendThisMail].</a>\n";
            PrintLoginForm($GLOBALS['strUserNotYetActivated'], $message);
            include("bottom.html");
            exit;
        
        case PML_LoginStyle_NoGuestAllowed:
        
            if($ActiveUser['name']!="Guest") return(true);
            
            PrintLoginForm($GLOBALS['strLogin'], $GLOBALS['strYouMustBeLoggedInToDoThisAction']);
            include("bottom.html");
            exit;
        
        case PML_LoginStyle_UserNoStatus:
            
            PrintLoginForm($GLOBALS['strUserNotYetEnabled'], $GLOBALS['strEveryUserMustBeEnabledHasntBeenEnabledEmailAdmin']);
            include("bottom.html");
            exit;
    }
}


function PrintLoginForm($title, $message, $showForm=true) {
global $CFG, $pmldb, $usr, $_POST, $FILE_SELF, $smarty;

    loadSmarty();
    
    $smarty->caching = 0; //no cache - this site isn't too complicated    
    $TplFile = "login.tpl";
    
    $smarty->assign("title", $title);
    $smarty->assign("message", $message);
    $smarty->assign("CFG",array("LinkListType"=>$CFG['LinkListType'], "ListType"=>$CFG['ListType'], "ShowRegisterUser"=>$CFG['ShowRegisterUser'], "GlobalArg"=>$GLOBALS['GlobalArg'], "GlobalArgWOActive"=>$GLOBALS['GlobalArgWOActive']));
    $smarty->assign("ActiveList", $GLOBALS['ActiveList']);
    $smarty->assign("lang", array("LngCharSet"            => $GLOBALS['LngCharSet'],
                                  "strLoginUser"          => $GLOBALS['strLoginUser'],
                                  "strLogMeOnAutoEachVisit"=> $GLOBALS['strLogMeOnAutoEachVisit'],
                                  "strLoginPass"          => $GLOBALS['strLoginPass'],
                                  "strRegister"           => $GLOBALS['strRegister'],
                                  "strLostPassword"       => $GLOBALS['strLostPassword'],
                                  "strLogin"              => $GLOBALS['strLogin']));
    $smarty->assign("showForm", $showForm);
    if(isset($_POST['LUser']))
        $LUser = $_POST['LUser'];
    else
        $LUser = "";
    $smarty->assign("LUser", $LUser);
    if($CFG['ListType']==0 && $CFG['ShowRegisterUser']) {
        $smarty->assign("RegisterUserLink", $usr->GetRegisterUserLink());
    } else {
        $smarty->assign("RegisterUserLink", "");
    }
    
    //redirect-url
    if(isset($_POST['RedirectUrl'])) { //when login.php clalled!
        $RedirectUrl = $_POST['RedirectUrl'];
    } else {
        if($FILE_SELF=="") {
            $RedirectUrl="index.php".$GLOBALS['GlobalArg'];
        } else {
            $RedirectUrl = $FILE_SELF."?".$_SERVER['QUERY_STRING'];
            $RedirectUrl = str_replace("&Login=1", "", $RedirectUrl);
            $RedirectUrl = str_replace("?Login=1", "", $RedirectUrl);
        }
    }
    if($RedirectUrl=="") $RedirectUrl="index.php".$GLOBALS['GlobalArg'];
    $smarty->assign("RedirectUrl", $RedirectUrl);

    $smarty->display($TplFile);
}

function ErrorExit($print) {
global $CFG, $pmldb, $DOC_TITLE,$ActiveList;
	if(!isset($DOC_TITLE)) $DOC_TITLE="ERROR";
	include_once("top.html");
	if(!isset($GLOBALS['strErrError'])) $GLOBALS['strErrError'] = "ERROR";
	if(!isset($GLOBALS['strErrGoBack'])) $GLOBALS['strErrGoBack'] = "back";
	echo "<br><b>$GLOBALS[strErrError]:</b> ";
	echo $print;
	echo "<br><br><a href=\"javascript: history.go(-1)\">$GLOBALS[strErrGoBack]</a>";
	include("bottom.html");
	exit;
}



//RETURN-Value: anz lines printed
function ImageStringMultiLine($image, $Font, $PosX, $PosY, $Text, $Color, $MaxWidth, $MaxHeight=0) {
		$PerLine = floor($MaxWidth / ImageFontWidth($Font));
		$Pos = 0;
		$i=0;

		//echo $Text."<br><br>";
		while($Pos < strlen($Text)) {
				$Dat = substr($Text, $Pos, $PerLine);
				$Pos += strlen($Dat);
				//echo $Dat . "<br>";
				if($Pos < strlen($Text)) {
						if(strstr($Dat, " ")) {
								$NewDat = substr($Dat, 0, strrpos($Dat, " "));
								$Pos = $Pos - (strlen($Dat) - strlen($NewDat));
								$Dat = $NewDat;
						}
						//echo $Dat . "<br>";
				}
				ImageString($image, $Font , $PosX, $PosY+$i*ImageFontHeight($Font), trim($Dat), $Color);
				$i++;

				if($MaxHeight!=0) {
						if($MaxHeight < ($i+1) * ImageFontHeight($Font)) {
								return($i);
								//maximale h?e erreicht!
						}
				}

		}
		if($i==0) $i=1;
		return($i);
}


function ImageRotate90($dest, $src, $tot_x, $tot_y) {
		for($i_x=0;$i_x<$tot_x;$i_x++) {
				for($i_y=0;$i_y<$tot_y;$i_y++){
						$ris_x=$tot_y-($i_y+1);
						$ris_y=$i_x;
						imagecopy($dest, $src, $ris_x,$ris_y,$i_x,$i_y,1,1);
				} // Y
		} // X
}



function CheckIfEmail($fEmail) {
		// check for stuff around @
		$pos = strpos ($fEmail, "@");
		if (($pos == 0) or ($pos == strlen($fEmail) - 1)) {
				return(false);
		} else {
				// check for a @ after the first @
				$pos = strpos ($fEmail, "@", strpos ($fEmail,
				"@")+1);
				if ($pos != false) {
						return(false);
				}
		}
		return(true);
}





/**
 * Removes comment lines and splits up large sql files into individual queries
 *
 * Last revision: September 23, 2001 - gandon
 *
 * @param   array    the splitted sql commands
 * @param   string   the sql commands
 *
 * @return  boolean  always true
 *
 * @access  public
 */
function PMA_splitSqlFile(&$ret, $sql)
{
	$sql          = trim($sql);
	$sql_len      = strlen($sql);
	$char         = '';
	$string_start = '';
	$in_string    = FALSE;
	$time0        = time();

	for ($i = 0; $i < $sql_len; ++$i) {
		$char = $sql[$i];

		// We are in a string, check for not escaped end of strings except for
		// backquotes that can't be escaped
		if ($in_string) {
			for (;;) {
				$i         = strpos($sql, $string_start, $i);
				// No end of string found -> add the current substring to the
				// returned array
				if (!$i) {
					$ret[] = $sql;
					return TRUE;
				}
				// Backquotes or no backslashes before quotes: it's indeed the
				// end of the string -> exit the loop
				else if ($string_start == '`' || $sql[$i-1] != '\\') {
					$string_start      = '';
					$in_string         = FALSE;
					break;
				}
				// one or more Backslashes before the presumed end of string...
				else {
					// ... first checks for escaped backslashes
					$j                     = 2;
					$escaped_backslash     = FALSE;
					while ($i-$j > 0 && $sql[$i-$j] == '\\') {
						$escaped_backslash = !$escaped_backslash;
						$j++;
					}
					// ... if escaped backslashes: it's really the end of the
					// string -> exit the loop
					if ($escaped_backslash) {
						$string_start  = '';
						$in_string     = FALSE;
						break;
					}
					// ... else loop
					else {
						$i++;
					}
				} // end if...elseif...else
			} // end for
		} // end if (in string)

		// We are not in a string, first check for delimiter...
		else if ($char == ';') {
			// if delimiter found, add the parsed part to the returned array
			$ret[]      = substr($sql, 0, $i);
			$sql        = ltrim(substr($sql, min($i + 1, $sql_len)));
			$sql_len    = strlen($sql);
			if ($sql_len) {
				$i      = -1;
			} else {
				// The submited statement(s) end(s) here
				return TRUE;
			}
		} // end else if (is delimiter)

		// ... then check for start of a string,...
		else if (($char == '"') || ($char == '\'') || ($char == '`')) {
			$in_string    = TRUE;
			$string_start = $char;
		} // end else if (is start of string)

		// ... for start of a comment (and remove this comment if found)...
		else if ($char == '#'
				 || ($char == ' ' && $i > 1 && $sql[$i-2] . $sql[$i-1] == '--')) {
			// starting position of the comment depends on the comment type
			$start_of_comment = (($sql[$i] == '#') ? $i : $i-2);
			// if no "\n" exits in the remaining string, checks for "\r"
			// (Mac eol style)
			$end_of_comment   = (strpos(' ' . $sql, "\012", $i+2))
							  ? strpos(' ' . $sql, "\012", $i+2)
							  : strpos(' ' . $sql, "\015", $i+2);
			if (!$end_of_comment) {
				// no eol found after '#', add the parsed part to the returned
				// array if required and exit
				if ($start_of_comment > 0) {
					$ret[]    = trim(substr($sql, 0, $start_of_comment));
				}
				return TRUE;
			} else {
				$sql          = substr($sql, 0, $start_of_comment)
							  . ltrim(substr($sql, $end_of_comment));
				$sql_len      = strlen($sql);
				$i--;
			} // end if...else
		} // end else if (is comment)

		// ... and finally disactivate the "/*!...*/" syntax if MySQL < 3.22.07
//        else if ($release < 32270
//                 && ($char == '!' && $i > 1  && $sql[$i-2] . $sql[$i-1] == '/*')) {
//            $sql[$i] = ' ';
//        } // end else if

		// loic1: send a fake header each 30 sec. to bypass browser timeout
		$time1     = time();
		if ($time1 >= $time0 + 30) {
			$time0 = $time1;
			header('X-pmaPing: Pong');
		} // end if
	} // end for

	// add any rest to the returned array
	if (!empty($sql) && ereg('[^[:space:]]+', $sql)) {
		$ret[] = $sql;
	}

	return TRUE;
} // end of the 'PMA_splitSqlFile()' function


function ConnectDatabase() {
global $CFG, $pmldb,$pmldb;
		if(isset($pmldb)) return;
		$pmldb = @mysql_connect($CFG['DatabaseAdress'], $CFG['DatabaseUser'], $CFG['DatabasePass']);
		if (!$pmldb)
				die($GLOBALS['strCantConnect'] . "<br>Edit config.inc.php and update your connection-settings!");
		mysql_select_db($CFG['DatabaseName'], $pmldb); 
}

function GetValidLink($Dat) {
		if(strstr($Dat,"<a href=\"")) {
				$Pos = strpos($Dat,"<a href=\"");
				$Dat = substr($Dat,$Pos+9);
				$Dat = substr($Dat,0,strpos($Dat,"\""));
		}
		return($Dat);
}

function GetRightsCode() {
	global $CFG, $pmldb, $ActiveUser, $ActiveList;
	if($ActiveUser['admin']==1) {
		return(array("Permissions"=>PML_Rights_SuperAdmin, "Fetch"=>1));
	}

	if($CFG['ListType']==2) {
		//Single-User-Mode -> Anderer als Super-Admin hat immer View-Rechte!
		return(array("Permissions"=>PML_Rights_View, "Fetch"=>0));
	}
	if($CFG['ListType']==1) {
		//Simple-Mode
		//Wenn Ersteller der aktiven liste eingeloggt ist, dann hat er Super-Admin-Rechte, wenn nicht dann view-Rechte
		if($ActiveList['UserID']==$ActiveUser['ID']) {
			return(array("Permissions"=>PML_Rights_ListAdmin, "Fetch"=>1));
		} else {
			return(array("Permissions"=>PML_Rights_View, "Fetch"=>0));
		}
	}
	
	if($ActiveList['ID']==0) { //is any list active?`
		return(array("Permissions"=>PML_Rights_None, "Fetch"=>0)); //no rights found ;-(
	}

	//check in userrights
	if($GLOBALS['ConfigVerBuild'] < 980) {
		//if below build 980 there is not fetch-field
		$strSql = "SELECT Permissions, 1 FROM " . $CFG['Prefix'] . "userrights WHERE UserID='$ActiveUser[ID]' AND ListID='$ActiveList[ID]'";
	} else {
		$strSql = "SELECT Permissions, FetchRights FROM " . $CFG['Prefix'] . "userrights WHERE UserID='$ActiveUser[ID]' AND ListID='$ActiveList[ID]'";
	}
	$result = pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
	if($row = mysql_fetch_row($result)) {
		return(array("Permissions"=>$row[0], "Fetch"=>$row[1]));
	}

	//if below build 980 we don't have usergroups
	if($GLOBALS['ConfigVerBuild'] < 980) return(0);

    //check in usergroups
    $strSql = "SELECT Permissions, FetchRights
                FROM $CFG[Prefix]user2group u2g,
                     $CFG[Prefix]usergroup g, $CFG[Prefix]group2list g2l
                WHERE u2g.UG_ID = g.UG_ID
                AND   g.UG_ID   = g2l.UG_ID
                AND   g2l.L_ID  = '$ActiveList[ID]'
                AND   u2g.U_ID    = '$ActiveUser[ID]'
                ORDER BY Permissions DESC
                LIMIT 1";
    $result = pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
    if($row = mysql_fetch_row($result)) {
        return(array("Permissions"=>$row[0], "Fetch"=>$row[1]));
    }
	return(array("Permissions"=>PML_Rights_None, "Fetch"=>0)); //no rights found ;-(
}


/**
* html_decode: get rid of html entities (e.g. for printcover.php)
*
* @param string String to decode.
* @return string decoded String.
*/
function html_decode($string) {
 
 /* from php.net/get_html_translation_table */
  $trans_tbl = get_html_translation_table (HTML_ENTITIES);
  $trans_tbl = array_flip ($trans_tbl);
  $ret = strtr ($string, $trans_tbl);
  return preg_replace('/&#(\d+);/me',
	 "chr('\\1')",$ret);
}

/**
* FileExists: checks if a file/dir exists, this functions adds getcwd() if it is no absolute path
*             (has to be done for some php-versions)
*
* @param string FileName   name of the file
* @return bool            if the file exists or not
*/
function FileExists($FileName) {
	 //for absolute paths:
	if(file_exists($FileName))
		return(true);
	//then try it with getcwd()
	if(file_exists(getcwd() . "/" . $FileName))
		return(true);
	//else: file doesn't exist...
	return(false);
}

/**
* IsWriteable: checks if a file/dir is writeable, this functions adds getcwd() if it is no absolute path
*             (has to be done for some php-versions)
*
* @param string FileName   name of the file
* @return bool            if the file exists or not
*/
function IsWriteable($FileName) {
	 //for absolute paths:
	if(is_writeable($FileName))
		return(true);
	//then try it with getcwd()
	if(is_writeable(getcwd() . "/" . $FileName))
		return(true);
	//else: file doesn't exist...
	return(false);
}

/**
* GetPrettyFileSize: creates a human-readable file-size (xxx MB)
*
* @param int FileSize	Size of the file (in Bytes)
* @return string		size in human-readable-format
*/
function GetPrettyFileSize($FileSize, $kShortCut=0) {
	$ShortCuts = array("Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB");
	if($FileSize>1024 && ($kShortCut+1)<sizeof($ShortCuts)) {
		$FileSize=$FileSize/1024;
		$kShortCut++;        
		return(GetPrettyFileSize($FileSize, $kShortCut));
	} else {
		if($FileSize<10) {            
			$Dat = round($FileSize, 1);
		} else
			$Dat = round($FileSize);
		$Dat .= " ".$ShortCuts[$kShortCut];
		return($Dat);
	}
}

/**
* GetPrettyDate: like the function date, but works also with dates before 1970
*                this function uses the mysql-function DATE_FORMAT - so you have to use
*                the format-functions from mysql...
*
* @param	string	$Date			the date that has to be converted, format 0000-00-00 00:00:00 (from mysql)
*			string	$FormatString	the format-string
* @return	string					a pretty date...
*/
function GetPrettyDate($Date,$FormatString) {
global $pmldb;
	if($Date=="0000-00-00" || $Date=="0000-00-00 00:00:00") 
		return("");
	if($FormatString=="") $FormatString = $GLOBALS['strDefaultDateFormat']; //load the default-date-format for this language

	$strSql = "SELECT DATE_FORMAT('$Date','$FormatString')";
	$resultDat = pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);		
	$x = mysql_fetch_row($resultDat);
	return $x[0];
}

/**
* PrintExecTime: Prints out the time php needed to interpret the script till now
*                used in bottom.html, but can be used anywhere else for debugging...
*
* @param	none
* @return	nothing
*/
function PrintExecTime() {
global $StartTime;
    if(isset($StartTime)) {
        echo "execution time: ";
        $endtime            = microtime();
        $parts_of_starttime = explode(' ', $StartTime);
        $starttime          = $parts_of_starttime[0] + $parts_of_starttime[1];
        $parts_of_endtime   = explode(' ', $endtime);
        $endtime            = $parts_of_endtime[0] + $parts_of_endtime[1];
        $time_taken         = $endtime - $starttime;
        $time_taken         = number_format($time_taken, 2);  // optional
        print $time_taken;
        if($time_taken>60)
        {
            echo round($time_taken/60) . " Min)\n";
        }
        echo "Sec<br>";
    }
}
/**
* getmicrotime: returns the current microtime() as a float-var (not string like microtime())
*
* @param	none
* @return	microtime
*/
function getmicrotime(){ 
   list($usec, $sec) = explode(" ",microtime()); 
   return ((float)$usec + (float)$sec); 
}

/**
* DownloadFile: Downloads the specified Url and saves it local under
*               $LocalFileName
*
* @param	string   $Url            the Url that has to be downloaded
*           string   $LocalFileName  the filename where to save the data
* @return	boolean  if sucessfull or not...
*/
function DownloadFile($Url,$LocalFileName) {        
	$Url = str_replace(' ', '%20', $Url);
	if($Url=="") return(true);

	if(!($filehandle = fopen($LocalFileName,'wb')))
		return(false);

	$u = parse_url($Url);
	if(!isset($u['port']) || $u['port']=="") $u['port']="80";
	$fp = fsockopen($u['host'], $u['port']);
	if(!$fp) return(false);
	$out = "GET $Url HTTP/1.0\r\n"
		  ."User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)\r\n"
		  ."Host: $u[host]\r\n"
		  ."Connection: close\r\n\r\n";
	fputs($fp, $out);
	$endOfHeader = false;
	$data = "";
	while(!feof($fp)) {
		$data .= (fread($fp,1024));
	}
	$data = substr($data, strpos($data, "\r\n\r\n")+4); //strip http-header
	fwrite($filehandle, $data);

	fclose($fp);
	fclose($filehandle);
	return(true);
}


/**
* GetFileName: returns the filename of the url
*
* @param	string   $Url            the url
*           bool     $verbose        should the error messages be printed ot
* @return	string	 the file name, "" if unsuccessful
*/
function GetFileName($Url, $verbose=true) {
	//the url is saved, and the file is saved local
	// in Cache/$MovieID."-".$Prop['ID']."-".urlfilename
	if($Url=="") return("");
	$Dat = parse_url($Url);		
	if(!isset($Dat['path'])) {
		if($verbose) echo "<b>$GLOBALS[strErrError]:</b> $GLOBALS[strInvalidUrl] (" . $Url . ")<br>\n";
		return("");
	}
	$Dat = $Dat['path'];
	$Pos = strrpos($Dat,"/");
	if($Pos === false) {
		if($verbose) echo "<b>$GLOBALS[strErrError]:</b> $GLOBALS[strInvalidUrl] (" . $Url . ")<br>\n";
		return("");
	} else {
		$Dat = substr($Dat, $Pos+1);
		return($Dat);
	}
}

/**
* GetFileNameDelem: returns the filename of the url - checks too if the filename is saved after the Delem-char
*
* @param	string   &$Url            the url <- as reference!
*           bool     $verbose        should the error messages be printed ot
* @return	string	 the file name, "" if unsuccessful
*/
function GetFileNameDelem(&$Url, $verbose=true) {
	//get the local-filename:
	//it is either the filename of the url
	//or when http://www.xxx.com/xxx.xxx.PML_PropertyDelem.localfilename.jpg  the added name
	if($Pos=strpos($Url, PML_PropertyDelem)) {
		$ret = substr($Url, $Pos+1); //ret is the local-filename
		$Url = substr($Url, 0, $Pos); //the url itself        
	} else {        
		$ret = GetFileName($Url,$verbose); //or esle get it from the url itself (false=be silent)
	}
	return($ret);
}

/**
* GetStandardValue: gets the standard-value for a given PropID
*                   warning: works for most property types
*
* @param	int		$PropID		the PropID...
* @param	int		$PropType	the PropType (default is text)
* 
* @return	string	the standard-value
*/
function GetStandardValue($Prop) {
global $CFG, $pmldb, $ActiveList;
static $stdVal=array();
	$PropID = $Prop['ID'];
	$PropType = $Prop['PropType'];
	if(isset($stdVal[$PropID]) && ($PropType!=PML_PropType_AutoIncrement))	return($stdVal[$PropID]);

	// retreive default value from db
	$ret="";
	switch ($PropType){
		case PML_PropType_Text:
		case PML_PropType_Textfield:
		case PML_PropType_Url:
		case PML_PropType_Date:
            $strSql = "SELECT `$Prop[Name]` AS Property FROM $CFG[Prefix]movies_$ActiveList[name] WHERE MovieID='0'";
			$result = pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);   
			if(mysql_num_rows($result)) {
				$row = mysql_fetch_array($result, MYSQL_ASSOC);
				$ret = $row['Property'];
			}
			break;
		case PML_PropType_AutoIncrement:	// auto-incremented value
			if (isset($stdVal[$PropID])){
				$ret=$stdVal[$PropID]+1;
			}
			else {
				//Property+0 converts a string to a number - so invalid strings get 0
	            $strSql = "SELECT MAX(`$Prop[Name]`)+1 AS Property FROM $CFG[Prefix]movies_$ActiveList[name]";
				$q = pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
				$r = mysql_fetch_assoc($q);
				$ret = $r['Property'];
				if (is_null($ret)) $ret = 1;
			}
			break;
		case PML_PropType_Boolean:
		case PML_PropType_ListBox:
		case PML_PropType_ListBoxMulti:
            $strSql = "SELECT `$Prop[Name]` AS Property FROM $CFG[Prefix]movies_$ActiveList[name] WHERE MovieID='0'";
			$q = pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);	
			$Sel = mysql_fetch_array($q, MYSQL_ASSOC);
			$Sel = $Sel['Property'];
			if($Prop['PropType']==PML_PropType_ListBoxMulti) {
				if(substr($Sel, 0, 1)=="_") $Sel = substr($Sel, 1);
				if(substr($Sel, -1)=="_") $Sel = substr($Sel, 0, -1);
				$ret = explode("_", $Sel);
			} else {
				$ret = array($Sel);
			}
			break;
	}

	$stdVal[$PropID] = $ret;
	return($ret);
}

/**
* loads the prop table into $PropAll (global!)
*
* checks if it is allrady loaded and doesn't load it again
*
* @param	int the ListID PropAll should be loaded for (if not given the activelist will be used)
* @return	nothing
*/
function LoadPropAll($ListID=0) {
global $CFG, $pmldb, $PropAll, $PropNames, $ActiveList;
static $PropAllLoadedListID=0;
	if($ListID==0) $ListID=$ActiveList['ID'];
	if($PropAllLoadedListID==$ListID) return;
	$strSql = "SELECT * FROM $CFG[Prefix]prop WHERE ListID=$ListID ORDER BY SortOrder ASC";
	$result = pml_mysql_unbuffered_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
	$PropAll = $PropNames = array();	
	while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
		$PropAll[$row['ID']] = $row;
		$PropAll[$row['ID']]['Loaded'] = false;
		$PropNames[$row['Name']] = $row['ID'];
		$PropAll[$row['ID']]['FetchScripts'] = array();
	}
	$PropAllLoadedListID=$ListID;
}

/**
* loads the propfetch table into $PropAll (global!)
*
* checks if it is allrady loaded and doesn't load it again
* checks if prop-table is allready loaded, if not it reloads it
*
* @param	int the ListID PropAll should be loaded for (if not given the activelist will be used)
* @return	nothing
*/
function LoadPropFetchScripts($ListID=0) {
global $CFG, $pmldb, $PropAll, $PropNames, $ActiveList;
static $PropFetchScriptsLoadedListID=0;
	LoadPropAll($ListID); //first make sure that PropAll is loaded
	if($ListID==0) $ListID=$ActiveList['ID'];
	if($PropFetchScriptsLoadedListID==$ListID) return; //don't load again if allready loaded

	$strSql = "SELECT $CFG[Prefix]propfetch.* FROM $CFG[Prefix]propfetch, $CFG[Prefix]prop WHERE $CFG[Prefix]prop.ID=$CFG[Prefix]propfetch.PropID AND $CFG[Prefix]prop.ListID=$ListID ORDER BY $CFG[Prefix]propfetch.SortOrder ASC";
	$result = pml_mysql_unbuffered_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);  
	while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
		$PropAll[$row['PropID']]['FetchScripts'][$row['ID']] = $row;
	}
	$PropFetchScriptsLoadedListID=$ListID;
}

/**
* LoadStatistics: loads the statistics for the current list
*                 the data should be cached by smarty, as it
*                 takes several sql-queries to get the data
* @param	nothing...
* 
* @return	array  the statistic-data
*/
function LoadStatistics() {
global $Active, $CFG, $pmldb, $ActiveList, $usr;
	if($Active!="index")
		$sqlWhere = "$CFG[Prefix]movies.ListID=$ActiveList[ID]";
	else
		$sqlWhere = "1";

	$strSql = "SELECT COUNT(*) FROM $CFG[Prefix]movies WHERE $sqlWhere";
	$result = pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);		
	$row = mysql_fetch_row($result);
	$Statistics['entries'] = $row[0];

	$strSql = "SELECT COUNT(*) FROM $CFG[Prefix]movies WHERE $sqlWhere AND DateAdded BETWEEN '".date("Y-m-d")." 00:00:00' AND '".date("Y-m-d H:i:s")."'";
	$result = pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);		
	$row = mysql_fetch_row($result);
	$Statistics['addedtoday'] = $row[0];

	$strSql = "SELECT COUNT(*) FROM $CFG[Prefix]movies WHERE $sqlWhere AND DateAdded BETWEEN '".date("Y-m-d",mktime (0,0,0,date("m")  ,date("d")-1,date("Y")))." 00:00:00' AND '".date("Y-m-d",mktime (0,0,0,date("m")  ,date("d")-1,date("Y")))." 23:59:59'";
	$result = pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);		
	$row = mysql_fetch_row($result);
	$Statistics['addedyesterday'] = $row[0];

	$Statistics['users'] = $usr->GetUserCount();

	$strSql = "SELECT COUNT(*) FROM $CFG[Prefix]lists WHERE name!='index'";
	$result = pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);		
	$row = mysql_fetch_row($result);
	$Statistics['lists'] = $row[0];

	return($Statistics);
}

/**
* Load PropPreSettings and exported PropSettings
*
* loads pml_prop values
* all movie-data will be lost! - and existing data will not be backuped or deleted so a lot of garbage will be there
* !!! call it ONLY when creating new lists, or when importing presettings (bevore that delete all entries) !!!
*
* @param int ID of the list
* @param array setting to load
* @return	array  the fetch-fieldss
*/
function LoadPropPreSetting($ListID, $PropData) {	
global $CFG, $pmldb, $strPresettingsText;

	$strSql = "SELECT name FROM $CFG[Prefix]lists WHERE ID='$ListID'";
	$q = pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
	$r = mysql_fetch_assoc($q);
	$ListName = strtolower($r['name']);


	$TranslationAvaliable = array_keys($strPresettingsText);

	foreach($PropData['prop'] as $kProp=>$Prop) {
		//translation:
		if(in_array($Prop['InTitle'],$TranslationAvaliable)) 
			$Prop['InTitle'] = $strPresettingsText[$Prop['InTitle']];
		if(in_array($Prop['ListHeader'],$TranslationAvaliable)) 
			$Prop['ListHeader'] = $strPresettingsText[$Prop['ListHeader']];

		foreach($Prop as $k=>$i) {
			$Prop[$k]=addslashes($Prop[$k]);		
		}

		//compatibily with old versions:
		if(!isset($Prop['ShowAdd']) && isset($Prop['FetchScript'])) {
			if($Prop['FetchScript']=="") $Prop['ShowAdd']=1; else $Prop['ShowAdd']=0;
		}

		$strSql = "INSERT INTO $CFG[Prefix]prop (ListID, Name,          SortOrder,          PropType,          InTitle,          InProp,          ShowInList,          ListHeader,          UseSort,          ListProperties,          Url,          ShowFilter,          ShowInPopUp,          ShowOnCover,          ShowLinkType,          RequiredRights,          ShowAdd)
										VALUES ($ListID, '$Prop[Name]', '$Prop[SortOrder]', '$Prop[PropType]', '$Prop[InTitle]', '$Prop[InProp]', '$Prop[ShowInList]', '$Prop[ListHeader]', '$Prop[UseSort]', '$Prop[ListProperties]', '$Prop[Url]', '$Prop[ShowFilter]', '$Prop[ShowInPopUp]', '$Prop[ShowOnCover]', '$Prop[ShowLinkType]', '$Prop[RequiredRights]', '$Prop[ShowAdd]')";
		pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
		$PropData['prop'][$kProp]['ID'] = mysql_insert_id();

        //new db-structure
        $fieldType = getFieldTypeByPropType($Prop['PropType']);
        if(is_array($fieldType)) {
            foreach($fieldType as $field=>$typ) {
                $strSql = "ALTER TABLE $CFG[Prefix]movies_$ListName ADD `{$Prop['Name']}_$field` $typ NOT NULL";
				pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
            }
        } else if ($fieldType!="") {
            $strSql = "ALTER TABLE $CFG[Prefix]movies_$ListName ADD `{$Prop['Name']}` $fieldType NOT NULL";
			pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
        }
        
	}

    $strSql = "REPLACE INTO $CFG[Prefix]movies_$ListName SET MovieID=0";
	pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);        

	foreach($PropData['movieprop'] as $kMovieProp=>$MovieProp) {
		//translation:
		if(in_array($MovieProp['Property'],$TranslationAvaliable)) 
			$MovieProp['Property'] = $strPresettingsText[$MovieProp['Property']];
		
		if(!isset($PropData['prop'][$MovieProp['PropKey']]['ID'])) continue;
		$strSql = "UPDATE $CFG[Prefix]movies_$ListName SET `".$PropData['prop'][$MovieProp['PropKey']]['Name']."`='".addslashes($MovieProp['Property'])."' WHERE MovieID='0'";
		pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);        
	}

	foreach($PropData['propval'] as $kPropVal=>$PropVal) {
		//translation:
		if(in_array($PropVal['DisplayText'],$TranslationAvaliable)) 
			$PropVal['DisplayText'] = $strPresettingsText[$PropVal['DisplayText']];
		if(in_array($PropVal['DisplayTextShort'],$TranslationAvaliable)) 
			$PropVal['DisplayTextShort'] = $strPresettingsText[$PropVal['DisplayTextShort']];

		if(!isset($PropData['prop'][$PropVal['PropKey']]['ID'])) continue;
		$Dat = $PropData['prop'][$PropVal['PropKey']]['ID'];
		foreach($PropVal as $k=>$i)
			$PropVal[$k]=addslashes($PropVal[$k]);
		if(!isset($PropVal['DisplayTextHtml'])) $PropVal['DisplayTextHtml']="";
		if(!isset($PropVal['SortText'])) $PropVal['SortText']="";
		$strSql = "REPLACE INTO $CFG[Prefix]propval (PropID, DisplayText,             DisplayTextShort,             DisplayTextHtml,             FetchText,             Value,             SortText,             SortOrder)
									VALUES          ('$Dat', '$PropVal[DisplayText]', '$PropVal[DisplayTextShort]', '$PropVal[DisplayTextHtml]', '$PropVal[FetchText]', '$PropVal[Value]', '$PropVal[SortText]', '$PropVal[SortOrder]')";
		pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
		$PropData['propval'][$kPropVal]['ID'] = mysql_insert_id();

		//save StdFilterPropValID
		foreach($PropData['prop'] as $kProp=>$Prop) {
			if(isset($Prop['StdFilterPropValKey']) && $Prop['StdFilterPropValKey']!=0 && $Prop['StdFilterPropValKey']==$kPropVal) {
				$strSql = "UPDATE $CFG[Prefix]prop SET StdFilterPropValID='".$PropData['propval'][$kPropVal]['ID']."' WHERE PropID='$Prop[ID]'";
				pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
			}
		}
	}

	$ListBoxMultiPropKeys = array();
	foreach($PropData['moviepropval'] as $kMoviePropVal=>$MoviePropVal) {
		if(!isset($PropData['propval'][$MoviePropVal['PropValKey']]['ID'])) continue;
		$Prop = $PropData['prop'][$PropData['propval'][$MoviePropVal['PropValKey']]['PropKey']];
		$PropKey = $PropData['propval'][$MoviePropVal['PropValKey']]['PropKey'];
		if($Prop['PropType']==PML_PropType_ListBoxMulti) {
			$ListBoxMultiPropKeys[$PropKey][] = $PropData['propval'][$MoviePropVal['PropValKey']]['ID'];
		} else if($Prop['PropType']==PML_PropType_Boolean || $Prop['PropType']==PML_PropType_ListBox) {
			$Dat = $PropData['propval'][$MoviePropVal['PropValKey']]['ID'];
			$strSql = "UPDATE $CFG[Prefix]movies_$ListName SET `".$Prop['Name']."`='".addslashes($Dat)."' WHERE MovieID='0'";
			pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
		}

	}
	foreach($ListBoxMultiPropKeys as $PropKey=>$Dat)
	{
		$Dat = "_".implode("_", $Dat)."_";
		$strSql = "UPDATE $CFG[Prefix]movies_$ListName SET `".$PropData['prop'][$PropKey]['Name']."`='".addslashes($Dat)."' WHERE MovieID='0'";
		pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
	}

	if(isset($PropData['propfetch'])) {
		foreach($PropData['propfetch'] as $kPropFetch=>$PropFetch) {
			$Dat = $PropData['prop'][$PropFetch['PropKey']]['ID'];
			foreach($PropFetch as $k=>$i)
				$PropFetch[$k]=addslashes($PropFetch[$k]);
			$strSql = "INSERT INTO $CFG[Prefix]propfetch (PropID, FetchScript, SortOrder, Settings) VALUES ('$Dat','$PropFetch[FetchScript]','$Prop[SortOrder]','$PropFetch[Settings]')";
			pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
		}
	} else {
		//for compatibility with old pmlset-versions import the FetchScript from prop
		foreach($PropData['prop'] as $kProp=>$Prop) {
			if(isset($Prop['FetchScript']) && $Prop['FetchScript']!="") {
				$Dat = $PropData['prop'][$kProp]['ID'];
				$strSql = "INSERT INTO $CFG[Prefix]propfetch (PropID, FetchScript, SortOrder, Settings) VALUES ('$Dat','$Prop[FetchScript]','1','')";
				pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
			}
		}
	}
}

/**
* SendActivationMail: sends the activation-email for a given user
*
* @param	array array containing all required user-information
* @return	boolean if successfull sent
*/
function SendActivationMail($User) {
global $ActiveList, $CFG, $pmldb;
	$MailFileName = "activateuser";

	if(FileExists("mail/$MailFileName.$ActiveList[lang].txt"))
		$MailFileName = "mail/$MailFileName.$ActiveList[lang].txt";
	else
		$MailFileName = "mail/$MailFileName.english.txt"; //use the default-file

	$MailSubject = "Registration Confirmation"; //default Value
	$MailData = file($MailFileName);
	foreach($MailData as $k=>$Line) {
		$MailData[$k] = trim($MailData[$k]);
		$MailData[$k] = str_replace("_ACTIVATEURL_", "$CFG[HttpPath]activate.php?a=$User[activate]&ID=$User[ID]", $MailData[$k]);
		$MailData[$k] = str_replace("_HTTPPATH_", "$CFG[HttpPath]", $MailData[$k]);
		$MailData[$k] = str_replace("_USERNAME_", "$User[name]", $MailData[$k]);
		if($MailData[$k]!="" && strstr($MailData[$k],"Subject: ")==$MailData[$k]) {
			$MailSubject =  str_replace("Subject: ", "", $MailData[$k]);
			$MailSubject =  $MailData[$k];
			unset($MailData[$k]); //delete this line
		}
	}
	echo "$GLOBALS[SendingActivationEMail]<br>\n";
	if($CFG['Debug']) {
		echo "<pre>";
		echo "To: $User[email]\nSubject: $MailSubject\nFrom: $CFG[AdminEmail]\n";
		echo "\n";
		echo implode("\n", $MailData);
		echo "</pre>";
	}
	if(!mail($User['email'], $MailSubject, implode("\n", $MailData),"From: $CFG[AdminEmail]")) {
		echo "Failed sending activation-email! Please contact the system-admin!<br>";
		return(false);
	}
	return(true);
}


/**
* GetMovieTitle
*
* gets the Title of a movie. The FetchTextProperty defined in main-config will be returned
* as this is usually the Title of the entry.
*
* @param int the ID of the movie
* @param int the ID of the list, if 0 or not set the current list will be used
* 
* @return	text: the title of the movie
*/
function GetMovieTitle($MovieID, $ListID=0) {
global $CFG, $pmldb, $PropAll, $ActiveList;
	LoadPropAll($ListID);
	if($ActiveList['ID']!=$ListID && $ListID!=0) {
		$strSql = "SELECT FetchTextPropID, name FROM $CFG[Prefix]lists WHERE ID='$ListID'";
		$result = pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
		$row = mysql_fetch_assoc($result);
		$PropID = $row['FetchTextPropID'];
        $ListName = $row['name'];
	} else {
		$PropID = $ActiveList['FetchTextPropID'];
        $ListName = $ActiveList['name'];
	}

	$ret = ReadMovieDataFromDb("prop", array("MovieID"=>$MovieID, "PropID"=>$PropID), "long", $ListName);
	return($ret['Data'][$MovieID][$PropAll[$PropID]['Name']]);
}


/**
* AddListActions
*
* this functions does all the actions requried when creating a new list
* it will be mainly called from editlist when doing addsave
* AND, when CFG[ListType] = simple-mode (1) from edituser too
*
*/
function AddListActions() {
global $ActiveUser, $CFG, $pmldb, $ID;

	if($CFG['ListType']!=1) {
		$UserID = $ActiveUser['ID'];
		$ListID = $ID;
	} else {
		$UserID = $ID;
		$ListID = $GLOBALS['ListID'];
	}

	//check if the .htaccess is configured properly so that the list can be accessed directly over /listname
	//if this returns not a 302 we must use list.php?Active=listname
	$Dat="";
	$fp=@fsockopen($_SERVER['SERVER_NAME'], $_SERVER['SERVER_PORT']);
	if ($fp) {
	   fputs ($fp, "GET $CFG[HttpPath]$_POST[name] HTTP/1.0\r\n\r\n");
	   while (!feof($fp)) {
		   $Dat.=fgets ($fp,128);
	   }
	   fclose ($fp);
	}    
	//check if 302 or not
	if(preg_match('#^HTTP/1.[0-1]{1} 302#', $Dat))
		$ListUrl = "$CFG[HttpPath]$_POST[name]";
	else
		$ListUrl = "$CFG[HttpPath]list.php?Active=$_POST[name]";
	
	//load some standard-values:
	$strSql = "UPDATE $CFG[Prefix]lists SET designcss='default.css', listtpl='list.tpl', popuptpl='popup.tpl', url='".addslashes($ListUrl)."', urlname='".addslashes(htmlentities($ListUrl))."' WHERE ID=$ListID";
	pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);


    //benutzer bei linkliste hinztufgen
	$strSql = "SELECT SortOrder FROM " . $CFG['Prefix'] . "linklist ORDER BY SortOrder DESC";
	$result = pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
	$row = mysql_fetch_assoc($result);
	$inSortOrder = $row['SortOrder']+1;
	
	$strSql = "INSERT INTO " . $CFG['Prefix'] . "linklist (Type, ListID, Url, Text, SortOrder) VALUES ('User', '" . $ListID . "', '', '$_POST[title]', '$inSortOrder')";
	pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);

	//eingeloggten benutzer List-Admin-Rechte geben:
	$strSql = "INSERT INTO " . $CFG['Prefix'] . "userrights (UserID, ListID, Permissions) VALUES ('$UserID', '$ListID', '".PML_Rights_ListAdmin."')";
	pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);

    //add list to default-usergroup
    $strSql = "SELECT UG_ID FROM $CFG[Prefix]usergroup WHERE IsDefault=1";
    $result = pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
    $row = mysql_fetch_row($result);
    $UG_ID = $row[0];
    $strSql = "INSERT INTO $CFG[Prefix]group2list (UG_ID, L_ID, Permissions) VALUES ('$UG_ID', '$ListID', '".PML_Rights_View."')";
    pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);

	if($CFG['LinkListType']==PML_LinkListType_Fav || $CFG['LinkListType']==PML_LinkListType_FavText) {
		//add list to favourites:
		$strSql = "SELECT SortOrder FROM $CFG[Prefix]fav WHERE UserID='$ActiveUser[ID]' ORDER BY SortOrder ASC";
		$result=pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
		$row=mysql_fetch_assoc($result);
		$newSortOrder = $row['SortOrder']+1;
		$strSql = "REPLACE INTO $CFG[Prefix]fav (UserID, ListID, SortOrder) VALUES ('$ActiveUser[ID]', '$ListID', '$newSortOrder')";
		pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
		echo "$GLOBALS[strAddedListToYourFav]...<br>\n";
	}
    
    $table = $CFG['Prefix']."movies_".strtolower($_POST['name']);
    $strSql = "CREATE TABLE $table (
        MovieID BIGINT NOT NULL PRIMARY KEY,
        DateAdded datetime NOT NULL default '0000-00-00 00:00:00',
        DownloadCount int(11) NOT NULL default '0',
        UserAddedID INT DEFAULT '0' NOT NULL)";
    pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);

    
	//iimport presettings:
	$FileName = "presettings/".$_POST['presetting'];
	do { //do this on a do while(0) loop - so we can break it anywhere...
		if(!FileExists($FileName)) {
			echo "<b>ERROR:</b> can't import presettings, as the file doesn't exist...<br>";
			break;
		}
	
		$data = "";
		$fp = @gzopen ($FileName, "rb");		
		if(!$fp) {
			echo "<b>ERROR:</b> can't open presetting-file...<br>";
			break;
		}
		while(!gzeof($fp))
			$data .= (gzread($fp,1024));
		gzclose ($fp); 

		$InData = @unserialize($data);  //unserialize (unpack) it
		if(!$InData) {
			echo "<b>ERROR:</b> can't import presettings, as the selected file ($FileName) is an invalid .pmlset-file - contact the admin!<br>";
			break;
		}

		//check version compatibility        
		if($InData['ExportVersion'] > $GLOBALS['ExportSettingsVersion']) {
			echo "<b>ERROR</b>: The selected presetting-file has been generated with version $InData[version] (Build $InData[VerBuild]). Please update to the most current version to use this file.<br>no presettings imported...";
			break;
		}
		
		if(!isset($InData['prop'])) {
			echo "<b>ERROR:</b> The selected-presetting-file doesn't include any presettings!<br>";
			break;
		}
		LoadPropPreSetting($ListID, $InData);
		echo "$GLOBALS[strPresettingsImported]...<br>\n";
	} while (0);

	//output the path
	echo "<b>$GLOBALS[strYouCanAccessTheListDirectlyOver] <a href='$ListUrl'>".htmlentities($ListUrl)."</a></b><br><br>";
	
	echo str_replace("%url%", "list.php".$GLOBALS['GlobalArgWOActive']."Active=" . $_POST['name'], $GLOBALS['strClickHereToGoToYourNewList']);

}

/**
* GetFetchText: returns the text that should be used for the fetch-scripts
*               what entry used is defined in the configuration
*               only works for ActiveList
*/
function GetFetchText($MovieID, $ListID=0) {
global $ActiveList, $CFG, $pmldb, $PropAll;
    if($ListID==0) $ListID=$ActiveList['ID'];
	if($ListID!=$ActiveList['ID']) {
		$strSql = "SELECT * FROM $CFG[Prefix]lists WHERE ID='$ListID'";
		$q = pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
		$list = mysql_fetch_assoc($q);
	} else {
		$list = $ActiveList;
	}
	LoadPropAll($ListID);
	if(isset($PropAll[$list['FetchTextPropID']])) {
		$Prop = $PropAll[$list['FetchTextPropID']];
	} else {
		//not found, use the first text-item
		foreach($PropAll as $Prop) {
			if($Prop['PropType']==PML_PropType_Text) break;
		}
	}

	$strSql = "SELECT `$Prop[Name]` FROM $CFG[Prefix]movies_$list[name] WHERE MovieID='$MovieID'";
	$q = pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
	$r = mysql_fetch_array($q,MYSQL_NUM);
	return($r[0]);
}

/**
* insert_ActiveUserName: smarty-insert-function
*                        called from list.php and index.php when displaying the list
*                        this must be a insert-function, because insert's wont be cached!
*/
function insert_ActiveUserName($params) {
	global $ActiveUser;
	return $ActiveUser['name'];
}
/**
* insert_ActiveUserRights: smarty-insert-function
*                          called from list.php and index.php when displaying the list
*                          this must be a insert-function, because insert's wont be cached!
*/
function insert_ActiveUserRights($params) {
	global $ActiveUserRights, $strUserRights;
	return $strUserRights[$ActiveUserRights];
}
/**
* insert_UserMenu: smarty-insert-function
*                  called from list.php and index.php when displaying the list
*                  this must be a insert-function, because insert's wont be cached!
*/
function insert_UserMenu($params) {
	extract($params);
	return(GetUserMenu($design));
}

/**
* insert_CounterTotal: smarty-insert-function
*                      called from list.php and index.php when displaying the list
*                      this must be a insert-function, because insert's wont be cached!
*/
function insert_CounterTotal($params) {
global $Counter;
	return($Counter['Total']);
}

/**
* insert_CounterOnline: smarty-insert-function
*                       called from list.php and index.php when displaying the list
*                       this must be a insert-function, because insert's wont be cached!
*/
function insert_CounterOnline($params) {
global $Counter;
	return($Counter['Online']);
}

/**
* insert_CounterMaxOnline: smarty-insert-function
*                          called from list.php and index.php when displaying the list
*                          this must be a insert-function, because insert's wont be cached!
*/
function insert_CounterMaxOnline($params) {
global $Counter;
	return($Counter['MaxOnline']);
}

/**
* insert_OnlineUsers: smarty-insert-function
*                     called from list.php and index.php when displaying the list
*                     this must be a insert-function, because insert's wont be cached!
*/
function insert_OnlineUsers($params) {
global $Active,$Counter;
	extract($params);
	if(!isset($Counter['Users'])) $Counter['Users'] = GetOnlineUsers();
	$ret = "";
	foreach($Counter['Users'] as $Dat) {
		if($Dat['name']=="Guest") continue;
		$out = str_replace("_Text", $Dat['name'], $design);
		$ret .= str_replace("_Url", $GLOBALS['usr']->GetUserDetailsLink($Dat['ID']), $out);
	}
	return($ret);
}

/**
* insert_CounterGuestsOnline: smarty-insert-function
*                             called from list.php and index.php when displaying the list
*                             this must be a insert-function, because insert's wont be cached!
*/
function insert_CounterGuestsOnline($params) {
global $Counter;
	if(!isset($Counter['Users'])) $Counter['Users'] = GetOnlineUsers();
	return($Counter['Users'][0]['Count']);
}

/**
* SendDownloadFile: sends the given data as a download-file to the browser
*                   it should send the right headers for the specific brwosers
*                   (functions copied from http://szewo.com/php/mydump/eng/)
*
* @param	string the data of the file
* @param    string the filename sent to the client
* @param    bool   true if this is a binary file
*                  false when a text file... then \n will be replaced to the right line-breaks, depending on the plattform of the client.
* 
* @return	nothing
*/
function SendDownloadFile($Data, $FileName, $Binary=true) {
	if(!$Binary) {
		//replace all \n with the right crlf
		if (strstr($_SERVER['HTTP_USER_AGENT'], 'Win')) {
			$crlf = "\r\n";
		} else if (strstr($_SERVER['HTTP_USER_AGENT'], 'Mac')) {
			$crlf = "\r";
		} else {
			$crlf = "\n";
		}
		$Data = str_replace("\n", $crlf, $Data);
	}

	$HTTP_USER_AGENT = $_SERVER['HTTP_USER_AGENT'];

	if (ereg('Opera(/| )([0-9].[0-9]{1,2})', $HTTP_USER_AGENT)) {
		$USER_BROWSER_AGENT = 'OPERA';
	} else if (ereg('MSIE ([0-9].[0-9]{1,2})', $HTTP_USER_AGENT)) {
		$USER_BROWSER_AGENT = 'IE';
	} else if (ereg('OmniWeb/([0-9].[0-9]{1,2})', $HTTP_USER_AGENT)) {
		$USER_BROWSER_AGENT = 'OMNIWEB';
	} else if (ereg('Mozilla/([0-9].[0-9]{1,2})', $HTTP_USER_AGENT)) {
		$USER_BROWSER_AGENT = 'MOZILLA';
	} else if (ereg('Konqueror/([0-9].[0-9]{1,2})', $HTTP_USER_AGENT)) {
		$USER_BROWSER_AGENT = 'KONQUEROR';
	} else {
		$USER_BROWSER_AGENT = 'OTHER';
	}

	$mime_type = ($USER_BROWSER_AGENT == 'IE' || $USER_BROWSER_AGENT == 'OPERA')
				   ? 'application/octetstream'
				   : 'application/octet-stream';
				   
	$now = gmdate('D, d M Y H:i:s') . ' GMT';
	
	// Send headers
	header('Content-Type: ' . $mime_type);
	header('Expires: ' . $now);
	Header("File-Length: ". strlen($Data));
	// lem9 & loic1: IE need specific headers
	if ($USER_BROWSER_AGENT == 'IE') {
		header('Content-Disposition: inline; filename="' . $FileName . '"');
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		header('Pragma: public');
	} else {
		header('Content-Disposition: attachment; filename="' . $FileName . '"');
		header('Pragma: no-cache');
	}

	//and now print out the file itself:
	echo $Data;
}

/**
* read announcments from database for active list
*
* @todo add dateon dateoff
* 
* @return	array  the Text
*/
function GetAnnouncments() {
global $CFG, $ActiveList, $pmldb;
	$strSql = "SELECT ID,Text,DateOn,UserID FROM $CFG[Prefix]announcment
		WHERE ListID=$ActiveList[ID]
		AND ((UseDate=1 AND NOW() BETWEEN DateOn AND DateOff) OR UseDate=0)
		ORDER BY DateAdded DESC";
	$result = pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
	$ret=array();
	while($row = mysql_fetch_assoc($result)) {
		$ret[$row['ID']] = $row;
	}
	return($ret);
}

/**
* GetFetchFields: returns all avaliable fetch-fields
*                 don't call this function too often, it is some kind of slow
*                 as it has to include every fetch-script found...
*
* @param	none
* 
* @return	array  the fetch-fieldss
*/
function GetFetchFields() {
	include_once("fetch/fetch.php");
	$ret = array();
	$d = dir("fetch/");
	while($entry=$d->read()) {
		if(filetype("fetch/" . $entry)!="file") continue;
		if(substr($entry,-4)!=".php") continue;
		if($entry=="fetch.php") continue;
		$entry=substr($entry,0,strlen($entry)-4);
		$entry=substr($entry,6);
		include_once("fetch/fetch-".$entry.".php");
		if(!class_exists("pmlfetch_".$entry)) {			
			continue;
		}

		$ClassName = "pmlfetch_$entry";
		$FetchClass = new $ClassName;
		foreach($FetchClass->getFieldNames() as $Dat) {
			$ret[] = $entry."-".$Dat;
		}
	}
	$d->close();
	return($ret);
}

//thanks to phlipping at yahoo dot com for this function
function WildToReg($str)
{
  $s = ""; 
  for ($i = 0; $i < strlen($str); $i++)
  {
   $c = $str{$i};
   if ($c =='?')
   $s .= '.'; // any character
   else if ($c == '*')   
   $s .= '.*'; // 0 or more any characters   
   else if ($c == '[' || $c == ']')
   $s .= $c;  // one of characters within []
   else
   $s .= '\\' . $c;
  }
  $s = '^' . $s . '$';

  //trim redundant ^ or $
  //eg ^.*\.txt$ matches exactly the same as \.txt$
  if (substr($s,0,3) == "^.*")
   $s = substr($s,3);
  if (substr($s,-3,3) == ".*$")
   $s = substr($s,0,-3);
  return $s;
}

function loadSmarty()
{
global $smarty, $CFG;

    if(isset($smarty)) return;
    
    require_once(SMARTY_DIR."Smarty.class.php");

    $smarty = new Smarty;

    $smarty->compile_check = true;
    $smarty->debugging = $CFG['Debug'];
    $smarty->compile_dir = $CFG['CompileDir'];
    $smarty->cache_dir = $CFG['SmartyCacheDir'];
    $smarty->use_sub_dirs = $CFG['SmartyUseSubDirs'];
    $smarty->security = $CFG['SmartySecurity'];
    $smarty->secure_dir = array("templates/", "smarty/");
    if(isset($CFG['SmartyCacheHandler']) && $CFG['SmartyCacheHandler']!="" && function_exists($CFG['SmartyCacheHandler'])) {
        $smarty->cache_handler_func = $CFG['SmartyCacheHandler'];
    }        
    if($CFG['UseCache']) {
        $smarty->caching = 2; //each cache can have his individual live-time (index-page has a lower!)
    }
}

function buildSqlString($sql)
{
	$strSql = "SELECT " . implode(", \n", $sql['select'])."\n";
	$strSql .= "FROM " . implode(", ", $sql['from'])."\n";

	if(isset($sql['right join']) && sizeof($sql['right join'])) {
		foreach($sql['right join'] as $table=>$on) {
			$strSql .= "RIGHT JOIN $table ON ";
			if(is_array($on)) $strSql .= implode("\nAND ", $on)."\n";
			else $strSql .= $on."\n";;
		}
	}

	if(isset($sql['left join']) && sizeof($sql['left join'])) {
		foreach($sql['left join'] as $table=>$on) {
			$strSql .= "LEFT JOIN $table ON ";
			if(is_array($on)) $strSql .= implode("\nAND ", $on)."\n";
			else $strSql .= $on."\n";;
		}
	}

	if(isset($sql['where']) && sizeof($sql['where']))
		$strSql .= "WHERE " . implode("\nAND ", $sql['where'])."\n";

	if(isset($sql['group']) && sizeof($sql['group']))
		$strSql .= "GROUP BY " . implode("\n, ", $sql['group'])."\n";
	
	if(isset($sql['order']) && $sql['order']!="")
		$strSql .= "ORDER BY $sql[order]\n";

	if(isset($sql['limit']) && $sql['limit']!="")
		$strSql .= "LIMIT $sql[limit]";

	return($strSql);
}

function getFieldTypeByPropType($PropType) {
	if($PropType>100) return("");
	switch($PropType) {
		case PML_PropType_Text:
			$fieldType = "TEXT";
			break;
		case PML_PropType_Date:
			$fieldType = "DATE";
			break;
		case PML_PropType_Boolean:
			$fieldType = "TINYINT";
			break;
		case PML_PropType_ListBox:
			$fieldType = "INT";
			break;
		case PML_PropType_Textfield:
			$fieldType = "TEXT";
			break;
		case PML_PropType_Url:
			$fieldType = "TINYTEXT";
			break;
		case PML_PropType_UrlCached:
			$fieldType = "TINYTEXT";
			break;
		case PML_PropType_FileUpload:
			$fieldType = "TINYTEXT";
			break;
		case PML_PropType_UserRating:
			$fieldType = "FLOAT";
			break;
		case PML_PropType_DownloadLink:
		case PML_PropType_DownloadLinkFileUpload:
			$fieldType = array("link"=>"TINYTEXT", "text"=>"TINYTEXT", "size"=>"SMALLINT", "dloadcount"=>"INT");
			break;
		case PML_PropType_StaticText:
		case PML_PropType_DisplayNr:
			$fieldType = "";
			break;
		case PML_PropType_AutoIncrement:
			$fieldType = "INT";
			break;
		case PML_PropType_ListBoxMulti:
			$fieldType = "TEXT";
			break;
		default:
			trigger_error("Unknown PropType", E_USER_ERROR);
			break;
	}
	return $fieldType;
}


function ReadMovieDataFromDb($type, $display, $DisplayText, $ListName=null)
{
global $PropAll, $CFG, $pmldb;
    if(!isset($ListName)) {
        $ListName = $GLOBALS['ActiveList']['name'];
    }

	if($type=="list" || $type=="printlist") {
		$sDisplay = $display;
	} elseif($type=="popup") {
		$MovieID = $display;
	} elseif($type=="prop") {
		$MovieID = $display['MovieID'];
		$PropID = $display['PropID'];
	}

	$sql = array();

	$sql['from'][] = "$CFG[Prefix]movies_".strtolower($ListName)." AS movies";
	$sql['select'][] = "movies.MovieID";
	$sql['select'][] = "movies.DateAdded";
	if($type=="popup" || $type=="prop") {
		$sql['where'][] = "movies.MovieID='$MovieID'";
	}


	foreach($PropAll as $prop)
	{
		if($type=="list") {
			if(!$prop['ShowInList']) continue;
		} elseif($type=="prop") {
			if($prop['ID']!=$PropID) continue;
		}

        if($GLOBALS['ActiveUserRights'] < $prop['RequiredRights']) continue;
        if($prop['RequiredRights']==-1 && $GLOBALS['ActiveUser']['name'] == "Guest") continue;
		if($prop['PropType'] > 100) {
			$pSql = call_user_func($CFG['CustomPropTypes'][$prop['PropType']]['sqlFunc'], $prop, "sql");
			$sql['select'][] = $pSql['select'];
			unset($pSql['select']);
			foreach($pSql as $k=>$i) {
				$sql[$k] = array_merge($sql[$k], $i);
			}
			continue;
		}
        switch($prop['PropType']) {
            case PML_PropType_Text:
            case PML_PropType_Textfield:
            case PML_PropType_Url:
            case PML_PropType_UrlCached:
            case PML_PropType_FileUpload:
            case PML_PropType_UserRating:
            case PML_PropType_AutoIncrement:
                $sql['select'][] = "movies.`".$prop['Name']."`";
                break;
            case PML_PropType_Date:
                $sql['select'][] = "DATE_FORMAT(movies.`$prop[Name]`,'$GLOBALS[strDefaultDateFormat]') AS `$prop[Name]`";
                break;
            case PML_PropType_Boolean:
            case PML_PropType_ListBox:
				if($DisplayText=="html") {
	                $sql['select'][] = "IF(propval$prop[Name].DisplayTextHtml='', propval$prop[Name].DisplayTextShort, propval$prop[Name].DisplayTextHtml) AS `$prop[Name]`";
			    } elseif($DisplayText=="short" || $DisplayText=="export") {
				    $sql['select'][] = "propval$prop[Name].DisplayTextShort AS `$prop[Name]`";
			    } elseif($DisplayText=="long") {
				    $sql['select'][] = "propval$prop[Name].DisplayText AS `$prop[Name]`";
				}	
                $sql['left join']["$CFG[Prefix]propval AS propval".$prop['Name']] = "propval$prop[Name].ID = movies.`$prop[Name]` AND propval$prop[Name].PropID = $prop[ID]";
                break;
            case PML_PropType_ListBoxMulti:
                $sql['select'][] = "movies.".$prop['Name'];
                break;
            case PML_PropType_DownloadLink:
            case PML_PropType_DownloadLinkFileUpload:
                $sql['select'][] = "movies.`".$prop['Name']."_text` AS `$prop[Name]`";
                $sql['select'][] = "movies.`".$prop['Name']."_link`";
                $sql['select'][] = "movies.`".$prop['Name']."_text`";
                $sql['select'][] = "movies.`".$prop['Name']."_size`";
                $sql['select'][] = "movies.`".$prop['Name']."_dloadcount`";
                foreach($CFG['AddDownloadLinkFields'] as $f) {
                    $sql['select'][] = "movies.`".$prop['Name']."_".strtolower($f)."`";
                }
                break;
            case PML_PropType_StaticText:
                $sql['select'][] = "'$prop[InTitle]' AS `$prop[Name]`";
                break;
            case PML_PropType_DisplayNr:
                //nothing...
                break;
                break;
            default:
                trigger_error("Unknown PropType", E_USER_ERROR);
                break;
        }
	}

	if(($type=="list" || $type=="printlist") && isset($PropAll[$sDisplay['SortPropID']]['PropType']))
	{
        $dir = "";
        $prop = $PropAll[$sDisplay['SortPropID']];        
        if($prop['UseSort']==1 || $prop['UseSort']==3) {
            if($sDisplay['SortDirection']) $dir=" ASC"; else $dir=" DESC";
        } if($prop['UseSort']==2 || $prop['UseSort']==4) {
            if($sDisplay['SortDirection']) $dir=" DESC"; else $dir=" ASC";
        }
        
		if($dir!="")
		{
			if($prop['PropType'] > 100) {
				$ord = call_user_func($CFG['CustomPropTypes'][$prop['PropType']]['sqlFunc'], $prop, "order");
				if($ord=="") $ord = "`$prop[Name]`";
			} elseif($prop['PropType']==PML_PropType_Date) {
	            $ord = "movies.`".$prop['Name']."`";
			} elseif($prop['PropType']==PML_PropType_Text) {
				$ord = "`$prop[Name]`";
				//numeric?
				if($prop['UseSort']==3 || $prop['UseSort']==4) $ord .= "+0";
			} else {
				$ord = "`$prop[Name]`";
			}

            
            $ord .= $dir;

            $sql['order'] = $ord;
        }
	}

	if(($type=="list" || $type=="printlist") && $sDisplay['SearchText']!="")
	{
		$sqlSearchText = array();
		foreach($PropAll as $Prop)
		{
			if(isset($Prop['ShowFilter']) && ($Prop['ShowFilter']==PML_ShowFilter_Search || $Prop['ShowFilter']==PML_ShowFilter_SearchChars))
			{
				if($PropAll[$sDisplay['SortPropID']]['PropType']==PML_PropType_ListBoxMulti) {			
					trigger_error("Search-Text-Filter for ListBoxMulti not possible", E_USER_ERROR);
				} else {
					$sqlSearchText[] = "movies.`$Prop[Name]` LIKE '%$sDisplay[SearchText]%'";
				}
			}
		}
		$sql['where'][] = "(".implode(" OR ", $sqlSearchText).")";
	}


	if(($type=="list" || $type=="printlist") && $sDisplay['Char']!="")
	{
		foreach($PropAll as $Prop)
		{
			if(isset($Prop['ShowFilter']) && ($Prop['ShowFilter']==PML_ShowFilter_Chars || $Prop['ShowFilter']==PML_ShowFilter_SearchChars))
			{
				if($PropAll[$sDisplay['SortPropID']]['PropType']==PML_PropType_ListBoxMulti) {			
					trigger_error("Char-Filter for ListBoxMulti not possible", E_USER_ERROR);
				} else {
					if($sDisplay['Char']=="0") {
						$sql['where'][] = "movies.`$Prop[Name]` NOT REGEXP '^[a-z]'";
					} else {
						$sql['where'][] = "movies.`$Prop[Name]` LIKE '$sDisplay[Char]%'";
					}
				}
			}
		}
	}
	if($type=="list" || $type=="printlist")
	{
		foreach($sDisplay['Filter'] as $PropID=>$FilterVal)
		{
			if($FilterVal==0) continue;
            $prop = $PropAll[$PropID];
			if($prop['PropType']==PML_PropType_Boolean || $prop['PropType']==PML_PropType_ListBox) {
				$sql['where'][] = "propval".$prop['Name'].".ID='$FilterVal'";
                //may exist allready:
                $sql['left join']["$CFG[Prefix]propval AS propval".$prop['Name']] = "propval$prop[Name].ID = movies.`$prop[Name]` AND propval$prop[Name].PropID = $prop[ID]";
			} elseif($prop['PropType']==PML_PropType_ListBoxMulti) {
				$sql['where'][] = "movies.".$prop['Name']." LIKE '%\\_{$FilterVal}\\_%'";
			} else {
				$sql['where'][] = $prop['Name']."='$FilterVal'";
			}
		}
	}

	$multiSelectPropVals = array();
	foreach($PropAll as $prop)
	{
		if($type=="list") {
			if(!$prop['ShowInList']) continue;
		} elseif($type=="prop") {
			if($prop['ID']!=$PropID) continue;
		}

		if($prop['PropType']==PML_PropType_ListBoxMulti) {
			$strSql2 = "SELECT ID, ";
			if($DisplayText=="html") {
				$strSql2 .= "IF(propval.DisplayTextHtml='', propval.DisplayTextShort, propval.DisplayTextHtml)";
			} elseif($DisplayText=="short" || $DisplayText=="export") {
				$strSql2 .= "propval.DisplayTextShort";
			} elseif($DisplayText=="long") {
				$strSql2 .= "propval.DisplayText";
			}	
			$strSql2 .= " FROM $CFG[Prefix]propval AS propval
						 WHERE PropID='$prop[ID]'";
			$query = pml_mysql_unbuffered_query($strSql2, $pmldb) or trigger_error("can't execute:<pre>$strSql2</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
			while($row=mysql_fetch_row($query)) {
				$multiSelectPropVals[$prop['ID']][$row[0]] = $row[1];
			}
					
		}
	}

	if($type=="list") {
		$sql['limit'] = (($sDisplay['Page']-1)*$sDisplay['PerPage']).','.$sDisplay['PerPage'];
	}

	$sql['where'][] = "movies.MovieID!=0";

    $strSql = buildSqlString($sql);    

    $query = pml_mysql_unbuffered_query($strSql, $pmldb) or trigger_error("mysql-error: ".mysql_error($pmldb)."</i>",E_USER_ERROR);
    

	$Data = array();

    while($row=mysql_fetch_assoc($query))
	{
        $Data[$row['MovieID']]=$row;
    }

    if($type=="list" || $type=="printlist") {
        $nr = ($sDisplay['Page']-1)*$sDisplay['PerPage'];
    } else {
        $nr = 0;
    }

    foreach($Data as $MovieID=>$row)
    {
		$nr++;

		foreach($multiSelectPropVals as $PropID=>$PropVals)
		{
			$data = substr($Data[$row['MovieID']][$PropAll[$PropID]['Name']], 1, -1);
			$data = explode("_", $data);
			$Data[$row['MovieID']][$PropAll[$PropID]['Name']] = "";
			foreach($data as $PropValID) {
				if(isset($PropVals[$PropValID])) {
					$Data[$row['MovieID']][$PropAll[$PropID]['Name']] .= $PropVals[$PropValID] . ", ";
				}
			}
			$Data[$row['MovieID']][$PropAll[$PropID]['Name']] = substr($Data[$row['MovieID']][$PropAll[$PropID]['Name']], 0, -2);
		}

		foreach($PropAll as $prop)
		{
			if($type=="list") {
				if(!$prop['ShowInList']) continue;
			} elseif($type=="prop") {
				if($prop['ID']!=$PropID) continue;
			}
			if($prop['PropType']==PML_PropType_UrlCached)
			{
				if($DisplayText=="export") continue;

				//get the local-filename:
				//it is either the filename of the url
				//or when http://www.xxx.com/xxx.xxx.PML_PropertyDelem.localfilename.jpg  the added name
				$ret = GetFileNameDelem($Data[$row['MovieID']][$prop['Name']], false); //false=be silent

				if(!@FileExists($CFG['CacheDir'].$row['MovieID']."-".$prop['ID']."-".$ret)) { //check if url is allready cached
					if($ret=="" || !DownloadFile($Data[$row['MovieID']][$prop['Name']], $CFG['CacheDir'].$row['MovieID']."-".$prop['ID']."-".$ret)) {//if not download url again
						//download failed, use standard-value                    
						$MovieID = 0;
						$stdValue = GetStandardValue($prop);
						$ret = GetFileName($stdValue); //error, return default-value
						if($ret!="" && !@FileExists($CFG['CacheDir'].$row['MovieID']."-".$prop['ID']."-".$ret)) {  //check if url is allready cached                    
							if(!DownloadFile($stdValue, $CFG['CacheDir'].$row['MovieID']."-".$prop['ID']."-".$ret)) //download it again
								$ret = ""; //if download failed, return ""
							else
								resizeImage($CFG['CacheDir']."0-".$prop['ID']."-".$ret, $prop['ImageSize']);
						}
						if($ret!="") { //if ret not empty return standard-value with movieid and propid                            
							$ret = $CFG['CacheDirHttp'].$row['MovieID']."-".$prop['ID']."-".$ret;
						}
					} else {
						resizeImage($CFG['CacheDir'].$row['MovieID']."-".$prop['ID']."-".$ret, $prop['ImageSize']);
						//downloaded sucessfully, return now the url
						$ret = $CFG['CacheDirHttp'].$row['MovieID']."-".$prop['ID']."-".$ret;
					}
				} else { 
					//file exists, use it
					$ret = $CFG['CacheDirHttp'].$row['MovieID']."-".$prop['ID']."-".$ret;
				}

				$Data[$row['MovieID']][$prop['Name']] = $ret;
			}
			elseif($prop['PropType']==PML_PropType_FileUpload)
			{
                if($DisplayText=="export") continue;

                $ret = $Data[$row['MovieID']][$prop['Name']];
                if($ret!="" && !@FileExists($CFG['UploadDir'].$row['MovieID']."-".$prop['ID']."-".$ret)) {
                    //try getting the filename (if url...)
                    $ret = GetFileName($ret,false);
                    if($ret!=""
                       && !@FileExists($CFG['UploadDir'].$row['MovieID']."-".$prop['ID']."-".$ret)
                       && !DownloadFile($Movie[$PropID], $CFG['UploadDir'].$row['MovieID']."-".$prop['ID']."-".$ret)) {
                        $ret = ""; //doesn't exist either...
                    } else {
                        $ret = $CFG['UploadDirHttp'].$row['MovieID']."-".$prop['ID']."-".$ret;
                    }
                } else if($ret!="") {
                    $ret = $CFG['UploadDirHttp'].$row['MovieID']."-".$prop['ID']."-".$ret;
                }
                if($ret=="") {
                    $ret = GetStandardValue($prop);
                    if(@FileExists($CFG['UploadDir']."0-".$prop['ID']."-".$ret)) {
                        $ret = $CFG['UploadDirHttp']."0-".$prop['ID']."-".$ret;
                    }
                }

				$Data[$row['MovieID']][$prop['Name']] = $ret;
			}
			elseif($prop['PropType']==PML_PropType_DownloadLinkFileUpload)
			{
				if($DisplayText=="export") continue;

				$ret = $CFG['UploadDir'].$row['MovieID']."-".$prop['ID']."-".$Data[$row['MovieID']][$prop['Name']."_link"];
                if(!@FileExists($ret)) {
                    $ret = "";
                }                
                $Data[$row['MovieID']][$prop['Name']."_link"] = $ret;
                
			}

			switch($prop['PropType'])
			{
				case PML_PropType_DisplayNr:
					$Data[$row['MovieID']][$prop['Name']] = $nr;
					break;
                case PML_PropType_UserRating:
                    if($Data[$row['MovieID']][$prop['Name']]==0) {
                        //keine votes
                        $Data[$row['MovieID']][$prop['Name']] = "-";
                    }
                    break;
				case PML_PropType_Url:
				case PML_PropType_UrlCached:
				case PML_PropType_FileUpload:
					if($DisplayText!="html") break;
					$ret = $Data[$row['MovieID']][$prop['Name']];
					switch($prop['ShowLinkType']) {
						case PML_ShowLinkType_Normal:
							$ret = "<a href='$ret'>" . $prop['InTitle'] . "</a>";
							break;
						case PML_ShowLinkType_Newpage:
							$ret = "<a href='$ret' target='_blank'>" . $prop['InTitle'] . "</a>";
							break;
						case PML_ShowLinkType_Image:
							if(preg_match('#^([0-9]+)x([0-9]+)([a-z]*)$#', $prop['ImageSize'], $m)) {
								$ret = "<img src='" . $ret . "' width='$m[1]' height='$m[2]' border='0'>";
							} else {
								$ret = "<img src='" . $ret . "' border='0'>";
							}
							break;
                        case PML_ShowLinkType_Link:
                            break;
					}
					$Data[$row['MovieID']][$prop['Name']] = $ret;
					break;
				case PML_PropType_DownloadLink:
				case PML_PropType_DownloadLinkFileUpload:
					if($DisplayText=="export") {
						$Data[$row['MovieID']][$prop['Name']]=="";
						break;
					}
					$ret = array("Link"=>$Data[$row['MovieID']][$prop['Name']."_link"],
						         "Text"=>$Data[$row['MovieID']][$prop['Name']."_text"],
						         "Size"=>$Data[$row['MovieID']][$prop['Name']."_size"]);
					foreach($CFG['AddDownloadLinkFields'] as $field) {
						$ret[$field] = $Data[$row['MovieID']][$prop['Name']."_".strtolower($field)];
					}
					$Data[$row['MovieID']][$prop['Name']] = $ret;
					break;
			}
		}
    }	

	$ret = array();

	if($type=="list" || $type=="printlist") {
		$strSql = "SELECT COUNT(movies.MovieID) FROM $CFG[Prefix]movies_$ListName AS movies WHERE movies.MovieID!=0 LIMIT 1";
		$query = pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
		$row=mysql_fetch_row($query);
		$AnzGes = $row[0];
		$ret['AnzGes'] = $AnzGes;

		unset($sql['limit']);
		unset($sql['order']);
		unset($sql['group']);
		$sql['select'] = array("COUNT(movies.MovieID)");
		$strSql = buildSqlString($sql). " LIMIT 1";
		$query = pml_mysql_query($strSql, $pmldb) or trigger_error("can't execute:<pre>$strSql</pre><i>".mysql_error($pmldb)."</i>",E_USER_ERROR);
		$row = mysql_fetch_row($query);
		$AnzFound = $row[0];    
		$ret['AnzFound'] = $AnzFound;
	}
	
	$ret['Data'] = $Data;
	return($ret);
}



function pml_mysql_unbuffered_query($strSql, $db) {
global $CFG, $sqlStrings;
    if(isset($CFG['ShowSqlStrings']) && $CFG['ShowSqlStrings']) {
        p($strSql);
    }    
//$fp = fopen("sqllog.txt", "a");
//fwrite($fp, date("Y-m-d H:i:s")."\n");
//fwrite($fp, $strSql."\n\n\n");
//fclose($fp);
	if($CFG['Debug']) $start = getmicrotime();
	$ret = mysql_unbuffered_query($strSql, $db);
	if($CFG['Debug']) {
		$time = getmicrotime()-$start;
		$sqlStrings[] = array('sql'=>$strSql, 'time'=>$time, 'type'=>"unbuffered");
	}
	return($ret);
}

function pml_mysql_query($strSql, $db) {
global $CFG, $sqlStrings;
    if(isset($CFG['ShowSqlStrings']) && $CFG['ShowSqlStrings']) {
        p($strSql);
    }
//$fp = fopen("sqllog.txt", "a");
//fwrite($fp, date("Y-m-d H:i:s")."\n");
//fwrite($fp, $strSql."\n\n\n");
//fclose($fp);
	if($CFG['Debug']) $start = getmicrotime();
	$ret = mysql_query($strSql, $db);
	if($CFG['Debug']) {
		$time = getmicrotime()-$start;
		$sqlStrings[] = array('sql'=>$strSql, 'time'=>$time, 'type'=>"normal");
	}
	return($ret);
}

function getMovieProp($MovieID, $PropID) {
global $ActiveList, $PropAll;
	$ret = ReadMovieDataFromDb("prop", array("MovieID"=>$MovieID, "PropID"=>$PropID), "long", $ActiveList['name']);
	return($ret['Data'][$MovieID][$PropAll[$PropID]['Name']]);
}


function resizeImage($FileName, $ImageSize)
{
	if(!preg_match('#^([0-9]+)x([0-9]+)([a-z]*)$#', $ImageSize, $m)) return(false);

	$dW = $m[1]; $dH = $m[2];
	if($m[3]=='crop') $crop=true; else $crop=false;

	$size = getimagesize($FileName);
	$sW = $size[0]; $sH = $size[1];

	$sX = 0;
	$sY = 0;
	if($crop)
	{
		$sAr = $sW / $sH;
		$dAr = $dW / $dH;
		$wFactor = $sW / $dW;
		$hFactor = $sH / $dH;
		if ($sAr < $dAr) { // Kopie ist im Verhältnis niedriger				
			$sHnew = $dH * $wFactor;
			$sY = ($sH - $sHnew) / 2;
			$sH = $sHnew;
		} else if ($sAr > $dAr) { // Kopie ist im Verhältnis schmäler
			$sWnew = $dW * $hFactor;
			$sX = ($sW - $sWnew) / 2;
			$sW = $sWnew;
		}
	}
	
	if ($size[2]==2) {
		$sImg = ImageCreateFromJPEG($FileName);
	} else if ($size[2]==1) {
		$sImg = ImageCreateFromGIF($FileName);
	} else if ($size[2]==3) {
		$sImg = ImageCreateFromPNG($FileName);
	}
	$dImg = imagecreatetruecolor($dW, $dH);

	// Bild skalieren
	imagecopyresampled($dImg, $sImg, 0, 0, $sX, $sY, $dW, $dH, $sW, $sH);

	imagejpeg($dImg, $FileName, 80);
	imagedestroy($sImg);
	imagedestroy($dImg);
}

?>
Return current item: PowerMovieList