<?php

/*
 * $Horde: chora/common.php,v 1.32 2001/03/18 01:52:45 avsm Exp $
 *
 * Copyright 2000,2001 Anil Madhavapeddy <anil@recoil.org>
 * Copyright 2000,2001 Charles Hagenbuch <chuck@horde.org>
 *
 * See the enclosed file COPYING for license information (GPL).  If you
 * did not receive this file, see http://www.fsf.org/copyleft/gpl.html.
 */

require_once dirname(__FILE__).'/config/conf.php';
require_once dirname(__FILE__).'/config/cvsroots.php';
require_once dirname(__FILE__).'/config/mime.php';
require_once dirname(__FILE__).'/lib/CVSLib.php';
require_once dirname(__FILE__).'/lib/version.php';

/* Variable we wish to propagate across web pages
 *  sbt = Sort By Type (name, age, author, etc)
 *  ha  = Hide Attic Files
 *  ord = Sort order
 *
 * Obviously, defaults go into $defaultActs :)
 * TODO: defaults of 1 will not get propagated correctly - avsm
 */

$defaultActs = array ( "sbt"=>CVSLIB_SORT_NONE, "sa"=>0, 
                       "ord"=>CVSLIB_SORT_ASCENDING );

foreach ($cvsroots as $key=>$val) {
    
    if (isset($val['default']) || !isset($defaultActs['rt'])) {
        $defaultActs['rt'] = $key;
    }
}

$acts = $defaultActs;

/* See if any have been passed as GET variables, and if
 * so, assign them into the acts array */

while (list($key,)=each($acts)) {
  if (!empty($$key)) {
    $acts[$key]=$$key;
  }
}

if (!isset($cvsroots[$acts['rt']])) {
   fatal(404,'Malformed URL');
}

$cvsrootopts = $cvsroots[$acts['rt']];

$cvsroot = $cvsrootopts['location'];

$conf['paths']['cvsRoot'] = $cvsrootopts['location'];
$conf['paths']['cvsusers'] = "$cvsroot/".@$cvsrootopts['cvsusers'];
$conf['paths']['introText'] = dirname(__FILE__).'/config/'.@$cvsrootopts['intro'];
$conf['options']['introTitle'] = @$cvsrootopts['title'];
$conf['options']['cvsRootName'] = $cvsrootopts['name'];

$CVS = new CVSLib($conf, $mime);

/*
 * Return an array with the names of any of the variables we
 * need to keep, that are different from the defaults
 *
 * @ret Array containing names/vals of differing variables
 */
function differingVars() {
    global $acts, $defaultActs;
    reset($acts);
    $ret = array();
    while (list($key,$val) = each($acts)) {
        if ($val != $defaultActs[$key]) {
            $ret[$key]=$val;
        }
    }
   return $ret;
}

/**
  * Generate a series of HIDDEN input forms based on the 
  * GET parameters which are different from the defaults
  *
  * @param except Array of exceptions to never output
  * @return A set of INPUT tags with the different variables
  */
function generateHiddens($except=array()) {
    global $acts;
    $toOut = differingVars();
    $ret = "";
    while (list($key,$val) = each($toOut)) {
        if (is_array($except) && !in_array($key, $except)) {
            $ret .= "<input type=\"hidden\" name=\"$key\" value=\"$val\" />\n";
        }
    }
    return $ret;
}

/**
  * Generate A HREF tags for urls found within an input string
  * Only http and ftp URIs are scanned for.
  *
  * @param text The input text to be scanned for URLs
  * @return The processed text with <A HREF> tags
  */
function htmlify ($text) {
    /* TODO: cleanup all this - avsm */
    return preg_replace('|<br />(\W*<br />)+|','<br />',preg_replace('|<br>|','<br />',nl2br(trim(preg_replace('%(http|ftp)(://\S+)%', '<a href="\1\2">\1\2</a>', htmlspecialchars($text))))));
}

/**
  * Convert a commit-name into whatever the user wants
  * @param commit name
  * @return transformed name 
  */
function showAuthorName($name, $fullname=false) {
    global $cvsusers, $CVS;

    if (!isset($cvsusers)) {
        $cvsusers = $CVS->parseCVSUsers();
    }

    if (is_array($cvsusers) && isset($cvsusers[$name])) {
        return '<a href="mailto:'.$cvsusers[$name]['mail'].'">'.($fullname?$cvsusers[$name]['name']:$name).'</a>'.($fullname?" <i>($name)</i>":'');
    } else {
        return $name;
    }
}

/**
  * Output an error page with relevant HTTP error headers
  *
  * @param errcode The HTTP error number and text
  * @param errmsg The verbose error message to be displayed
  */
function fatal ($errcode, $errmsg) {
    global $conf,$phpgw;
    //header("Status: $errcode");
    include($conf['paths']['templates'].'/error_page.inc');
	$phpgw->common->phpgw_footer();
    $phpgw->common->phpgw_exit();
}

/**
  * Given a return object from a CVSLib call, make sure
  * that it's not a CVSLib_Error object.
  * @param e Return object from a CVSLib call
  */
function checkError($e) {
    if (is_object($e) && $e->id()==CVSLIB_ERROR) {
        fatal($e->error_header(), $e->error_body());
    }
}

function repositories() {
    global $cvsroot, $cvsroots, $defaultActs, $phpgw;
    $arr = array();
    foreach ($cvsroots as $key=>$val) {
        if ($cvsroot != $val['location']) {
            $arg = (($defaultActs['rt'] == $key)?'':$key);
            $arr[] = '<b><a href="' . $phpgw->link('/chora/cvs.php','rt=' . $arg).'">'.$val['name'].'</a></b>';
        }
    }

    if (sizeof($arr)) {
       return 'Other Repositories: '.implode(' , ', $arr);
    } else {
       return "";
    }
}

if (!isset($HTTP_SERVER_VARS['PATH_INFO'])) {
    $HTTP_SERVER_VARS['PATH_INFO'] = '';
}

/* Location relative to the CVSROOT */
//$where = preg_replace("|^/|", '', $HTTP_SERVER_VARS['PATH_INFO']);
//$where = preg_replace("|\.\.|", '', $where);
//$where = preg_replace('|/$|', '', $where); 

/* Location of this script (e.g. /chora/cvs.php) */
$scriptName = preg_replace('|^/?|', '/', $HTTP_SERVER_VARS['SCRIPT_NAME']); 
$scriptName = preg_replace('|/$|', '', $scriptName); 

/* Path to the script base (e.g. /chora) */
$scriptPath = dirname($scriptName);
$fullname = "$cvsroot/$where";

$wherePath = '';
$wherePath_arr = explode('/',$where);

if (!@is_dir($cvsroot)) {
    fatal("500 Internal Error","CVSROOT not found!  This could be a misconfiguration by the server administrator, or the server could be having temporary problems.  Please try again later.");
}

function url($script, $uri='', $args = array(), $anchor='')
{
    global $scriptPath;
    $url=$scriptPath.'/'.$script.'.php'.'/'.$uri;
    $arglist = array_merge(differingVars(), $args);
    $argarr = array();
    while (list($key, $val)=each($arglist)) {
        if ($val) $argarr[] = "$key=$val";
    }
    if (sizeof($argarr)>0) {
        $url = "$url?".implode('&',$argarr);
        $glue = '&';
    } else {
        $glue = '?';
    }

    if (!empty($implodedQuery)) {
        $url = "$url$glue$implodedQuery";
    }

    if (!empty($anchor)) {
        $url .= "#$anchor";
    }

    $url = preg_replace('|/\?|','?',$url);
    return htmlspecialchars(preg_replace('|/+|','/',$url)); 
}
 
function graphic($name) {
    //global $scriptPath;
	global $phpgw;
	$imgpath = $phpgw->common->get_image_path('chora');
    return $imgpath.SEP.$name; 
}
?>
