<?php
  /**
   * phpaga
   *
   * Return simple query results
   *
   * This page is called by xmlhttprequests.
   *
   * @author Florian Lanthaler <florian@phpaga.net>
   * @version $Id: service.php 872 2007-10-01 13:57:15Z florian $
   *
   * Copyright (c) 2005, Florian Lanthaler <florian@phpaga.net>
   *
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are
   * met:
   *
   *    * Redistributions of source code must retain the above copyright
   *      notice, this list of conditions and the following disclaimer.
   *
   *    * Redistributions in binary form must reproduce the above copyright
   *      notice, this list of conditions and the following disclaimer in
   *      the documentation and/or other materials provided with the
   *      distribution.
   *
   *    * Neither the name of Florian Lanthaler nor the names of his
   *      contributors may be used to endorse or promote products derived
   *      from this software without specific prior written permission.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
   * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
   * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
   * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
   * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   */

include_once("./config.php");

if (!isset($_REQUEST["saction"]) || !is_numeric($_REQUEST["saction"]))
    return "";

switch ($_REQUEST["saction"])
{

    case ACTION_SERVICE_GETCURRTIME:
        print phpaga_getCurrentDateTimeFormatted();
        break;

    case ACTION_SERVICE_PAYTERM:
        if (isset($_REQUEST["id"]) && is_numeric($_REQUEST["id"]))
            print phpaga_companies_getdefaultpayterm($_REQUEST["id"]);
        else
            print "";
        break;

    case ACTION_SERVICE_MEMBERPARM:

        $peInfo = array();
        $pe_hourlyrate = "";
        $jcat_id = "";

        if (isset($_REQUEST["id"]) && is_numeric($_REQUEST["id"]))
        {
            $peInfo = phpaga_persons_getInfo($_REQUEST["id"]);

            if (!PhPagaError::isError($peInfo))
            {
                if (isset($peInfo["jcat_id"]))
                    $jcat_id = $peInfo["jcat_id"];

                if (isset($peInfo["pe_hourlyrate"]))
                    $pe_hourlyrate = $peInfo["pe_hourlyrate"];
            }
        }

        print sprintf("%s||%s",
                      $jcat_id,
                      $pe_hourlyrate);

        break;

    case ACTION_SERVICE_OPDETAILS:


        $html = "";

        if (isset($_REQUEST["id"]) && is_numeric($_REQUEST["id"]))
        {
            $opInfo = array();
            $prjInfo = array();

            $opInfo = phpaga_operations_getInfo($_REQUEST["id"]);

            if (!PhPagaError::isError($opInfo)) {

                $prjInfo = phpaga_projects_getInfo($opInfo["prj_id"]);
                if (!PhPagaError::isError($prjInfo) && count($prjInfo)) {

                    $tpl = new psmarty;
                    $tpl->assign("prjInfo", $prjInfo);
                    $tpl->assign("opInfo", $opInfo);
                    $tpl->assign("isdiv", true);
                    $html = $tpl->fetch("view_operation.tpl.html");
                }
            }
        }

        print $html;
        break;

    case ACTION_SERVICE_GETADDTASK:

        $values = "";
        $err = false;
        $errtxt = null;
        $oid = null;
        $otxt = null;
        $ismember = false;
        $can_manage = false;
        $prjInfo = array();
        $select_user = array();

        if (isset($_REQUEST["id"]) && is_numeric($_REQUEST["id"])) {

            $prj_id = $_REQUEST["id"];

            $ismember = phpaga_project_is_member($prj_id, $_SESSION["auth_user"]["pe_id"]);
            $can_manage = phpaga_project_canmanage($prj_id);

            /* user can add tasks if she is a project member, if she has the right
             * to manage this project */

            if (!$ismember && !$can_manage) {
                $err = true;
                $errtxt = _("You cannot file tasks for this project because you are not a member or manager.");
            } else {

                $prjInfo = phpaga_projects_getInfo($prj_id);

                if (!PhPagaError::isError($prjInfo) && count($prjInfo)) {

                    $tags = "<prjid>".$prj_id."</prjid>\n<prjtitle>".$prjInfo["prj_title"]."</prjtitle>\n";

                    $select_opcat = phpaga_operations_getCategoryList();
                    phpaga_arrayAddOption($select_opcat, PHPAGA_OPTION_SELECT);

                    foreach ($select_opcat as $oid => $otxt)
                        $tags .= sprintf("<opcat id=\"%s\">%s</opcat>\n", $oid, phpaga_sanitize_htmlout($otxt));

                    /* Only the project owner and overall project managers can set an operation's user */

                    if (!$can_manage) {

                        $peInfo = phpaga_persons_getInfo($_SESSION["auth_user"]["pe_id"]);

                        $select_user[$peInfo["pe_id"]] = sprintf("%s (%s)",
                                                                 $peInfo["pe_person"],
                                                                 $_SESSION["auth_user"]["usr_login"]);

                    } else {

                        $userInfo["prj_id"] = $prj_id;
                        $users = phpaga_user_search($userInfo);

                        foreach ($users as $u)
                            $select_user[$u["pe_id"]] = $u["pe_name"]." (".$u["usr_login"].")";
                    }

                    foreach ($select_user as $oid => $otxt)
                        $tags .= sprintf("<user id=\"%s\">%s</user>\n", $oid, phpaga_sanitize_htmlout($otxt));

                    $tpl = new psmarty;
                    $tpl->assign("status", 0);
                    $tpl->assign("tags", $tags);
                    $values = $tpl->fetch("xmlresponseframe.tpl.xml");

                } else {
                    $err = true;
                    $errtxt = $prjInfo->getMessage();
                }
            }

        } else {
            $err = true;
            $errtxt = _("Invalid project");
        }

        if ($err) {
            $tpl = new psmarty;
            $tpl->assign("status", 20);

            if (strlen($errtxt))
                $tpl->assign("message", $errtxt);

            $tpl->assign("tags", "");
            $values = $tpl->fetch("xmlresponseframe.tpl.xml");
        }

        header("Content-type: text/xml");
        print $values;
        break;


    case ACTION_SERVICE_ADDTASK:

        $op_id = null;
        $err = false;
        $errtxt = null;
        $ismember = false;
        $can_manage = false;
        $values = null;
        $opInfo = array();

        if (isset($_REQUEST["prj_id"]) && is_numeric($_REQUEST["prj_id"]))
        {
            $prj_id = $_REQUEST["prj_id"];
            $opInfo["prj_id"] = $prj_id;

            $ismember = phpaga_project_is_member($prj_id, $_SESSION["auth_user"]["pe_id"]);
            $can_manage = phpaga_project_canmanage($prj_id);

            if (!$ismember && !$can_manage) {
                $err = true;
                $errtxt = _("You cannot file tasks for this project because you are not a member or manager.");
            } else {

                /* only the project owner and overall project managers
                 * can set an operation's user */

                if (!$can_manage)
                    $opInfo["pe_id"] = $_SESSION["auth_user"]["pe_id"];
                else
                    $opInfo["pe_id"] = $_REQUEST["pe_id"];

                if (isset($_REQUEST["op_billabletype"]) && ($_REQUEST["op_billabletype"] == 0)) {
                    $opInfo["op_billabletype"] = 0;
                    $opInfo["billable_checked"] = true;
                } else {
                    $opInfo["op_billabletype"] = 10;
                    $opInfo["billable_checked"] = false;
                }

                $opInfo["opcat_id"] = $_POST["opcat_id"];
                $opInfo["op_desc"] = $_POST["op_desc"];
                $opInfo["op_duration"] = $_POST["op_duration"];

                /* if the duration is numeric, convert it from fractional hours into hours:minutes */

                if (is_numeric($opInfo["op_duration"]))
                {
                    // Under 24 - assume the duration was given in hours
                    if ($opInfo["op_duration"] < 24)
                        $opInfo["op_duration"] = (int)$opInfo["op_duration"].':'.sprintf('%02d', 60 * ($opInfo["op_duration"] - (int)$opInfo["op_duration"]));
                    // More than 60 minutes, different calculation
                    elseif ($opInfo["op_duration"] >= 60)
                        $opInfo["op_duration"] = (int)($opInfo["op_duration"] / 60).':'.sprintf('%02d', $opInfo["op_duration"] % 60);
                    // duration given in minutes
                    else
                        $opInfo["op_duration"] = '0:'.(int)$opInfo["op_duration"];
                }

                /* if there is a valid start date and time then convert it to a timestamp */

                $opInfo["op_startdate"]  = $_POST["op_startdate"];
                $opInfo["op_starthours"] = $_POST["op_starthours"];

                $start_tmp = "";

                if ($opInfo["op_startdate"] != "") {

                    $start_tmp = $opInfo["op_startdate"];

                    if ($opInfo["op_starthours"] != "")
                        $start_tmp .= " ".$opInfo["op_starthours"];

                    $opInfo["op_timestamp_start"] = strtotime($start_tmp);
                } else
                    $opInfo["op_timestamp_start"] = "";

                /* if there is a valid end date and time then convert it to a timestamp */

                $opInfo["op_enddate"]  = $_POST["op_enddate"];
                $opInfo["op_endhours"] = $_POST["op_endhours"];

                $end_tmp = "";

                if ($opInfo["op_enddate"] != "") {

                    $end_tmp = $opInfo["op_enddate"];

                    if ($opInfo["op_endhours"] != "")
                        $end_tmp .= " ".$opInfo["op_endhours"];

                    $opInfo["op_timestamp_end"] = strtotime($end_tmp);
                } else
                    $opInfo["op_timestamp_end"] = "";

                /* check if operation data is valid and add the operation */

                $result = phpaga_operations_validdata($opInfo);

                if (PhPagaError::isError($result)) {
                    $err = true;
                    $errtxt = $result->getMessage();
                } else {
                    $op_id = phpaga_operations_add($opInfo);

                    if (PhPagaError::isError($op_id)) {
                        $err = true;
                        $errtxt = $op_id->getMessage();
                    } else {

                        $duration = phpaga_projects_getDuration($prj_id);
                        $opInfo = phpaga_operations_getInfo($op_id);

                        if (PhPagaError::isError($opInfo)) {
                            $err = true;
                            $errtxt = $opInfo->getMessage();
                        } else {

                            $taskdate = strftime(PHPAGA_DATEFORMAT_SHORT, $opInfo["op_timestamp_start"]);

                            if (strlen($opInfo['prj_title']) > PHPAGA_SHOWPRJTITLELENGHT)
                                $prj_title = phpaga_substr($opInfo['prj_title'], 0, PHPAGA_SHOWPRJTITLELENGHT).'...';
                            else
                                $prj_title = $opInfo['prj_title'];

                            if (strlen($opInfo['op_desc']) > PHPAGA_SHOWOPDESCLENGHT)
                                $op_desc = phpaga_substr($opInfo['op_desc'], 0, PHPAGA_SHOWOPDESCLENGHT).'...';
                            else
                                $op_desc = $opInfo['op_desc'];

                            $deltxt = phpaga_jsmessage_sanitizestr(sprintf("%s\n%s: %s\n%s: %s",
                                                                           $taskdate,
                                                                           _("Project"),
                                                                           $opInfo['prj_title'],
                                                                           _("Task"),
                                                                           $opInfo['op_desc']));

                            $tpl = new psmarty;
                            $tpl->assign("status", 0);
                            $tpl->assign("tags",
                                         sprintf("<prjid>%s</prjid>\n".
                                                 "<prjduration>%s</prjduration>\n".
                                                 "<prjtitle>%s</prjtitle>\n".
                                                 "<opcat>%s</opcat>\n".
                                                 "<opid>%s</opid>".
                                                 "<opdesc>%s</opdesc>".
                                                 "<opstart>%s</opstart>\n".
                                                 "<opduration>%s</opduration>\n".
                                                 "<deltxt>%s</deltxt>",
                                                 $prj_id,
                                                 $duration,
                                                 phpaga_jsmessage_sanitizestr($prj_title),
                                                 phpaga_jsmessage_sanitizestr($opInfo["opcat_title"]),
                                                 $op_id,
                                                 phpaga_jsmessage_sanitizestr($op_desc),
                                                 phpaga_jsmessage_sanitizestr($taskdate),
                                                 phpaga_jsmessage_sanitizestr($opInfo["op_duration"]),
                                                 $deltxt
                                             ));
                            $values = $tpl->fetch("xmlresponseframe.tpl.xml");
                        }
                    }
                }
            }
        }

        if ($err) {
            $tpl = new psmarty;
            $tpl->assign("status", 20);

            if (strlen($errtxt))
                $tpl->assign("message", $errtxt);

            $tpl->assign("tags", "");
            $values = $tpl->fetch("xmlresponseframe.tpl.xml");
        }

        header("Content-type: text/xml");
        print $values;

        break;


    case ACTION_SERVICE_MATDETAILS:

        $html = "";

        if (isset($_REQUEST["id"]) && is_numeric($_REQUEST["id"]))
        {
            $matInfo = array();
            $prjInfo = array();

            $matInfo = phpaga_materials_getInfo($_REQUEST["id"]);
            if (!PhPagaError::isError($matInfo))
            {
                $prjInfo = phpaga_projects_getInfo($matInfo["prj_id"]);
                if (!PhPagaError::isError($prjInfo) && count($prjInfo)) {

                    $tpl = new psmarty;
                    $tpl->assign("prjinfo", $prjInfo);
                    $tpl->assign("matinfo", $matInfo);
                    $html = $tpl->fetch("material.tpl.html");
                }
            }
        }

        print $html;
        break;


    case ACTION_SERVICE_PRODINFO:

        $h_status = null;
        $values = "";
        $err = false;

        if (isset($_REQUEST["prod_code"]) && strlen($_REQUEST["prod_code"]))
        {
            $prodInfo = array();

            $prodInfo = phpaga_products_getInfo($_REQUEST["prod_code"], true);

            if (!PhPagaError::isError($prodInfo)) {

                if (count($prodInfo)) {
                    $h_status = 0;
                    $tags = "<prodname>".$prodInfo["prod_name"]."</prodname>\n".
                        "<prodprice>".$prodInfo["prod_price"]."</prodprice>\n".
                        "<prodid>".$prodInfo["prod_id"]."</prodid>\n";
                } else {
                    $h_status = 30;
                    $tags = null;
                }

                $tpl = new psmarty;
                $tpl->assign("status", $h_status);
                $tpl->assign("tags", $tags);
                $values = $tpl->fetch("xmlresponseframe.tpl.xml");
            }
            else
                $err = true;
        }
        else
            $err = true;

        if ($err) {
            $tpl = new psmarty;
            $tpl->assign("status", 20);
            $tpl->assign("message", $prodInfo->getMessage());
            $tpl->assign("tags", "");
            $values = $tpl->fetch("xmlresponseframe.tpl.xml");
        }

        header("Content-type: text/xml");
        print $values;

        break;


    case ACTION_SERVICE_GETEMPLOYEES:

        $ret = '';
        $err = false;

        $persons = array();
        $persons_count = 0;
        $tags = null;

        if (isset($_REQUEST["id"]) && strlen($_REQUEST["id"])) {

            $persons = phpaga_persons_list($persons_count, null, $_REQUEST["id"]);

            if (!PhPagaError::isError($persons)) {

                $tags = "<person><id>-1</id><name>-</name></person>\n";

                foreach ($persons as $p)
                    $tags .= sprintf("<person><id>%s</id><name>%s</name></person>\n", (int)$p["pe_id"], $p["pe_person"]);

                $tpl = new psmarty;
                $tpl->assign("status", 0);
                $tpl->assign("tags", $tags);
                $ret = $tpl->fetch("xmlresponseframe.tpl.xml");

            } else
                $err = true;

        } else
            $err = true;

        if ($err) {
            $tpl = new psmarty;
            $tpl->assign("status", 20);
            $tpl->assign("tags", "");
            $ret = $tpl->fetch("xmlresponseframe.tpl.xml");
        }

        header("Content-type: text/xml");
        print $ret;

        break;


    default:
        print "";
        break;
}

?>