<?php
//vim: ts=2 sw=2

include_once "db.php";
include_once "base_controller.php";

class GrdataController extends BaseController {
  protected function signinRequired() {
    return true;
  }

  protected function doAjaxGet() {
    $response = array();
    $_SESSION['curGrPath'] = $_GET['grName'];
    if (!$this->isReadable()) {
      $this->renderAjaxError($response, L("permission denied"));
    }

    // the grName may contains '&' and space characters, urldecode will handle it
    $grName = urldecode($_GET['grName']);

    if (!(endsWith($grName, '.gr') || endsWith($grName, '.xml')))
      $this->renderAjaxError($response, L('invalid gr data type'));

    $isNavFile = $grName == "grNav.xml";
    $grPath = './grdata/' . $grName;
    $realGrPath = realpath($grPath);
    if (startsWith($realGrPath, realpath('.')) && file_exists($grPath)) {
        // for grNav.xml file or docInfo request, return some info data
        if ($isNavFile || isset($_GET['infoOnly'])) {
          $u = $this->curUser();
          $response['actionPermitted'] = $u->can('write', $grName) ? 'true' : 'false';
          if (!$u->isAdmin())
              $response['grBlackList'] = implode(",", $u->grBlackList());
          $response['home_page'] = $u->attr('home_page');

          //since grNav.xml file is small, just load it all into memory 
          if ($isNavFile)
              $response['data'] = file_get_contents($grPath)
          $this->renderAjaxSuccess($response);
        } else {
            //for other gr file, transfer chunk by chunk
            header("Content-Type: application/xml");
            readfile_chunked($grPath);
        }
    } else {
      $this->renderAjaxError($response, sprintf(L("failed to read data file: %s"), $grName));
    }
  }
}

$controller = new GrdataController();
$controller->run();

?>