<?php
/*
 * Copyright (c)  2006-2008 Maskat Project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* 内部エンコーディングを UTF-8 に設定 */
setlocale(LC_ALL, "ja_JP.UTF-8");
mb_language("ja");
mb_internal_encoding("UTF-8");

/* PHP5 以降の場合に PHP4 互換の DOM API をロードする */
if (version_compare(PHP_VERSION, "5", ">=")) {
  require_once("domxml-php4-to-php5.php");
}

function parse_request_xml() {
  if ($_SERVER["REQUEST_METHOD"] != "POST") {
    return null;
  }

  /* POST された XML 文字列データを読み込む */
  $fd = fopen("php://input", "r") or die("can't open post stream");
  $xml = fread($fd, 4096);
  if (!feof($fd)) {
    die("too much post data size.");
  }
  fclose($fd);

  /* XML DOM オブジェクトを連想配列に変換する */
  $dom = domxml_open_mem($xml);
  return parse_xml_element($dom->document_element());
}

function parse_xml_element($element) {
  $children = $element->child_nodes();
  $result = array();
  
  foreach ($children as $child) {
    $grand_children = $child->child_nodes(); 
    if (count($grand_children) == 1 and $grand_children[0]->tagname == "#text") {
      /* 子要素が単一のテキスト要素のみの場合、テキスト要素を返却する */
      $result[$child->tagname] = $child->get_content();
    } else {
      /* 子要素が複数存在する場合、タグ名ごとの連想配列に格納する */
      $list = array();
      foreach ($grand_children as $grand_child) {
        array_push($list, parse_xml_element($grand_child));
      }
      $result[$child->tagname] = $list;
    }
  }
  return $result;
}

function read_csv_file($filename, $id = null) {
  /* CSV ファイルをオープン */
  $fd = fopen($filename, "r") or die("can't open file: $filename");

  /* CSV の最初の行からヘッダ情報を取得する */
  $headers = fgetcsv($fd);
  
  /* 残りの行を連想配列に変換して格納する */
  $store = array();
  while ($line = fgetcsv($fd)) {
    $item = array();
    for ($i = 0; $i < count($line); $i++) {
      $item[$headers[$i]] = $line[$i];
    }
    if ($id != null) {
      $store[$item[$id]] = $item;
    } else {
      array_push($store, $item);
    }
  }
  fclose($fd);
  
  return $store;
}

function utf8_urldecode($str) {
  $str = preg_replace("/%u([0-9a-f]{3,4})/i","&#x\\1;", urldecode($str));
  return html_entity_decode($str, null, 'UTF-8');
}
?>