カレンダー制作 vol.7

【授業内容】
カレンダー制作
★index.php

<?php
define('WEB_ROOT_DIR' , realpath(dirname('__FILE__').'/..'));

//controllerを呼び出す。
require_once(WEB_ROOT_DIR.'/calendar/lib/controller.php');

$controller = new Controller();
$controller->dispatch();
?>

★controller.php

<?php

class Controller
{
    public $module;
    public $action;

    public function __construct() {
        $this->module = isset($_GET["module"]) ? $_GET["module"] : "main";
        $this->action = isset($_GET["action"]) ? $_GET["action"] : "calendar";
    }

    public function dispatch() {
        $act_file_name = sprintf(WEB_ROOT_DIR.'/calendar/%s/actions/%s.php'
                                              ,$this->module, $this->action);
        $view_file_name = sprintf(WEB_ROOT_DIR.'/calendar/%s/view/%s.php'
                                              ,$this->module, $this->action);

        if(file_exists($act_file_name) !== true) {

        } else {

            require_once($act_file_name);
            $action = new $this->action();
            $action->execute();
            $action->render($view_file_name);
        }
    }
}
?>

★【Model】calendar.php

<?php
class calendar
{
    //メンバ変数設定
    public  $calendar_dates = array(
                                    'blanktop' => array(),
                                    'dates' => array(),
                                    'blankbottom' => array()
                                    );

    public $calendar_contents = array();
    public $select_years = array();
    public $select_months = array();
    public $year;
    public $month;
    public $module;
    public $action;

    //newしたと同時に以下の処理をする
    public function __construct() {
        $this->module = isset($_GET["module"]) ? $_GET["module"] : "main";
        $this->action = isset($_GET["action"]) ? $_GET["action"] : "calendar";
        $this->year = isset($_GET["year"]) ? $_GET["year"] : date("Y");
        $this->month = isset($_GET["month"]) ? $_GET["month"] : date("m");
    }
    
    //メインロジック開始
    public function execute() {
        //カレンダー表示
        //「show Calendar」ボタンが押されたら、
        if (isset($_GET["submit"])) {

            //月の始めまで、余白を★にする($calendar_datesに格納1)
            $w_top = date('w',mktime(0, 0, 0, $this->month, 1, $this->year));
            for($i = 0 ; $i < $w_top; $i++){
                $this->calendar_dates['blanktop'][] = "";
            }

            //月ごとの日にちを取ってくる($calendar_datesに格納2)
            for($day = 1; checkdate($this->month, $day, $this->year); $day++) {
                $this->calendar_dates['dates'] []= sprintf('%02d',$day);
                $lastday = $day;
            }
            
            //月の終わりまで、余白を★にする。($calendar_datesに格納3)
            $w_end = date('w', mktime(0, 0, 0, $this->month, $lastday, $this->year));
            for($i = 0; $i < 6-$w_end; $i++) {
                $this->calendar_dates['blankbottom'][] = "";
            }

            //月初めの★をHTMLタグに入れる($calendar_contentsに格納1)
            $blank_key = 0;

            foreach  ($this->calendar_dates['blanktop'] as $key => $star) {
                $this->calendar_contents[] =  "<td class='calendar-blank' align='center'>
                                               $star</td>";
                $blank_key = $key + 1;
            }

            //日付をHTMLタグに入れる($calendar_contentsに格納2)
            foreach ($this->calendar_dates["dates"] as $key => $date) {
                if (($blank_key + $key) % 7 == 0) {
                    $this->calendar_contents[] = "</tr><tr>";
                    $this->calendar_contents[] = "<td class='calendar-sunday'>
                                                 <a href='calendar_index.php?module=schedule&action=schedule&year=$this->year&month=$this->month&day=$date'>
                                                  $date</td>";
                } elseif (($blank_key + $key) % 7 == 6) {
                    $this->calendar_contents[] = "<td class='calendar-saturday'>
                                                  <a href='calendar_index.php?module=schedule&action=schedule&year=$this->year&month=$this->month&day=$date'>
                                                  $date</td>";
                } else {
                    $this->calendar_contents[] = "<td class='calendar-weekday'>
                                                  <a href='calendar_index.php?module=schedule&action=schedule&year=$this->year&month=$this->month&day=$date'>
                                                  $date</td>";
                }
            }
            //月終わりの★をHTMLタグに格納($calendar_contentsに格納3)
            foreach  ($this->calendar_dates["blankbottom"] as $star) {
                $this->calendar_contents[] = "<td class='calendar-blank' align='center'>
                                              $star</td>";
            }
        }

        //select(年)の値を作る
        $year = 1986;
        while ($year <= 2030) {
            if ($year == $this->year) {
                $this->select_years[] = "<option value='$year' selected>$year</option>";
            } else {
                $this->select_years[] = "<option value='$year'>$year</option>";
            }
            $year++;
        }

        //select(月)の値を作る
        $month = 1;
        while ($month <= 12) {
            if ($month == $this->month) {
                $months_default = "<option value='%02d' selected>%02d</option>";
                $this->select_months[] = sprintf($months_default, $month,$month);
            } else {
                $months_default = "<option value='%02d'>%02d</option>";
                $this->select_months[] = sprintf($months_default, $month, $month);
            }
            $month++;
        }
    }

    //HTMLファイルの呼び出し
    public function render($path) {
        require_once($path);
    }

        
}
?>

★【View】calendar.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>かれんだー</title>
    <link href="./calendar.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <h1>CALENDAR</h1>
      <p id="comp_msg">
       <span>Please Choose the Year & Month You Wanna See ! </span>
      </p>

      <form action="calendar_index.php?module=main&action=calendar" method="GET">
        <select name="year">
<?php
     foreach ($this->select_years as $select_year) {
          echo $select_year;
      }
?>
        </select><select name="month">
<?php
     foreach ($this->select_months as $select_month) {
         echo $select_month;
     }
?>
        </select>

        <input type="hidden" name="module" value="main">
        <input type="hidden" name="action" value="calendar">
        <input type="submit" name="submit" value="Show Calendar!">
      </form>

<br />
  <div class="calendar">
    <table class="calendar" border="4">
      <caption>
       <?php echo isset($_GET["year"]) ? $_GET["year"] : "★☆★";?><?php echo isset($_GET["month"]) ? $_GET["month"] : "★☆★";?>
      </caption>
            <tr>
              <th class="calendar-sunday"></td>
              <th class="calendar-weekday"></td>
              <th class="calendar-weekday"></td>
              <th class="calendar-weekday"></td>
              <th class="calendar-weekday"></td>
              <th class="calendar-weekday"></td>
              <th class="calendar-saturday"></td>
           </tr>
           <tr>
<?php
  foreach ($this->calendar_contents as $calendar_content) {
    echo $calendar_content;
  }

?>
	      </tr>
    </table>
  </body>
</html>

★【Model】schedule.php

<?php
class Schedule {

    //メンバ変数設定
    public $err_data = array(
                          'is_error' => false,
                          'err_msgs' => array()
                          );
    public $schedules = array();
    public $none_schedule_msg;
    public $select_hours = array();
    public $select_minutes = array();
    public $title;
    public $content;
    public $day;
    public $month;
    public $year;

    //new下と同時に以下の処理をする
    public function __construct() {
        $this->day = $_GET["day"];
        $this->month = $_GET["month"];
        $this->year = $_GET["year"];
    }

    //メインロジック開始
    public function execute() {
        //初期値を設定
        define('ERR_MSG_NO_TITLE' , 'タイトルが未入力です。');
        define('ERR_MSG_NO_CONTENT' , '内容が未入力です。');
        //DB接続用
        $link = mysql_connect('localhost' , 'root');
        //libraryを開く
        require_once(WEB_ROOT_DIR.'/calendar/lib/library.php');

        
        //スケジュール削除
        //「Delete」ボタンが押されたら、
        if (isset($_POST["del"])) {
            
            //DBに接続
            if (is_connect($link)) {
                //エラーがなかったら、トランザクション開始
                $this->err_data = is_tran_begin($link, $this->err_data);
                if ($this->err_data["is_error"]) {
                    
                } else {
                    //エラーがなかったら、DELETE文を走らせる
                    $this->err_data = del_schedule($link, $this->err_data);
                    //エラーがあったら、ROLLBACKする
                    if ($this->err_data["is_error"]) {
                        $this->err_data = rollback_tran($link, $this->err_data);
                        
                    } else {
                        //エラーがなかったら、COMMITする
                        $this->err_data = commit_tran($link, $this->err_data);
                    }
                }
            } else {
                mysql_close($link);
            }
        }


        //スケジュール一覧表示
        //DBに接続する
        if (is_connect($link)) {
            //DBにある値を拾って、配列に格納
            $this->schedules = get_schedules($this->schedules);
        }
       
                    
        //スケジュール登録
        //「Entry」ボタンが押されたら
        if (isset($_POST["entry"])) {
            //バリデータにかける
            $this->err_data = set_valid_result($this->err_data);
            
            if ($this->err_data['is_error']) {

            } else {
                //エラーがなかったらDBに接続、トランザクション開始
                if (is_connect($link)) {
                    $this->err_data = is_tran_begin($link,$this->err_data);
                    if ($this->err_data["is_error"]) {

                    } else {
                        //エラーがなかったら、有害な文字列を書き換え
                        $this->title = replace_sp_chara($_POST["title"]);
                        $this->content = replace_sp_chara($_POST["content"]);
                        $this->date = replace_sp_chara($_GET["year"]."-".$_GET["month"]."-".$_GET["day"]);

                        //DBに書き込む
                        $this->err_data = set_schedule($link, $this->err_data, $this->title, $this->content, $this->date);
                        //エラーがあったらROLLBACK
                        if ($this->err_data["is_error"]) {
                            $this->err_data = rollback_tran($link, $this->err_data);
                            
                        } else {
                            //なかったらCOMMIT
                            $this->err_data = commit_tran($link, $this->err_data);
                            //エラーがなかったら、登録完了画面に飛ばす。
                            if (!$this->err_data["is_error"]) {
                                header("Location: calendar_index.php?module=schedule&action=complete_entry&year=$this->year&month=$this->month&day=$this->day");
                                exit();
                            } else {

                            }
                        }
                    }
                    mysql_close($link);
                }
            }
            
        }




        //select(時)の値を作る
          $hour = 1;
        while ($hour <= 24) {
            if ($hour == 8) {
                $hours_default = "<option value='%02d' selected>%02d</option>";
                $this->select_hours[] = sprintf($hours_default, $hour, $hour);
            } else {
                $hours_default = "<option value='%02d'>%02d</option>";
                $this->select_hours[] = sprintf($hours_default, $hour, $hour);
            }
                $hour++;
        }

        //select(分)の値を作る
        $minute = 0;
        while ($minute <= 55) {
            $minutes_default = "<option value='%02d'>%02d</option>";
            $this->select_minutes[] = sprintf($minutes_default, $minute, $minute);
            $minute = $minute + 5;
        }
    }
     //HTMLファイルの呼び出し
    public function render($path) {
        require_once($path);
    }
}

?>

★【View】schedule.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>すけじゅーる</title>
    <link href="./calendar.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <h1 class="index">SCHEDULE</h1>

    <h2 class="index">
      <span>
        <?php echo $this->year ?><?php echo $this->month ?><?php echo $this->day ?>
      </span>
    </h2>
    <h3 class="index"><span>schedule are . . .</span></h3>

    <table class="schedule" border="2" >
      <thead>
        <tr>
          <th class="schedule-th">Time</th>
          <th class="schedule-th">Title</th>
          <th class="schedule-th">Content</th>
          <th class="schedule-th">Delete</th>
        </tr>
      </thead>
      <tbody>
       <?php
         if (count($this->schedules) != 0) {
             foreach ($this->schedules as $schedule) {
       ?>
        <tr>
          <td class="time" align='center'><?php echo isset($schedule["time"]) ? $schedule["time"] : ""; ?></td>
          <td class="title" align='center'><?php echo isset($schedule["title"]) ? $schedule["title"] : ""; ?></td>
       <td class="content" align='center'><?php echo isset($schedule["body"]) ? nl2br($schedule["body"]) : ""; ?></td>
          <td class="del" align='center'>
            <form action="" method="POST">
              <input type="hidden" name="id" value="<?php echo $schedule["id"] ?>">
              <input type="submit" name="del" value="Delete">
            </form>
          </td>
        </tr>
<?php
             }
         } else {
             $this->none_schedule_msg = "No Schedules in this day.";
         }
?>
      </tbody>
    </table>

  <p id="no_schedule">
<?php
     if (strlen($this->none_schedule_msg) != 0) {
?>
    <MARQUEE align="top" width="350" height="30" loop="INFINITE" scrollamount="5" scrolldelay="90"><?php echo $this->none_schedule_msg; ?></MARQUEE>
<?php
     } else {
     }
?>
  </p>
<br />
<hr />
  <p id="error">
<?php
        if ($this->err_data['is_error']) {
             foreach ($this->err_data['err_msgs'] as $err_msg) {
                 echo $err_msg;
             }
         }
?>
  </p>

<hr />

  <form action="" method="POST">
    <p><em>Appointment time. . .</em></p>

    <select name="hour">
<?php
     foreach ($this->select_hours as $select_hour) {
         echo $select_hour;
     }
?>
    </select><select name="minute">
<?php
     foreach ($this->select_minutes as $select_minute) {
         echo $select_minute;
     }
?>
    </select>

  <p><em>Title. . .</em></p>
    <input type="text" name="title" size="25" value="<?php echo isset($_POST["title"]) ? $_POST["title"] : "" ?>"></p>
  <p><em>Content. . .</em></p>
    <textarea name="content" rows="8" cols="50"><?php echo isset($_POST["content"]) ? $_POST["content"] : "" ?></textarea></p>

<br />
<br />
    <input type="submit" name="entry" value="entry!">
  </form>

<br />

    <form action="calendar_index.php?" method="GET">
      <input type="hidden" name="module" value="main">
      <input type="hidden" name="action" value="calendar">
      <input type="hidden" name="year" value="<?php echo $_GET["year"]; ?>">
      <input type="hidden" name="month" value="<?php echo $_GET["month"]; ?>">
      <input type="submit" name="submit" value="Back to Calendar!">
    </form>
  </head>
</html>

★【Model】complete_entry.php

<?php

class Complete_entry
{
    //メンバ変数設定
    public $day;
    public $month;
    public $year;
    public $schedule_date;

    //newしたと同時に以下の処理をする
    public function __construct() {
        $this->day = $_GET["day"];
        $this->month = $_GET["month"];
        $this->year = $_GET["year"];
    }

    //メインロジック開始
    public function execute() {
        $this->schedule_date = $this->year."/".$this->month."/".$this->day;
    }

    //HTMLファイルの呼び出し
    public function render($path) {
        require_once($path);
    }

}
?>

★【View】complete_entry.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>とうろくかんりょう</title>
    <link href="./calendar.css" rel="stylesheet" type="text/css" />
  </head>

  <body>
    <h1>The Entry was done ! !</h1>

    <h2><span>Your schedule had been written.</span></h2>
    <p id="comp_msg">
      <span>New schedule was added on <?php echo $this->schedule_date; ?>('◇'*)</span>
    </p>
    <a href="calendar_index.php?module=schedule&action=schedule&year=<?php echo $this->year ?>&month=<?php echo $this->month ?>&day=<?php echo $this->day ?>">
Back to Past page
    </a>
  </body>
</html>


★今回の反省点。
calendar.phpにおいて、HTML上のPHPを極限までなくしたくて、Modelで全部配列にHTMLタグごと突っ込んでしまったけど、これは間違った書き方。PHPの中にHTMLタグを書かない方がよし。


★今回のお初にお目にかかります。
 ○$_REQUEST
$_GET、 $_POST そして $_COOKIE の内容をまとめた連想配列
=>要は$_GETの値も$_POSTの値も拾ってくれるマルチな子。
  
 ○PEAR
PHP Extension and Application Repository の略。
  PHP4からついてくるようになった、クラスライブラリ(よく使う機能を「クラス」としてまとめたもの)週のこと。
  つまりおまけでついてくるようになった便利ツールさん。