<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * Display informations from a specific package
 *
 * PHP version 5
 *
 * Copyright © 2010 Remi Collet
 *
 * This file is part of rpmphp.
 *
 * rpmphp is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * rpmphp is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with rpmphp.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @category  Main
 * @package   RPMPHP
 *
 * @author    Remi Collet <unknown@unknwown.com>
 * @author    Johan Cwiklinski <johan@x-tnd.be>
 * @copyright 2010 Remi Collet
 * @license   http://www.gnu.org/licenses/agpl-3.0-standalone.html AGPL License 3.0 or (at your option) any later version
 * @link      http://github.com/remicollet/rpmphp/
 * @since     The begining of times.
*/
require 'include/main.php';

$fedcli = new FedoraPkgdb();

$name = $_GET['rpm'];
$type = (isset($_GET['type']) ? $_GET['type'] : "html");

$smarty->assign('name_required', true);
$smarty->assign('name', $name);
$ariane[] = array(
    'url'   => '#',
    'text'  => 'Package: ' . $name
);
$ajax_infos = '<span class="ajax">(wait for ajax or <a href="' .
    $_SERVER['PHP_SELF'] . '?rpm='.$name.
    '&amp;pkgdb=1">reload with pkgdb</a>)</span>';
$smarty->assign('ajax_infos', $ajax_infos);
$smarty->assign('ariane', $ariane);
$smarty->assign('page_title', 'Package: ' . $name);

/**
* Retrieve people informations for a specific branch
*
* @param array $params Array of parameters
*
* @return string
*/
function getBranchPeople($params)
{
    global $fedpkg;

    $branch = $people = null; // avoid IDE warning
    extract($params);
    $ret = null;
    if (isset($fedpkg[$branch]['owner'])) {
        if ( !$people || $people == '' || $people == 'owner' ) {
            $ret = $fedpkg[$branch]['owner'];
        } else if ( $people == 'people') {
            $ret_tmp = $fedpkg[$branch]['people'];
        }
    }
    if ( $people == 'people') {
        foreach ( $ret_tmp as $r ) {
            if ( $ret !== null ) {
                $ret .= ', ';
            }
            $ret .= $r['username'];
        }
    }
    return $ret;
}
$smarty->register_function('getBranchPeople', 'getBranchPeople');

if ( !isset($name) || !$name ) {
    $smarty->assign('error', 'missing_name');
} else {
    try {
        $db = new PDO ("mysql:dbname=" . MYBASE . ";host=" . MYHOST, MYUSER, MYPASS);

        $uptable = new TableUpstream($db);

        $sql = "SELECT rpm.*,
            CONCAT(repo.url,rpm.name,'-',rpm.ver,'-',rpm.rel,'.src.rpm') as rpmurl
            FROM rpm
            INNER JOIN repo ON (repo.main=rpm.repo_main AND repo.sub=rpm.repo_sub)
            WHERE rpm.name='$name'
            ORDER BY repo.id DESC";
        $resrpm = $db->query($sql);
        $rpm = ($resrpm ? $resrpm->fetchObject() : false);

        $up = $uptable->find(array('name'=>$name));

        $sql = "SELECT * FROM acls WHERE name = '$name'";
        $resown=$db->query($sql);
        $owner = ($resown ? $resown->fetchObject() : false);

        if (isset($owner->name)) {
            // Use exact name (with case) from acl (else pkgdb could fail)
            $name = $owner->name;
            $smarty->assign('name', $name);
            $smarty->assign('page_title', 'Package: ' . $name);
        }

        if (!$rpm) {
            echo "<h1>$name not found</h1>\n";
        } else {
            if ($rpm->summary) {
                $summary['Summary'] = $rpm->summary;
            } else if ($owner->summary) {
                $summary['Summary'] = $owner->summary;
            }
            $summary['Description'] = (
                (isset($fedpkg['devel']['package']['description'])) ?
                $fedpkg['devel']['package']['description'] :
                $ajax_infos
            );
            if ( $rpm->url ) {
                $summary['URL'] = $rpm->url;
            }
            if ($up && $up['type']) {
                $summary['Type'] = $up['type'];
            }
            if ($up && $up['channel']) {
                $summary['Channel'] = $up['channel'];
            }
            if ($up && $up['stable']) {
                $summary['Stabe version'] = $up['stable'];
            }
            if ($up && $up['unstable'] && $up['stable']!=$up['unstable']) {
                $summary['Unstable version'] = $up['unstable'];
                if ($up['state']) {
                    $summary['Unstable version'] .= ' (' . $up['state'] . ')';
                }
            }

            if ($owner && $owner->owner) {
                $summary['Owner'] = $owner->owner;
                if ($owner->cc) {
                    $summary['Owner'] .= ' (' . $owner->cc . ')';
                }

                // Only when owner (so we have the exact name)
                $summary['Bugzilla'] = 'https://bugzilla.redhat.com/buglist.cgi'.
                    '?bug_status=NEW&amp;bug_status=ASSIGNED&amp;bug_status=ON_QA' .
                    '&amp;component=' . $name;
            }
            $summary['GitWeb']
                = 'http://pkgs.fedoraproject.org/gitweb/?p=' . $name . '.git';

            $summary['PkgDB'] = $fedcli->getPackageURL($name);

            if (isset($_GET['pkgdb'])) {
                $fedpkg = $fedcli->getPackageInfo($name);
            } else {
                $fedpkg = false;
            }
            $i=0;

            $prev=false;
            do {
                $packages[] = $rpm;
                if ( $rpm->repo_main != $prev ) {
                    $prev = $rpm->repo_main;
                }
            } while ( $rpm = $resrpm->fetchObject() );
        }
        $smarty->assign('pkgdb', (isset($_GET['pkgdb']) ? $_GET['pkgdb'] : null));
        $smarty->assign('summary', $summary);
        $smarty->assign('packages', $packages);
        $smarty->assign('fedpkg', $fedpkg);
    } catch(PDOException $e) {
        $smarty->assign(
            'error',
            sprintf("%s ERREUR : %s\n", date("r"), $e->getMessage())
        );
    }
}

if ($type == "json") {
    // Displays the output as json (TODO : why not use json_encode)
    header('Content-Type: application/json');

    $json = "{";
    $json .= '"package":"' . $name ."\",";
    $json .= '"branch":[';
    $cnt = 0;
    foreach ($packages as $package) {
        $cnt += 1;
        $json .= "{";
        $json .= '"'. $package->repo_main .'":"';
        if ($package->epoch) {
            $json .= $package->epoch.':';
        }
        $json .= $package->ver."-".$package->rel.'"}';
        if ($cnt != count($packages)) {
            $json .= ",";
        }
    }
    $json .= "]}";
    echo $json;
} else if ($type == "text") {
    // Displays the output as text
    header('Content-Type: text/plain');

    $text = 'package: ' . $name ." \n";
    $cnt = 0;
    foreach ($packages as $package) {
        $cnt += 1;
        $text .= $package->repo_main .': ';
        if ($package->epoch) {
            $text .= $package->epoch.':';
        }
        $text .= $package->ver."-".$package->rel."\n";
    }
    echo $text;
} else {
    // Displays the output as html
    $page_content = $smarty->fetch('zoom.tpl');
    $smarty->assign('page_content', $page_content);
    $smarty->display('main.tpl');
}
?>