Location: PHPKode > projects > Pindorama > pindorama/active/components/core.php
<?php
/**
*                                                          
* @name    Pindorama core functions                    
* @version 0.11
* @author  Guilherme Capilé <hide@address.com>           
*                                                          
*/

require_once($c["components"]."schemes.php");

/**
*                                                          
* @name        pin_xml_array                    
* @deprecated  transforma arrays em estruturas XML
* @deprecated  transforma listas (arrays) em cadeias de elementos XML, com validação
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $arr
* @param       $disable_output_escaping (Default = True)
* @param       $escape_dashes (Default = False)
* @param       $element (Defalt = "")
*
* @global      $xml_error
*
* @static      $attributes
* @static      $txt
* @static      $xml      
*
* @see         pin_check_xml()
*
* @return      String cadeia de elementos XML baseada na lista enviada                                         
*/
function pin_xml_array ($arr, $disable_output_escaping = TRUE, $escape_dashes = FALSE, $element = "" )
{ // transforma listas (arrays) em cadeias de elementos XML, com validação
    global $xml_error;
    $attributes = "";
    $txt = "";
    $xml = "";
    if (is_array ($arr)) {
        foreach ($arr as $k=>$v) {
            /*if (is_numeric($k) && is_array($v)){
                return xml_array($v, $disable_output_escaping, $escape_dashes, $element);
            } else*/ if (is_numeric($k)){
                $txt .= pin_xml_array($v, $disable_output_escaping, $escape_dashes);
            } else if (!preg_match("/\@/", $k)) {
                $txt .= pin_xml_array($v, $disable_output_escaping, $escape_dashes, $k);
	        } else if ($escape_dashes) {
	        	$attributes .= " ".preg_replace("/\@/", "", $k).'="'.htmlspecialchars(stripslashes($v)).'"';
	        } else {
	        	$attributes .= " ".preg_replace("/\@/", "", $k).'="'.htmlspecialchars($v).'"';
	        }
        }
    } else if ($disable_output_escaping) {
        if (!$escape_dashes) {
            $txt = htmlspecialchars($arr);
        } else {
            $txt = htmlspecialchars(stripslashes($arr));
        }
    } else {
        if (!$escape_dashes) {
            $txt = $arr;
        } else {
            $txt = stripslashes($arr);
        }
        $txt = pin_check_xml($txt);
    }
    if ($element != "") {
        $element = preg_replace("/[^a-z\_\-0-9\.]/i", "_", $element);
        $element = preg_replace("/^([^a-z])/i", "i\\1", $element);
        $result = "<".$element.$attributes.">".$txt."</".$element.">";
    } else {
        $result = $txt;
    }
    return $result;
} // xml_array


/**
*                                                          
* @name        pin_check_xml                    
* @deprecated  checa um XML
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $str
*
* @global      $xml_error
*
* @return                                               
*/
function pin_check_xml($str)
{
	global $xml_error;
	$xml_parser = xml_parser_create();
	if (!xml_parse ($xml_parser, "<xpml>\n".$str."\n</xpml>")) {
	    $str = '<error message="'.$xml_error[$xml_parser].'" line="'.(xml_get_current_line_number ($xml_parser) -1).'" col="'.xml_get_current_column_number ($xml_parser).'">'.htmlspecialchars ($str)."</error>";
	}
	xml_parser_free ($xml_parser);
	return $str;
} //check_xml


/**
*                                                          
* @name        pin_files_array                    
* @deprecated  transforma as listas de arquivos enviados em cadeias de elementos XML
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $files (Default = "")
*
* @global      $xml_error
*
* @see         pin_xml_array()
*
* @return      String cadeia de elementos XML baseada no arquivo enviado
*/
function pin_files_array ($files = "")
{ // transforma as listas de arquivos enviados em cadeias de elementos XML
    global $xml_error;
    if ($files == "") {
        $files = $_FILES;
    }
    $txt = "";
    $xml = "";
    $result = "";
    foreach ($files as $k=>$v) {
        $txt .= pin_xml_array($v, $disable_output_escaping, $escape_dashes);
        $tmpnames = $v["tmp_name"];
        /*foreach ($tmpnames as $tmpfile) {
            if (is_uploaded_file($tmpfile)) {
                $txt .= "<file>".base64_encode(file_get_contents($tmpfile))."</file>";
            }
        }*/
        $element = $k;
        $element = preg_replace("/[^a-z\_\-0-9\.]/i", "_", $element);
        $element = preg_replace("/^([^a-z])/i", "i\\1", $element);
        $result .= "<".$element.">".$txt."</".$element.">";
        
    }
    return $result;
} // files_array


/**
*                                                          
* @name        pin_read_xpath                    
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $xpath
* @param       $xml
*
* @global      $arg
* @global      $param
* @global      $c
*
* @see         pin_xml_array()
*
* @return      
*/
function pin_read_xpath ($xpath, $xml)
{
    global $arg, $param, $c;
    $result = false;
    if (is_array($xpath)) {
        $rules = "";
        foreach ($xpath as $k=>$v) {
            $rules .= '<xsl:for-each select="'.$v.'">$result['.$k.'][] = '."'".'<xsl:value-of select="translate(., $from, $to)"/>'."'".';<xsl:text>'."\n".'</xsl:text></xsl:for-each>';
        }
    } else {
        $rules = '<xsl:for-each select="'.$xpath.'">$result[] = '."'".'<xsl:value-of select="translate(., $from, $to)"/>'."'".';<xsl:text>'."\n".'</xsl:text></xsl:for-each>';
    }
    $arg["xsl"] = <<<FIM
<?xml version="1.0" encoding="iso-8859-1" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output encoding="iso-8859-1" indent="no" method="xml" omit-xml-declaration="yes"/>
<xsl:variable name="from">'</xsl:variable>
<xsl:variable name="to">’</xsl:variable>
<xsl:template match="/">$rules</xsl:template>
</xsl:stylesheet>
FIM;
    eval(pin_xsl_process($xml, "arg:xsl"));
    return $result;
}

/**
*                                                          
* @name        pin_copy_xpath                    
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $xpath
* @param       $xml
* @param       $xmldecl (Default = False)
*
* @global      $arg
* @global      $param
* @global      $c
*
* @return      
*/
function pin_copy_xpath ($xpath, $xml, $xmldecl = FALSE)
{
    global $arg, $param, $c;
    $rules = '$result = "";';
    $rules = "";
    if (is_array($xpath)) {
        for ($i = 0; $i < count($xpath); $i++) {
            $xpath[$i] = str_replace('"', "'", $xpath[$i]);
            $rules .= '<xsl:for-each select="'.$xpath[$i].'"><xsl:copy-of select="."/></xsl:for-each>';
        }
    } else {
        $xpath = str_replace('"', "'", $xpath);
        $rules = '<xsl:for-each select="'.$xpath.'"><xsl:copy-of select="."/></xsl:for-each>';
    }
    if ($xmldecl) {
        $oxd = "no";
    } else {
        $oxd = "yes";
    }
    $arg["xsl"] = <<<FIM
<?xml version="1.0" encoding="iso-8859-1" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output encoding="iso-8859-1" indent="no" method="xml" omit-xml-declaration="{$oxd}"/>
<xsl:variable name="from">'</xsl:variable>
<xsl:variable name="to">’</xsl:variable>
<xsl:template match="/">$rules</xsl:template>
</xsl:stylesheet>
FIM;
    $result = pin_xsl_process($xml, "arg:xsl");
    return $result;
}

/**
*                                                          
* @name        pin_write_xpath                    
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $xpath
* @param       $xml
* @param       $content
*
* @global      $arg
* @global      $param
* @global      $c
*
* @return      
*/
function pin_write_xpath ($xpath, $xml, $content)
{
    global $arg, $param, $c;
    if (is_array($xpath) && is_array($content)) {
        $rules = "";
        for ($i = 0; $i < count($xpath); $i++) {
            $rules .= '<xsl:template match="'.$xpath[$i].'" priority="'.(count($xpath) - $i).'">'.$content[$i].'</xsl:template>';
        }
    } else {
        $rules = '<xsl:template match="'.$xpath.'" priority="1">'.$content.'</xsl:template>';
    }
    $arg["xsl"] = <<<FIM
<?xml version="1.0" encoding="iso-8859-1" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output encoding="iso-8859-1" indent="no" method="xml" omit-xml-declaration="no"/>
<xsl:template match="/"><xsl:apply-templates/></xsl:template>
<xsl:template match="*"><xsl:element name="{name()}"><xsl:apply-templates select="@*"/><xsl:apply-templates/></xsl:element></xsl:template>
<xsl:template match="@*"><xsl:attribute name="{name()}"><xsl:value-of select="."/></xsl:attribute></xsl:template>
<xsl:template match="text()"><xsl:value-of select="normalize-space(.)"/></xsl:template>
<xsl:template match="comment()"><xsl:comment><xsl:copy-of select="."/></xsl:comment></xsl:template>
<xsl:template match="processing-instruction()"><xsl:processing-instruction name="{name()}"><xsl:copy-of select="."/></xsl:processing-instruction></xsl:template>
$rules
</xsl:stylesheet>
FIM;
    $result = pin_xsl_process($xml, "arg:xsl");
    return $result;
}

/**
*                                                          
* @name        pin_redirect                    
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $url
*
* @global      $c
*
*/
function pin_redirect($url)
{
    global $c;
    if (!headers_sent()) {
        header("HTTP/1.1 301 Moved Permanently", TRUE);
        header("Location: ".$c["host"].$url, TRUE);
        exit();
    } else {
        echo '<html><head><meta http-equiv="Refresh" content="0; URL='.$c["redirect_base"].$c["host"].$url.'"></head><body><body></html>';
        exit();
    }
}

/**
*                                                          
* @name        pin_error
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $type
* @param       $message (Default = "")
*
* @global      $arg
* @global      $param
* @global      $c
*
* @return      
*/
function pin_error ($type, $message = "") 
{
    global $c, $arg, $param;
    if (!headers_sent ()) {
        if ($type == "404") {
            header("HTTP/1.0 404 Not Found");
        } elseif ($type == "500") {
            header("HTTP/1.0 500 Internal Server Error");
        } elseif ($type == "401") {
            header("WWW-Authenticate: Basic realm=\"CMS Pindorama\"");
            header("HTTP/1.0 401 Unauthorized");
        }
    }
    if ($param["quiet"]) {
        return "";
    } else if ($c["error"][$type] != "") {
        header("Location: {$c['error'][$type]}");
    } else {
        header("Content-type: text/html;");
        $param["message"] = htmlspecialchars($message);
        $param["type"] = $type;
        $result = pin_xsl_process("arg:empty", $c["stylesheets"]."error.xsl");
  	    exit($result);
    }
} //error

/**
*                                                          
* @name        pin_clean_xml
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $text
*
* @return      
*/
function pin_clean_xml ($text)
{
    return htmlspecialchars(iconv("ISO-8859-1","UTF-8", $text));
}

/**
*                  
* @name        pin_xsl_process
* @deprecated  processa o arquivo $xml pela forma $xsl utilizando a $base para transformacoes do tipo $saida
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $xml
* @param       $xsl
* @param       $result (Default = "")
* @param       $base (Default = "")
*
* @global      $arq
* @global      $param
* @global      $c
*
* @see         pin_save_file()
*
* @return      
*/
function pin_xsl_process ($xml, $xsl, $result = "", $base = "")
{ // processa o arquivo $xml pela forma $xsl utilizando a $base para transformacoes do tipo $saida
    
    global $arg, $param, $c;
    if ($xml == "") {
        $xml = $arg["empty"];
    }
    if (!function_exists("xslt_create")) {
        // php5
        require_once($c["components"]."/streams.php");
        /* Load the two XML sources */
        if ($base != "") {
            chdir($base);
        }
        $xml = preg_replace("/\:\/?/", "://", $xml);
        $xsl = preg_replace("/\:\/?/", "://", $xsl);

        $x = file_get_contents($xml);
        // echo "<pre>$xml \n".htmlentities($x)."</pre>";
        $xs = file_get_contents($xsl);
        // echo "<pre>$xsl \n".htmlentities($xs)."</pre>";
        echo "<pre>$xml => $xsl \n base: $base</pre>";

        $inbuf = new DomDocument; // from /ext/dom
        $inbuf->loadXML($x);
        
        $toxsl = new DomDocument;
        $toxsl->loadXML($xs);
        if ($base != "") {
            $base = preg_replace("/^file\:\/\//", "", $base);
            chdir($base);
        }
        /* Configure the transformer */
        $proc = new xsltprocessor;
        foreach ($param as $p=>$v) {
            $proc->setParameter ("", $p,$v);
        }                                                           
        $proc->importStyleSheet($toxsl); // attach the xsl rules
        $contents = $proc->transformToXML($inbuf); // actual transformation
        echo "<pre>".htmlentities($contents)."</pre>";
    } else {
        // debug:    echo "template ($xsl)\n";;
        $xh = xslt_create();
        if ($base != "") {
            xslt_set_base($xh, "file://".$base);
        } else {
            if (!preg_match("/.{2}\:/", $xml)) {
                $xml = "file://".$xml;
            }
            if (!preg_match("/.{2}\:/", $xsl)) {
                $xsl = "file://".$xsl;
            }
            xslt_set_base($xh, dirname($xsl)."/");
        }
        if ($c["log_level"] > 1) {
            xslt_set_log ($xh, true);
            xslt_set_log ($xh, $c["xslt_logfile"]);
        }
        xslt_set_error_handler ($xh, "pin_xsl_error");
        xslt_set_scheme_handlers($xh, array("get_all"=>"pin_xsl_schemes"));
        $contents = xslt_process($xh, $xml, $xsl, NULL, $arg, $param);
        // debug:  echo $xsl." + $xml -> ".$contents."\n\n";
        xslt_free($xh);
    }
    if ($result == "") { // sem geração de arquivos
        return $contents;
    } else if ($contents != "") {
        return pin_save_file($base.$result, $contents);
    } else {
        return false;
    }
} // xsl_process

/**
*                  
* @name        pin_save_file
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $file
* @param       $contents
*
* @global      $c
*
* @see         pin_make_pathtofile()
*
* @return      
*/
function pin_save_file ($file, $contents) {
    global $c;
    $file = preg_replace("/[^a-z\_\-0-9\/\:\.]*/i", "", $file);
    if ($file == "") {
        return FALSE;
    } else if ($contents != "") {
        $dir = dirname($file);
        if (!is_dir($dir)) {
            pin_make_pathtofile($file);
        }
        $fd = @fopen ($file, "wb");
        if ($fd) {
            fwrite ($fd, $contents);
            fclose ($fd);
            if ($c["file_mask"] != "") {
                @chmod ($file, $c["file_mask"]);
            }
            return TRUE;
        } else {
            return FALSE;
        }
    }
} //save_file

/**
*                  
* @name        pin_pathtofile
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $path
*
* @global      $c
*
* 
* @return      
*/
function pin_make_pathtofile ($path) {
    global $c;
    $file = basename($path);
    $diretorio = "";
    $temp = split ("/", $path);
    foreach ($temp as $p) {
        $dir = $dir.$p;
        if (substr($dir, 0, strlen($c["base"])) == $c["base"]) {
            if ($p == $file) {
                return true;
                exit;
            } elseif (!is_dir ($dir) && $dir != "") {
                if (!mkdir($dir, 0775)){
                    echo "o diretório ".$dir." não existe";
                    return false;
                    exit;
                }
                $dir = $dir."/";
            } else {
                $dir = $dir."/";
            }
        } else {
            $dir = $dir."/";
        }
    }
} //make_path


/**
*                  
* @name        pin_xsl_schemes
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $xh
* @param       $protocol
* @param       $req
*
* @global      $c
* @global      $arq
* @global      $req
*
* @return      
*/
function pin_xsl_schemes ($xh, $protocol, $req) {
    global $c, $arg, $param;
    //debug: echo "scheme ($req)\n";
    $req = preg_replace("/\'/", "\\\"", $req);
    $protocol = preg_replace("/[^a-z]/i", "_", $protocol);
    if ($protocol != "") {
        eval("\$cont = pin_read_$protocol ( '$xh', '$req' );");
        if ($cont != "") {
            return $cont;
        } else {
            return $arg["empty"];
        }
    }
} //xsl_schemes

/**
*                  
* @name        pin_xsl_schemes_update
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $xh
* @param       $protocol
* @param       $req
*
* @global      $c
* @global      $arq
* @global      $param
*
* @return      
*/
function pin_xsl_schemes_update ($xh, $protocol, $req) 
{
    global $c, $arg, $param;
    
    $req = preg_replace("/\'/", "\\\"", $req);
    $protocol = preg_replace("/[^a-z]/i", "_", $protocol);
    if ($protocol != "") {
        @eval("\$cont = pin_write_$protocol ( '$xh', '$req' );");
        return $cont;
    }
} //xsl_schemes_update


/**
*                  
* @name        pin_xsl_schemes_delete
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $xh
* @param       $protocol
* @param       $req
*
* @global      $c
* @global      $arq
* @global      $param
*
* @return      
*/
function pin_xsl_schemes_delete ($xh, $protocol, $req) 
{
    global $c, $arg, $param;
    
    $req = preg_replace("/\'/", "\\\"", $req);
    $protocol = preg_replace("/[^a-z]/i", "_", $protocol);
    if ($protocol != "") {
        @eval("\$cont = pin_delete_$protocol ( '$xh', '$req' );");
        return $cont;
    }
} //xsl_schemes_delete


/**
*                  
* @name        pin_index_update
* @deprecated  regras para atualização dos índices - deve passar para um registro semelhante aos componentes
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $xmlref
*
* @global      $c
* @global      $arq
* @global      $param
* @global      $pcom
* @global      $l
*
* @see         pin_xsl_schemes_update()
* @see         pin_read_xpath()
* @see         pin_send_message()
* @see         pin_redirect()
*
* @return      
*/
function pin_index_update ($xmlref) 
{//regras para atualização dos índices - deve passar para um registro semelhante aos componentes
    global $c, $arg, $param, $pcom, $l;
    //atualização do índice de registro de uris
    $info = array("/request/post/meta/identifier", "/request/post/meta-relation[@type='sitemap']/ref", "/request/post/meta-relation[@type='sitemap']/ref-type", "/request/post/x/ref[@id != '']/@id");
    $info = pin_read_xpath($info, "arg:request");
    $uris = $info[0];
    if (is_array($uris)) {
        $arg["index_update"] = $c["xmlpi"]."<resource name=\"uris\">";
        foreach ($uris as $temp) {
            $arg["index_update"] .= "<uri id=\"$xmlref\">$temp</uri>";
        }
        $arg["index_update"] .= "</resource>";
        pin_xsl_schemes_update ($xmlref, "index", "uris");
        $arg["index_update"] = "";
    }
    if (is_array($info[1]) && $info[1][0] != "" && $xmlref != $info[1][0]) {
        $arg["index_update"] = $c["xmlpi"];
        $arg["index_update"] .= "<page ref=\"$xmlref\"><ref>".$info[1][0]."</ref><ref-type>".$info[2][0]."</ref-type></page>";
        pin_xsl_schemes_update ($xmlref, "index", "sitemap");
        $arg["index_update"] = "";
    }
    if (is_array($info[3])) {
        $info[3] = array_reverse($info[3]);
        foreach ($info[3] as $k=>$v) {
            if (preg_match("/^([^\:]+)\:(.+)$/", $v, $matches)) {
                $arg["index_update"] = $c["xmlpi"].pin_copy_xpath("/request/post/x/ref[@id = '$v'][1]", "arg:request");
                pin_xsl_schemes_update ($xmlref, $matches[1], $matches[2]);
                if (preg_match("/(.+)\#new_record$/", $v, $matches)) {
                    $new_record = true;
                    $ref = pin_read_xpath("/xpml/resource/@next", $matches[1]);
                }
            }
        }
        $arg["index_update"] = "";
        if ($new_record && $ref[0] != "") {
            pin_send_message($l["msg"]["fileinfo"].$xmlref.$l["msg"]["success_ending2"]);
            $ref = $ref[0] -1;
            pin_redirect($pcom["pin_output_dav"]."?id=$xmlref&ref=$ref");
        }
            
    }
} //index_update

/**
*                  
* @name        pin_index_update_copy
* @deprecated  records index copies only -- no sitemap or uris change
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $xmlref
*
* @global      $c
* @global      $arq
* @global      $param
*
* @see         pin_xsl_schemes_update()
* @see         pin_read_xpath()
*
* @return      
*/
function pin_index_update_copy ($xmlref) 
{// records index copies only -- no sitemap or uris change
    global $c, $arg, $param;
    if (preg_match("/^\/?([^\.]+)\.([^\.]+)\.(.+)$/", $xmlref, $matches)) {
        $copy = ".".$matches[2].".".$matches[3];
        $xmlfile = $c["index"].preg_replace("/^[^\:]+\:/", "", $matches[1])."/".$matches[2].".".$matches[3].".xml";
    } else {
        return false;
    }
    $info = "/request/post/x/ref[@id != '']/@id";
    $info = pin_read_xpath($info, "arg:request");
    if (is_array($info)) {
        $info = array_reverse($info);
        foreach ($info as $k=>$v) {
            if (preg_match("/^([^\:]+)\:([^\#]+)/", $v, $matches)) {
                $arg["index_update"] = $c["xmlpi"].pin_copy_xpath("/request/post/x/ref[@id = '$v'][1]", "arg:request");
                pin_xsl_schemes_update ($xmlref, $matches[1], $matches[2].$copy);
            }
        }
        $arg["index_update"] = "";
    }
} //index_update_copy

/**
*                  
* @name        pin_output_header
* @deprecated  records index copies only -- no sitemap or uris change
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $file
* @param       $cache (Default = True)
* @param       $format (Default = "")
* @param       $size (Default = "")
* @param       $lastm (Default = "")
*
* @global      $c
* @global      $mime
*
* @return      
*/
function pin_output_header ($file, $cache = TRUE, $format = "", $size = "", $lastm = "")
{
    global $c, $mime;
    if (!headers_sent()) {
        if ($format == "") {
            $pathinfo = pathinfo($file);
            $format = $pathinfo["extension"];
        } else if ($format == "image/pjpeg") {
            $format = "image/jpeg";
        }
        if ($size != "") {
            header("Content-Length: ".$size);
        } else if ($format != "php" && $format != "application/x-httpd-php" && is_file($file)) {
            header("Content-Length: ".filesize($file));
        }
        if ($format == "php" || $format == "application/x-httpd-php") {
            $format = "";
        }
        if ($mime[$format] != "") {
            header("Content-Type: ".$mime[$format], TRUE);
        } else if (in_array($format, $mime)) {
            header("Content-Type: $format", TRUE);
        } else {
            //formato default para o PHP -- nenhum
            header("Content-Type: text/html", TRUE);
        }
        if ($cache) {
            if (is_file($file)) {
                header("Last-Modified: ".gmdate("D, d M Y H:i:s", filemtime($file)) . " GMT");
            } else {
                header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
            }
        } else {
            header("Cache-Control: no-store, no-cache, must-revalidate");
            header("Cache-Control: post-check=0, pre-check=0", false);
            header("Pragma: no-cache");
        }
    }
} // output_header



/**
*                  
* @name        pin_output_file
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $path
*
* @global      $c
* @global      $mime
*
* @see         pin_output_header()
* @see         pin_error()
*
* @return      
*/
function pin_output_file ( $path )
{
    global $c, $mime;
    if (preg_match("/\.php$/", $path) && is_file($path)) {
        pin_output_header($path, FALSE, "php");
        chdir(dirname($path));
        require_once($path);
    } else if (is_file($path)) {
        pin_output_header($path);
        $contents = file_get_contents($path);
        return $contents;
    } else {
        pin_error("404");
        exit();
    }
}


/**
*                  
* @name        pin_new_dav
* @deprecated  alias para output_dav
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $xmlref (Default = "")
*
* @global      $c
* @global      $param
*
* @see         pin_output_dav()
*/
function pin_new_dav ( $xmlref = "" )
{// alias para output_dav
    global $c, $param;
    pin_output_dav( $xmlref );
} //new_dav

/**
*                  
* @name        pin_output_dav
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $xmlref (Default = "")
*
* @global      $c
* @global      $param
* @global      $l
* @global      $g
* @global      $pcom
* @global      $arq
*
* @see         pin_redirect()
* @see         pin_xsl_schemes_update()
* @see         pin_xsl_process()
* @see         pin_output_header()
* @see         pin_index_update()
* @see         pin_send_message()
* @see         pin_index_update_copy()
* @see         pin_check_out()
* @see         pin_check_in()
* @see         pin_check_permission()
*
* @return      
*/
function pin_output_dav ( $xmlref = "" )
{
    global $c, $param, $l, $g, $pcom, $arg;
    $param["editing"] = true;
    if ($xmlref == "" && $_GET["id"] != "") {
        $xmlref = preg_replace("/[^a-z\_0-9\-\:\.\/]/", "_", $_GET["id"]);
    }
    if (!is_array($pcom)) {
        include($c["components"]."components.php");
    }
    if ($xmlref == "index:uris" || $xmlref == "index:users" || $xmlref == "index:sitemap" || $xmlref == "index:datasets") {
        pin_redirect($pcom["start.menu"]);
    }
    if ($_SERVER["REMOTE_USER"] != "") {
        $user = $_SERVER["REMOTE_USER"];
    } else if ($_SERVER["PHP_AUTH_USER"] != "") {
        $user = $_SERVER["PHP_AUTH_USER"];
    } else {
        $user = $param["user"];
    }
    $perm = TRUE;
    pin_output_header ($param["script-name"], FALSE, "php");
    if ($_POST["dav-id"] != "" || $param["dav-id"] != "") {
        //if (check_out($xmlref, $user) && (crypt($user,$_POST["dav-id"]) == $_POST["dav-id"])) {
           if (preg_match("/^([^\:]+)\:(.+)/", $xmlref, $matches)) {
                $result = pin_xsl_schemes_update ( $xmlref, $matches[1], $matches[2] );
            //} else {
            //    $result = pin_xsl_process ($xmlref, $c["stylesheets"]."dav/dav_update.xsl", $xmlref);
            }
            if ($result) {
                if (!preg_match("/\./", $xmlref)) {
                    pin_index_update ($xmlref);
                } else {
                    pin_index_update_copy ($xmlref);
                }
                $param["update"] = TRUE;
                pin_send_message($l["msg"]["fileinfo"].$xmlref.$l["msg"]["success_ending2"]);
                if ($_GET["merge"] != "") {
                    pin_redirect($pcom["pin_output_dav"]."?id=$xmlref");
                    exit();
                }
            }
        //}
    } else if ($_GET["close"] == 1) {
        pin_check_out($xmlref, $user);
        $url = $c["redirect_base"].$_GET["url"];
        if ($url == "") {
            $url = $pcom["preview_dav"]."?id=".$xmlref;
        }
        pin_redirect($url);
        exit();
    } else if ($_GET["copy"] == 1) {
        if (preg_match("/^([^\:]*)\:(.*)/", $xmlref, $matches)) {
            $param["copy"] = 1;
            $result = pin_xsl_schemes_update ( $xmlref, $matches[1], $matches[2] );
            if ($result) {
                pin_index_update_copy ($xmlref);
            }
        }
    }
    if (!pin_check_permission($xmlref, "write", $user)) {
        pin_send_message($l["msg"]["file_forbidden"]);
        $param["read-only"] = "all";
    }
    if ($perm && pin_check_in($xmlref, $user)) {
        $param["dav-id"] = crypt($user);
    } else if ($perm) {
        pin_send_message($l["msg"]["file"].$xmlref.$l["msg"]["file_locked"]);
        $param["read-only"] = "all";
    }
    $xsl = pin_xsl_process ($xmlref, "index.xsl", "", $c["stylesheets"]);
    echo pin_xsl_process ($xmlref, $c["stylesheets"].$xsl);
}


/**
*                  
* @name        pin_delete_dav
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $xmlref (Default = "")
*
* @global      $arg
* @global      $c
* @global      $param
* @global      $pcom
* @global      $l
*
* @see         pin_redirect()
* @see         pin_xsl_schemes_update_delete()
* @see         pin_index_update()
* @see         pin_send_message()
* @see         pin_check_out()
*
* @return      
*/
function pin_delete_dav ( $xmlref = "" )
{
    global $arg, $c, $param, $pcom, $l;
    if ($xmlref == "" && $_GET["id"] != "") {
        $xmlref = preg_replace("/[^a-z\_0-9\-\:\.]/", "_", $_GET["id"]);
    }
    if ($param["auth-user"] != "") {
        $user = $param["auth-user"];
    } else {
        $user = $param["user"];
    }
    require_once($c["components"]."components.php");
    if ($_POST["dav-id"] != "") {
        if (pin_check_out($xmlref, $user) && (crypt($user,$_POST["dav-id"]) == $_POST["dav-id"])) {
            if (preg_match("/^([^\:]*)\:(.*)/", $xmlref, $matches)) {
                // todo?
                $result = pin_xsl_schemes_delete ( $xmlref, $matches[1], $matches[2] );
            }
            if ($result) {
                //$xpath = array("/request/post/meta/identifier", "/request/post/meta-relation[@type='sitemap']/ref", "/request/post/meta-relation[@type='sitemap']/ref-type");
                //$content[] = "";
                //$arg["request"] = pin_write_xpath ($xpath, "arg:request", $content);
                if (!preg_match("/\./", $xmlref)) {
                    pin_index_update ($xmlref);
                    $redirect = $pcom["start.menu"];
                } else {
                    $redirect = $pcom["pin_output_dav"]."?id=".preg_replace("/\..+/", "", $xmlref);
                }
                pin_send_message($l["msg"]["file"].$xmlref.$l["msg"]["file_delete"]);
                pin_redirect($redirect);
                exit("");
            }
        }
    }
    pin_send_message($l["msg"]["file"].$xmlref.$l["msg"]["file_delete_failure"]);
    pin_redirect($pcom["pin_output_dav"]."?id=$xmlref");
    exit();
} // delete_dav

/**
*                                                          
* @name        pin_output_xml
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $xmlref (Default = "")
* @param       $headers (Default = True)
* @param       $cache (Default = True)
* @param       $procphp (Default = True)
*
* @global      $arg
* @global      $param
* @global      $c
*
* @see         pin_read_xpath()
* @see         pin_xsl_process()
* @see         pin_xsl_schemes()
* @see         pin_file_save()
* @see         pin_output_header()
* @see         pin_xml_graph()
* 
* @return      
*/
function pin_output_xml($xmlref = "", $headers = TRUE, $cache = TRUE, $procphp = TRUE)
{
    global $c, $param, $arg;
    $save = true;
    $cachefile = $c["cache_dir"].$param["script-name"];
    $checkfile = $c["var"]."check";
    if ($cache && $c["cache"] && is_file($cachefile) && (filemtime($cachefile) > filemtime($checkfile))) {
        // shows the cache
        $result = file_get_contents($cachefile);
    } else {
        $param["stylesheets-dir"] = "file://".$c["stylesheets"];
        $arg["www"] = file_get_contents($c["stylesheets"]."www-conf.xsl");
        $xsl = pin_xsl_process($xmlref, "arg:www", "", $c["templates"]);
        unset($param["stylesheets-dir"]);
        // debug: echo "\n\n-> $xsl\n\n";
        $result = pin_xsl_process ($xmlref, $xsl, "", $c["templates"]);
        if (substr(trim($result), 0, 6) == "<?xml " && !preg_match("/\.(html|xml|php)/", $param["script-name"])) {
            $arg["result"] = $result;
            $prop = pin_read_xpath(array("/resource-description/format", "/resource-description/size", "/resource-description/@ref-src", "/resource/@type"), "arg:result");
            $format = $prop[0][0];
            $bsize = $prop[1][0];
            if ($prop[2][0] != "" && preg_match("/^([a-z0-9]*)\:(.*)$/", $prop[2][0], $matches)) {
                $result = pin_xsl_schemes ($xmlref, $matches[1], $matches[2]);
            } else if ($prop[3][0] == "graph") {
                require_once($c["components"]."graph.php");
                pin_xml_graph($arg["result"], $cachefile);
                // don't save
                $result = file_get_contents($cachefile);
                $save = false;
            }
        }
        if ($save) {
            pin_save_file($cachefile, $result);
        }
    }
    if ($procphp && preg_match("/\.php$/", $cachefile) && is_file($cachefile)) {
        if ($headers) {
            pin_output_header($param["script-name"], FALSE, "php");
        }
        chdir(dirname($cachefile));
        ob_start();
        include_once($cachefile);
        $result = ob_get_contents();
        ob_end_clean();
        return $result;
    } else {
        if ($headers) {
            pin_output_header($cachefile, TRUE, $format, $bsize);
        }
        return $result;
    }
}

/**
*                                                          
* @name        pin_preview_dav
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $xmlref (Default = "")
* @param       $headers (Default = True)
*
* @global      $arg
* @global      $param
* @global      $c
*
* @see         pin_read_xpath()
* @see         pin_xsl_process()
* @see         pin_xsl_schemes()
* @see         pin_output_header()
* 
* @return      
*/
function pin_preview_dav ( $xmlref = "", $headers = TRUE )
{
    global $c, $param, $arg;
    if ($xmlref == "" && $_GET["id"] != "") {
        $xmlref = preg_replace("/[^a-z\_0-9\-\:\.]/", "_", $_GET["id"]);
    }
    $format = "php";
    $size = "";
    $scriptname = $param["script-name"];
    if ($xmlref  != "") {
        $result = pin_xsl_process ($xmlref, $c["stylesheets"]."preview.xsl");
    } else {
        $xmlref = "arg:empty";
    }
    if ($_GET["resource"] != "") {
        if ($_GET["name"] != "") {
            $scriptname = htmlspecialchars($_GET["name"]);
        }
        if (preg_match("/\<[^\>]+ ref-src\=/", $result)) {
            //checar o formato do arquivo
            $arg["result"] = $result;
            $prop = pin_read_xpath(array("/resource/resource-description/format", "/resource/resource-description/size", "/resource/resource-description/@ref-src"), "arg:result");
            $format = $prop[0][0];
            $bsize = $prop[1][0];
            if ($prop[2][0] != "" && preg_match("/^([a-z0-9]*)\:(.*)$/", $prop[2][0], $matches)) {
                $result = pin_xsl_schemes ($xmlref, $matches[1], $matches[2]);
            }
        }
        pin_output_header ($scriptname, FALSE, $format, $bsize);
        if ($scriptname != "/preview.dav") {
            header("Content-Disposition: inline; filename=$scriptname");
        }
        return $result;
    } else if ($_GET["src"] != "" && preg_match("/^([a-z0-9]*)\:(.*)$/", $_GET["src"], $matches)) {
        if ($_GET["name"] != "") {
            $scriptname = htmlspecialchars($_GET["name"]);
        }
        $result = pin_xsl_schemes ($xmlref, $matches[1], $matches[2]);
        $bsize = strlen($result);
        pin_output_header ($scriptname, FALSE, "", $bsize);
        if ($scriptname != "/preview.dav") {
            header("Content-Disposition: inline; filename=$scriptname");
        }
        return $result;
    } else if (!preg_match("/\</", $result)) {
        $param["script-name"] = trim($result);
        pin_output_header ($param["script-name"], FALSE, "", $size);
        $result = pin_output_xml($xmlref, FALSE, FALSE);
        $param["script-name"] = $scriptname;
        return $result;
    } else {
        pin_output_header ($param["script-name"], FALSE, "php", $size);
        return $result;
    }
}

/**
*                                                          
* @name        pin_check_in
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $path
* @param       $user 
*
* @global      $c
*
* @see         pin_save_file()
*
* @return      
*/
function pin_check_in ( $path, $user )
{
    global $c;
    $now = mktime();
    $delay = 1800;
    if ($c["lock_delay"] != "") {
    	$delay = (int)$c["lock_delay"];
    }
    $match = "/([^\s]*)\t(".addcslashes($path, "./\"'&+-()").")\t([0-9]*)\n/i";
    $checkfile = $c["var"]."check";
    $checkstr  = file_get_contents($checkfile);
    $checkline = $user."\t".$path."\t".$now."\n";
    if (!preg_match($match, $checkstr, $matches)) {
        $checkstr = $checkstr.$checkline;
        if (pin_save_file($checkfile, $checkstr)) {
            return true;
        } else {
            return false;
        }
    } else if ((($matches[3] + $delay) > $now) && $matches[1] == $user) {
        $checkstr = str_replace($matches[1]."\t".$matches[2]."\t".$matches[3]."\n", $checkline, $checkstr);
        if (pin_save_file($checkfile, $checkstr)) {
            return true;
        } else {
            return false;
        }
    } else if (($matches[3] + $delay) < $now) {
        $checkstr = str_replace($matches[1]."\t".$matches[2]."\t".$matches[3]."\n", $checkline, $checkstr);
        if (pin_save_file($checkfile, $checkstr)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

/**
*                                                          
* @name        pin_check_out
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $path
* @param       $user
*
* @global      $c
*
* @return      
*/
function pin_check_out ( $path, $user )
{
    global $c;
    $now = mktime();
    $delay = 1800;
    $match = "/([^\s]*)\t(".addcslashes($path, "./\"'&+-():").")\t([0-9]*)\n/i";
    $checkfile = $c["var"]."check";
    $checkstr  = file_get_contents($checkfile);
    $checkline = $user."\t".$path."\t".$now."\n";
    if (!preg_match($match, $checkstr, $matches)) {
        return false;
    } else if ((($matches[3] + $delay) > $now) && $matches[1] == $user) {
        $checkstr = str_replace($matches[1]."\t".$matches[2]."\t".$matches[3]."\n", "", $checkstr);
        if (pin_save_file($checkfile, $checkstr)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

/**
*                                                          
* @name        pin_xsl_error
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $xh
* @param       $error_no
* @param       $int
* @param       $message
*
* @global      $l
*
* @return      
*/
Function pin_xsl_error($xh, $error_no, $int, $message) 
{
    global $l;
    pin_error("500", $xh." \n".$l["error"]["file"].": ".$message["URI"]."\n".$l["error"]["line"].": ".$message["line"]."\n".$l["error"]["message"].": ".$message["msg"]);
}

/**
*                                                          
* @name        pin_send_message
* @deprecated  envia uma mensagem através de cookies ou no próprio template
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $message
*
* @global      $c
* @global      $param
*
* @return      True
*/
function pin_send_message($message) 
{
    global $c, $param;
    if ($_COOKIE["pindorama_message"] != "") {
        $message = $_COOKIE["pindorama_message"]."\\n\\n".$message;
    }
    if ($c["cookies"] && setcookie("pindorama_message", $message, time()+100*5, $c["base_url"]."/")) {
        return true;
    } else {
        $param["msg"] = pin_clean_xml($message);
        return true;
    }
} // xsl_message
  

/**
*                                                          
* @name        pin_xml_request
* @deprecated  transforma a requisição HTTP em dados XML
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $self (Default = "")
*
* @global      $arg
* @global      $param
* @global      $mime
* @global      $c
* @global      $a
* @global      $types
* @global      $lang
*
* @see         pin_xml_array()
* @see         pin_files_array()
*
* @return      True
*/
function pin_xml_request($self = "")
{
    global $arg, $param, $mime, $c, $a, $types, $lang;
    if (!is_array($c["dir_index"])) {
        $c["dir_index"] = explode(" ", $c["dir_index"]);
    }
    if ($self == "") {
        $self = $_SERVER["PHP_SELF"];
    }
    /*if (!preg_match ("/\.[^\/]+$/", $self)) {
        $self = preg_replace("/\/$/", "/".$c["dir_index"][0], $self);
    }*/
    if (substr($self, -1) == "/") {
        $self .= $c["dir_index"][0];
    }
    $self = preg_replace("/\.\.(\/?)/", "\\1", $self);
    $self = preg_replace("/[^a-z\.\:\@\~\^\_\-\+0-9\/]/i", "_", $self);
    $txt = $c["xmlpi"]."\n<request>";
    $txt = $txt."\n<request-uri>".htmlspecialchars($_SERVER["REQUEST_URI"])."</request-uri>";
    $txt = $txt."\n<script-name>".$self."</script-name>";
    if ($_SERVER["REMOTE_USER"] != "") {
        $txt = $txt."\n<auth-user>".htmlspecialchars($_SERVER["REMOTE_USER"])."</auth-user>";
    } else if ($_SERVER["PHP_AUTH_USER"] != "") {
        $txt = $txt."\n<auth-user>".htmlspecialchars($_SERVER["PHP_AUTH_USER"])."</auth-user>";
    } else if ($param["user"] != "") {
        $txt = $txt."\n<auth-user>".htmlspecialchars($param["user"])."</auth-user>";
    }
    if (count($_SESSION) > 0) {
        $txt = $txt."\n<session>".pin_xml_array($_SESSION, FALSE)."</session>";
    }
    if (count($_GET) > 0) {
        $txt = $txt."\n<get>".pin_xml_array($_GET)."</get>";
    }
    if (count($_POST) > 0) {
        $txt = $txt."\n<post>".pin_xml_array($_POST, TRUE, TRUE)."</post>";
    }
    if (count($_COOKIE) > 0) {
        $txt = $txt."\n<cookies>".pin_xml_array($_COOKIE, TRUE, TRUE)."</cookies>";
    }
    if (count($_FILES) > 0) {
        $txt = $txt."\n<files>".pin_files_array()."</files>";
    }
    $txt = $txt."\n</request>";
    $arg["request"] = $txt;
    foreach($a as $k=>$v) {
        $arg[$k] = $c["xmlpi"]."<$k>".pin_xml_array($v, FALSE)."</$k>";
    }
    $param["script-name"] = $self;
    $param["request-uri"] = $_SERVER["REQUEST_URI"];
    $param["query-string"] = $_SERVER["QUERY_STRING"];
    $param["read-only"] = $c["read-only"]." ";
    $param["search-dir"] = $c["search_dir"];
    $param["data-dir"] = $c["data_dir"];
    $param["language"] = $c["language"];
    $param["templates-dir"] = $c["templates"];
    $param["host"] = ($param["host"] != "")?($param["host"]):($_SERVER["HTTP_HOST"]);
    $param["date"] = date("Y-m-d\TH:i:s");
    $param["base"] = $c["base_url"];
} // xml_request


/**
*                                                          
* @name        pin_process_reguest
* @deprecated  processes the information generated by xml_request and creates the proper response
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @global      $arg
* @global      $param
* @global      $mime
* @global      $c
* @global      $HTTP_RAW_POST_DATA
*
* @see         pin_read_xpath()
* @see         pin_redirect()
* @see         pin_output_xml()
* @see         pin_output_header()
* @see         pin_output_file()
* @see         pin_error()
* @see         pin_xml_request()
*
* @return      True
*/
function pin_process_request()
{
    // processes the information generated by xml_request and creates the proper response
    global $arg, $param, $mime, $c, $HTTP_RAW_POST_DATA;
    require($c["components"]."components.php");
    $result = "";
    if (preg_match("/^(.*)\.dav$/", $param["script-name"], $matches)) {
        $scriptname = $matches[1];
        $dav = TRUE;
    } else {
        $scriptname = $param["script-name"];
        $dav = FALSE;
    }
    $xpath[] = "/xpml/resource/uri[ . = '$scriptname']/@id";
    foreach ($c["dir_index"] as $tmp) {
        $xpath[] = "/xpml/resource/uri[ . = '$scriptname/$tmp']/@id";
    }
    $id = pin_read_xpath($xpath, "index:uris");
    if (in_array($param["script-name"], $pcom)) {
        $component = array_search($param["script-name"], $pcom);
        if (preg_match("/^([^\.]+)\.(.+)$/", $component, $matches)) {
            if (is_file($c["components"].$matches[1].".php")) {
                chdir(dirname($c["components"].$matches[1].".php"));
                require_once($c["components"].$matches[1].".php");
            } else if (is_file($c["etc"]."components/".$matches[1].".php")) {
                chdir(dirname($c["etc"]."components/".$matches[1].".php"));
                require_once($c["etc"]."components/".$matches[1].".php");
            }
            eval('$result='.$matches[2].'();');
        } else {
            eval('$result='.$component.'();');
        }
        pin_output_header($param["script-name"], FALSE, "php");
        echo $result;
        return true;
    } else if (is_array($id[0]) && $dav) {
        // editing redirects
        pin_redirect($pcom["pin_output_dav"]."?id=".$id[0][0]);
        exit();
    } else if (is_array($id[0])) {
        // pages listed in the index:uris
        $result = pin_output_xml($id[0][0]);
    } else if (is_array($id)) {
        pin_redirect($param["script-name"]."/");
        exit();
    } else if (is_array($acom)) {
        foreach($acom as $component=>$patt) {
            $tmp = "";
            if (substr($param["script-name"], 0, strlen($patt)) == $patt) {
                if (preg_match("/^([^\.]+)\.(.+)$/", $component, $matches)) {
                    if (is_file($c["components"].$matches[1].".php")) {
                        chdir(dirname($c["components"].$matches[1].".php"));
                        require_once($c["components"].$matches[1].".php");
                    }
                    eval('$tmp='.$matches[2].'();');
                } else {
                    eval('$tmp='.$component.'();');
                }  
                echo $tmp;
                return true;
            }
        }
    }
    if ($result != "" || headers_sent()) {
        echo $result;
    } else if (is_file($c["www"].$param["script-name"])) {
        echo pin_output_file($c["www"].$param["script-name"]);
    } else if (count($c["dir_index"]) > 1 && substr($param["script-name"], -1 * strlen($c["dir_index"][0])) == $c["dir_index"][0]) {
        pin_xml_request(str_replace(array_shift($c["dir_index"]), $c["dir_index"][0], $param["script-name"]));
        pin_process_request();
        return true;
    } else {
        pin_output_header($param["script-name"], FALSE, "php");
        pin_error("404", $param["request-uri"]);
        return false;
    }
    return false;
} // process_request


/**
*                                                          
* @name        pin_read_dir
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $directory
* @param       $cols (Default = "fullname is_dir size modified")
* @param       $pattern (Default = "*")
* 
*
* @return      All the files in a associative array
*/
function pin_read_dir($directory, $col = "fullname name is_dir size modified", $pattern = "*") 
{
    if (substr($directory, -1) != "/") {
        $directory = $directory."/";
    }
    $cols = explode(" ", $col);
    $a = 0;
    $arquivo = array();
    $arr = glob($directory.$pattern, GLOB_BRACE);
    if (!is_array($arr)) {
        return array();
    }
    foreach ($arr as $file) {
         if (@in_array("fullname", $cols)) {
             $arquivo[$a]["fullname"] = $file;
         }
         if (@in_array("name", $cols)) {
             $arquivo[$a]["name"] = basename($file);
         }
         if (@in_array("is_dir", $cols)) {
             if (is_dir($base.$file)) {
                 $arquivo[$a]["is_dir"] = 1;
             } else {
             	$arquivo[$a]["is_dir"] = 0;
             }
         }
         if (@in_array("size", $cols)) {
             $arquivo[$a]["size"] = filesize($file);
         }
         if (@in_array("modified", $cols)) {
             $arquivo[$a]["modified"] = date("Y-m-d H:i:s", filemtime($file));
         }
         $a++;
    }
	return ($arquivo);
}

/**
*                                                          
* @name        pin_read_rdir
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $directory
* @param       $cols (Default = "fullname is_dir size modified")
* @param       $pattern (Default = "*")
* @param       $include_dir (Default = false)
*
* @return      True
*/
function pin_read_rdir($directory, $cols = "fullname name is_dir size modified", $pattern = "*", $include_dir = false)
{
    $res = pin_read_dir($directory, $cols, $pattern);
    $arquivos = array();
    if(!is_array($res)) {
        return array();
    }
    foreach ($res as $tmp) {
        if ($tmp["is_dir"]==1) {
            if ($include_dir) {
                $arquivos[]=$tmp;
            }
            $arquivos = array_merge($arquivos, pin_read_rdir($directory."/".$tmp["name"], $cols, $pattern, $include_dir));
        } else {
            $arquivos[]=$tmp;
        }
    }
    return $arquivos;
}
    
/**
*                                                          
* @name        pin_uris
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $directory (Default = "")
*
* @global      $c
*
* @see         pin_copy_xpath()
* @see         pin_read_dir()
*
* @return      True
*/
function pin_uris($directory = "") 
{
    global $c;
    $dir = "";
    $tmpfile = preg_replace("/\.uri$/", "", $directory);
    if (is_file($c["www"].$tmpfile)){
        $uris = "<uri id='$tmpfile'>$tmpfile</uri>";
        $uris = $c["xmlpi"]."<xpml><meta/><resource name='uris'>$uris</resource></xpml>";
        return $uris;
    } else if (preg_match("/^([a-z0-9]+\:[a-z\_\-0-9]+)(\.[a-z0-9]+)?$/", $directory, $matches)) {
        $xp = "/xpml/resource/uri[@id = '{$matches[1]}']";
        $uris = pin_copy_xpath($xp, "index:uris");
        $uris = $c["xmlpi"]."<xpml><meta/><resource name='uris'>$uris</resource></xpml>";
        return $uris;
    }
    if (preg_match("/^\/[^(\.\.):]+$/", $_GET["dir"])) {
        $dir = preg_replace("/\/+$/", "", $_GET["dir"]);
    }
    $xp = "/xpml/resource/uri[starts-with(., '$dir')]";
    $uris = pin_copy_xpath($xp, "index:uris");
    $files = ($directory == "")?(pin_read_rdir($c["www"].$dir, "fullname name is_dir", "*", true)):(pin_read_dir($c["www"].$dir, "fullname name is_dir"));
    foreach ($files as $tmp) {
        $name = (strpos($tmp["fullname"], $c["www"]) !== false)?(substr($tmp["fullname"], strlen($c["www"]))):($tmp["fullname"]);
        if ($tmp["is_dir"]==1) {
            $uris .= "<uri id=''>$name/_</uri>";
        } else {
            $uris .= "<uri id='$name'>$name</uri>";
        }
    }
    $index = $c["xmlpi"]."<xpml><meta/><resource name='uris'>$uris</resource></xpml>";
	return ($index);
}

/**
*                                                          
* @name        pin_image_info
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $str
*
* @global      $c
* @global      $arg
* @global      $param 
* 
* @see         pin_xml_array()
*
* @return      True
*/
function pin_image_info($str)
{
    global $c, $arg, $param;
    chdir($c["etc"]."image/");
    if (!function_exists('pin_create_image_info')) {
        require_once($c["components"]."image.php");
    }
    $res = pin_xml_array(pin_create_image_info($str));
    
    return $res;
}

/**
*                                                          
* @name        pin_file_info
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $str
*
* @global      $c
* @global      $arg
* @global      $param
* @global      $mime
*
* @see         pin_xml_array()
* 
* @return      True
*/
function pin_file_info($str)
{
    global $c, $arg, $param, $mime;
    if (is_file($c["www"].$str)) {
        $file = pathinfo($c["www"].$str);
        $file["format"] = $mime[$file["extension"]];
        $file["size"] = filesize($c["www"].$str);
        $file["ksize"] = (int)($file["size"] / 1024);
    } else {
        $file = parse_url($str);
        $file += pathinfo($file["path"]);
        $file["format"] = $mime[$file["extension"]];
    }
    $file["url"] = $str;
    $res = $c["xmlpi"].pin_xml_array($file,TRUE, FALSE, "file" );
    return $res;
}

/**
*                                                          
* @name        pin_dav_javascript
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $str
*
* @global      $arg
* @global      $param
* @global      $c
* @global      $l
*
* @see         pin_output_header()
* 
* @return      True
*/
function pin_dav_javascript()
{
    global $arg, $param, $c, $l;
    $js = "var msgstr = {";
    foreach ($l["javascript"] as $k=>$v){
        if ($v != "") {
            $js .= "$k : '$v',"; 
        }
    }
    $js .= "lang : '".$c["language"]."'};\n";
    $js .= ($param["referer"] != "")?("var pin_scriptname = '{$param['referer']}';\n"):("var pin_scriptname = '';");
    $js .= "var base_url = '{$c['base_url']}';\n";
    $js .= file_get_contents($c["components"]."dav/dav.js");
    pin_output_header ($param["script-name"], TRUE, "js", strlen($js));
    echo $js;
} // preview_uris


/**
*
*                                                          
* @name        pin_dav_javascript_menu
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
*
* @global      $arg
* @global      $param
* @global      $c
* @global      $l
*
* @see         pin_xls_process()
* @see         pin_dav_javascript()
* 
* @return      True
*/
function pin_dav_javascript_menu()
{
    global $arg, $param, $c, $l;
    $param["referer"] = pin_clean_xml($_SERVER["HTTP_REFERER"]);

    $url = parse_url($_SERVER["HTTP_REFERER"]);
    $self = $url["path"];
    if (!is_array($c["dir_index"])) {
        $c["dir_index"] = explode(" ", $c["dir_index"]);
    }
    if (substr($self, -1) == "/") {
        $self = substr($self, 0, strlen($self) -1);
    }
    $self = preg_replace("/\.\.(\/?)/", "\\1", $self);
    $self = preg_replace("/[^a-z\.\:\@\~\^\_\-\+0-9\/]/i", "_", $self);
    
    if (preg_match("/^(.*)\.dav$/", $self)) {
        exit();
    }
    $xpath[] = "/xpml/resource/uri[ . = '$self']/@id";
    foreach ($c["dir_index"] as $tmp) {
        $xpath[] = "/xpml/resource/uri[ . = '$self/$tmp']/@id";
    }
    $id = pin_read_xpath($xpath, "index:uris");
    if (is_array($id)) {
        foreach ($id as $xid) {
            if (is_array($xid)) {
                $param["referer-id"] = $xid[0];
                break;
            }
        }
    }
    $param["referer"] = $self;
    $menu = pin_xsl_process("arg:empty", $c["stylesheets"]."dav/dav_header.xsl");
    $menu = "document.write(\"".str_replace(array('"', "\n", "\r"), array('\\"', '\n', '\r'), $menu)."\");\n";
    echo $menu;
    pin_dav_javascript();
}

/**
*                                                          
* @name        pin_dav_files
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @global      $param
* @global      $c
* @global      $l
* @global      $acom
*
* @see         pin_output_file()
* 
* @return      True
*/
function pin_dav_files()
{
    global $param, $c, $l, $acom;
    include($c["components"]."components.php");
    $file = substr($param["script-name"], strlen($acom["pin_dav_files"]));
    return pin_output_file ($c["components"]."dav".$file);
}


/**
*                                                          
* @name        pin_log_xpml
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $msg
*
* @global      $c
*
* @see         pin_xml_array()
* 
* @return      True
*/
function pin_log_xpml($msg)
{
    global $c;
    error_log("\n".$msg, 3, $c["logfile"]);
}

/**
*                                                          
* @name        pin_check_permission
* @deprecated  
* @version     0.11
*
* @author      Guilherme Capilé <hide@address.com>
*
* @param       $id
* @param       $action (Default = "read")
* @param       $user (Default = "")
*
* @global      $c
* @global      $g
* @global      $param
*
* @see         pin_read_xpath()
* 
* @return      True
*/
function pin_check_permission($id, $action = "read", $user = "")
{
    global $c, $g, $param;
    if ($c["permissions"]) {
        if ($user == "") {
            if ($_SERVER["REMOTE_USER"] != "") {
                $user = $_SERVER["REMOTE_USER"];
            } else if ($_SERVER["PHP_AUTH_USER"] != "") {
                $user = $_SERVER["PHP_AUTH_USER"];
            } else {
                $user = $param["user"];
            }
        }
        if ($user == "admin") {
            return true;
        }
        if ($id == "none") {
            return true;
        }
        $xperm = pin_read_xpath(array("/xpml/meta/rights[@ref != '']/@ref", "/xpml/meta/rights[action = '$action']/@ref"), $id);
        if (is_array($xperm[0])) {
            if (!is_array($g)) {
                include_once($c["users"]."permissions.php");
            }
            $perm = FALSE;
            if (is_array($xperm[1])) {
                foreach ($xperm[1] as $allgrp) {
                    if (in_array($user, explode(" ", $g[$allgrp]))){
                        $perm = TRUE;
                        break;
                    }
                }
            }
            
            if (!$perm){
                return false;
            }
        }
    }
    return true;
}

function pin_url2query($str, $prefix)
{
    $r = array();
    $patt[] = "/( src=\")([^#\"][^\"]*)(\")/";
    $patt[] = "/( src=')([^#'][^']*)(')/";
    $patt[] = "/( src=)([^\"'#][^ ]*)/";
    $patt[] = "/( action=\")([^#\"][^\"]*)(\")/";
    $patt[] = "/( action=')([^#'][^']*)(')/";
    $patt[] = "/( action=)([^\"'#][^ ]*)/";
    $patt[] = "/([ \.]href=\")([^#\"][^\"]*)(\")/";
    $patt[] = "/([ \.]href=')([^#'][^']*)(')/";
    $patt[] = "/( href=)([^\"'#][^ ]*)/";
    $patt[] = "/( url\([\"']?)([^\"\']+)([\"']?\))/";
    foreach ($patt as $tmp) {
        preg_match_all($tmp, $str, $m);
        $r[0] = array_merge($r[0], $m[0]);
        $r[1] = array_merge($r[1], $m[1]);
        $r[2] = array_merge($r[2], $m[2]);
        $r[3] = array_merge($r[3], $m[3]);
    }
    for($i = 0; $i < count($r[0]);$i++) {
        $r[4][$i] = $r[1][$i].$prefix.str_replace(array("?", ":", "&amp;", "&"), array(urlencode("?"), urlencode(":"), urlencode("&"), urlencode("&")), $r[2][$i]).$r[3][$i];
    }
    return $a.str_replace($r[0], $r[4], $str);
}

if (!function_exists("file_get_contents")) {
function file_get_contents($filename) {
   $fd = fopen("$filename", "rb");
   $content = fread($fd, filesize($filename));
   fclose($fd);
   return $content;
}
}
?>
Return current item: Pindorama