Sitemap med PHP (v. 2008-08-23)
Om sitemappet
Sitemap-scriptet åbner alle mapper og oplister alle filer fra en givent mappe - f.eks. roden af ens website. Filerne oplistes alfabetisk og filstørrelsen bliver angivet for hver fil. Kun kendte filtyper (angives i koden) vises og specifikke filer kan udelades. For kendte filtyper vises et ikon der indikere filtypen - alle ikoner kommer fra FAMFAMFAM.
Sitemap-funktionen kaldes med 4 parametre:
Funktionskald
<?php
echo sitemap(
$start_sti,
$filtyper,
$hemmelige_filer,
$antal_links_ad_gangen);
?>
- $start_sti angiver navnet på det bibliotek som er udgangspunkt for sitemappet. Alle undermapper og filer indlæses. Kaldes funktionen med "." (et punktum) som første argument, søges med start i det bibliotek filen med koden ligger i.
- $filtyper angiver hvilke filtyper der skal læses. Angives den tomme streng "" oplistes kun default-typerne: php, phps, html, htm, shtml, xhtml, dhtml, asp, aspx, jsp, txt, pdf, doc, ppt, pps, avi, mpg, wmv, mp3, mid, exe, rar og zip.
- $hemmelige_filer kan bruges til at udelukke bestemte filer fra at blive oplistet, f.eks. hemmelige filer eller underordnede sider som stylesheets m.v. Kan angives som den tomme streng "" hvis alle filer skal indlæses.
- $antal_links_ad_gangen angiver hvor mange links der skal vises ad gangen på siden. Der bliver automatisk vist links til næste og evt. forrige side.
Kode
Nedenfor er vidst et eksempel på hvordan funktionen kaldes samt koden til funktionen. Desuden kan det også ses hvordan filtyper angives som andet argument. Eksemplet kan kopieres og indsættes i en tom fil som f.eks. kunne kaldes »sitemap.php« og sitemappet er klar til brug. NB. koden benytter sig af en række ikon-filer - hvis du ønsker at bruge disse skal du downloade eksemplet øverst på siden.
sitemap.php
<?php
/**
* PHP Sitemap
* Version: 2008-08-23
* Author: Christian L. Dünweber
* Webpage: http://www.dunweber.com/docs/scripts/#sitemap
* Copyright (C) 2006-2008 Christian L. Dünweber
* This program is distributed under the GNU General Public License,
* see <http://www.gnu.org/licenses/gpl.html>.
* Icons by courtesy of <http://www.famfamfam.com/>
*/
// Kalder funktionen:
$start_path = '.';
$allowed_types = 'php,htm,mp3'; //Escape regex characters
$exclude_paths = 'hemmelig_fil\.htm,mv\.php'; //Escape regex characters
$links_pr_page = 20;
echo sitemap($start_path, $allowed_types, $exclude_paths, $links_pr_page);
// Kildekode til funktionen:
/**
* Lists and links all files in specified directory and subdirectories.
* Only specified file types are listed and files can be excluded.
* The numberOfPages of files listed pr. page can be specified.
*
* @param string Path of directory to be listed. Set to '.' for same dir as this script.
* @param string Which file types should be read. Comma separated list, e.g. 'php,htm'.
* @param string Files to be excluded. Comma separated list, e.g. 'file.php,file.htm'.
* @param integer How many results should be shown pr. page. Set to even value, e.g. 20.
* @return string HTML output with links to the read files.
* @see openDirs()
* @see limitResults()
*/
function sitemap($startPath = '.', $fileTypes, $excludeFiles, $filesPerPage)
{
// Init the array for all read directories with the start path.
$dirs[] = $startPath;
// If the user hasn't informed about which file types to read,
// the most common are used.
if(!$fileTypes) {
$fileTypesStr = "\.(php|phps|html|htm|shtml|xhtml|dhtml|asp|aspx|jsp|txt|
pdf|doc|ppt|pps|avi|mpg|wmv|mp3|mid|exe|rar|zip)$";
}
else {
$fileTypes = trim(preg_replace('/\s/','',$fileTypes));
$fileTypesArr = explode(',',$fileTypes);
$fileTypesStr = '\.(' . implode('|',$fileTypesArr) . ')$';
}
// It the user has supplied a comma separated list of exclude files this is used
if($excludeFiles) {
$excludeFiles = trim(preg_replace('/\s/','',$excludeFiles));
$excludeFilesArr = explode(',',$excludeFiles);
$excludeFilesStr = '^(' . implode('|',$excludeFilesArr) . ')$';
}
// If the start dir given by the user can be opened and if it
// contains any readable files, these are shown.
if(is_string($result = openDirs($dirs,$fileTypesStr,$excludeFilesStr))) {
$sitemap = '<p class="red">Could not open the diretory <em>'.$result.'</em></p>';
}
else {
if(count($result) > 0) {
// The number of opened directories shown to the user are
// limited to the specified number at a time.
$sitemap = limitResults($result, $filesPerPage);
}
else {
$sitemap = '<p class="red"><strong>No files in '.$result[0].'</strong></p>';
}
}
return $sitemap;
}
/**
* Lists and links all files in specified directory and subdirectories.
*
* @param array Array with only the first element set - top dir to be opened.
* @param string Which file types should be read.
* @param string Files to be excluded.
* @return array/string Returns an array on success - a string on false (no files found).
*/
function openDirs($dirs, $fileTypes, $excludeFiles)
{
// The directories in $dirs are opened and read.
for($i=0; $i<count($dirs); $i++) {
if(is_dir($dirs[$i]) && $dh = opendir($dirs[$i])) {
while(false != ($file = readdir($dh))) {
// If the opened directory contains any sub directories, theese are
// put into $dirs so that these also are opened and read.
if(is_dir($file) && $file != '.' && $file != '..') {
$dirs[] = $dirs[$i] .'/'. $file;
}
elseif(is_dir($dirs[$i] .'/'. $file) && $file != '.' && $file != '..') {
$dirs[] = $dirs[$i] .'/'. $file;
}
else {
$fileName = strtolower($file);
if(preg_match('/'.$fileTypes.'/', $fileName) &&
!preg_match('/'.$excludeFiles.'/', $fileName)) {
$url = $dirs[$i].'/'.$file;
$url = preg_replace('/^\.\//','',$url);
// Links are made to the read files and these are
// collected intp an array.
$fileList[] = makeLink($url);
$dirNames[] = $dirs[$i];
}
}
}
closedir($dh);
}
else {
// If a directory couldn't be opened, this is returned as a string.
// This way the user can be informed.
return $dirs[$i];
}
}
// Otherwise the opened directories are sorted according to filenames
// and are returned.
array_multisort($dirNames,SORT_ASC, $fileList);
return $fileList;
}
/**
* Lists and links all files in specified directory and subdirectories.
*
* @param array Array of files to be listed.
* @param string How many results should be shown per page.
* @return string HTML-formatted string with the read files in <ul><li></li></ul> format.
*/
function limitResults($results, $resultsPerPage)
{
$startNr = $_GET['startNr'];
$numberOfPages = count($results);
// If an uneven number of $resultsPerPage has been given
// this added up to the next even number - otherwise it
// could display the same link twice.
if($resultsPerPage%2 == 1) {
$resultsPerPage = $resultsPerPage+1;
}
// If the number of read pages is smaller than the number
// of pages to display per page, $resultsPerPage is set
// equal to the number of pages.
if($numberOfPages < $resultsPerPage) {
$resultsPerPage = $numberOfPages;
if($resultsPerPage%2 == 1) {
$resultsPerPage = $resultsPerPage+1;
}
}
if(!$startNr || $startNr < 0) {
$startNr = 0;
}
$endNr = $startNr + $resultsPerPage;
if($endNr > $numberOfPages) {
$endNr = $numberOfPages;
}
// If there are more links to display than allowed at a time
// navigation links to those not shown are made.
if($numberOfPages > ($startNr + $resultsPerPage)) {
$nextStartNr = $startNr + $resultsPerPage;
$next = '<a href="?startNr='.$nextStartNr.'">Næste >></a>';
} else {
$next = '<span style="color:gray;">Næste >></span>';
}
if($startNr > 0 && ($startNr - $resultsPerPage) < $numberOfPages) {
$prevStartNr = $startNr - $resultsPerPage;
$prev = '<a href="?startNr='.$prevStartNr.'"><< Forrige</a>';
} else {
$prev = '<span style="color:gray;"><< Forrige</span>';
}
// The number of links are limited to the specified number at a time.
// The links are shown in two columns.
for($i=$startNr; $i<$startNr+$resultsPerPage/2; $i++) {
$firstCol[] = $results[$i];
}
for($i=$startNr+$resultsPerPage/2; $i<$endNr; $i++) {
$secondCol[] = $results[$i];
}
$sitemap = '';
// The two columns are put into a table.
for($i=0; $i<$resultsPerPage/2; $i++) {
$sitemap .= '<tr>' . $firstCol[$i] . '<td style="width:50px;">
</td>' . $secondCol[$i] . '</tr>';
}
$sitemap = '<table>' . $sitemap . '</table>';
return '<p>Viser '.$startNr.' til '.$endNr.' af '.$numberOfPages.'</p>
<p>' . $prev.' | '.$next .'</p>'. $sitemap;
}
/**
* Makes a link of the parameter URL. An icon is prepended in the
* link according to the file type of the URL. All icons used are
* found at http://www.famfamfam.com - nice work!
*
* @param string The URL that should be linked to.
* @return string HTML-formatted string with the link.
*/
function makeLink($url)
{
// Info on the file size
$size = '<td><small>'.round(filesize($url)/1024,2).' kB</small></td>';
if(strlen($url) > 40) {
$urlShown = wordwrap($url,40,'<br />',1);
}
else {
$urlShown = $url;
}
// Link to the file with icon
$link = array('<td><img src="icons/',
'" alt="" /></td><td><a href="'.$url.'">'.$urlShown.'</a></td>'.$size);
// Assigning icons to file types and returning link
if(preg_match('/\.pdf$/', $url)) {
$icon = 'acrobat.png';
return implode($icon, $link);
}
elseif(preg_match('/\.doc$/',$url)) {
$icon = 'word.png';
return implode($icon, $link);
}
elseif(preg_match('/\.(ppt|pps)$/',$url)) {
$icon = 'powerpoint.png';
return implode($icon, $link);
}
elseif(preg_match('/\.(php|phps)$/',$url)) {
$icon = 'php.png';
return implode($icon, $link);
}
elseif(preg_match('/\.(avi|mpg|mpeg|wmv)$/',$url)) {
$icon = 'video.png';
return implode($icon, $link);
}
elseif(preg_match('/\.(mp3|wma|mid)$/',$url)) {
$icon = 'sound.png';
return implode($icon, $link);
}
elseif(preg_match('/\.(jpg|jpeg|gif|png|tiff|bmp|ico|odg|pdn)$/',$url)) {
$icon = 'picture.png';
return implode($icon, $link);
}
elseif(preg_match('/\.(zip|rar|tar|gz)$/',$url)) {
$icon = 'compressed.png';
return implode($icon, $link);
}
elseif(preg_match('/\.(exe|bat|com|msi|jar)$/',$url)) {
$icon = 'application.png';
return implode($icon, $link);
}
elseif(preg_match('/\.(html|htm|shtml|dhtml|xhtml)$/',$url)) {
$icon = 'world.png';
return implode($icon, $link);
}
else {
$icon = 'generic.png';
return implode($icon, $link);
}
}
?>