<?php
/* SVN FILE: $Id: HTML.php 455 2008-05-22 09:24:36Z bb_yujiro $ */
/**
 * HTML出力
 *
 * PHP versions 5
 *
 *      hitSuji : Social Network Service <http://rakuto.net/rktSNS/>
 *      Copyright (c) 2007 Yujiro Takahashi
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @package         hitSuji
 * @copyright       Copyright (c) 2007 Yujiro Takahashi
 * @link            http://rakuto.net/
 * @author          Yujiro Takahashi <yujiro@rakuto.net>
 * @version         $Revision: 455 $
 * @modifiedby      $LastChangedBy: bb_yujiro $
 * @lastmodified    $Date: 2008-05-22 18:24:36 +0900 (木, 22 5 2008) $
 * @license         http://opensource.org/licenses/mit-license.php The MIT License
 */

/**
 * HTML出力クラス
 *
 * @category        View
 * @package         hitSuji
 * @copyright       Copyright (c) 2007 Yujiro Takahashi
 * @link            http://rakuto.net/
 * @author          Yujiro Takahashi <yujiro@rakuto.net>
 * @version         $Revision: 455 $
 * @modifiedby      $LastChangedBy: bb_yujiro $
 * @lastmodified    $Date: 2008-05-22 18:24:36 +0900 (木, 22 5 2008) $
 * @license         http://opensource.org/licenses/mit-license.php The MIT License
 */
class HTML
{
    /**
     * Pager移動可能ページの表示限度
     * @const integer
     */
    const PAGER_WIDTH = 5;

    /**
     * チェックボックスの出力
     *
     * @access public
     * @param string $name
     * @param array $options
     * @param mixed $checked
     * @param integer $column_number
     * @return void
     */
    public static function checkbox($name, $options, $checked=array(), $column_number=3)
    {
        if (!is_array($checked)){
            $checked = explode(',', $checked);
        }
        $width = array(
            '1'=> '382',
            '2'=> '186',
            '3'=> '122',
        );

        $break = 0;
        print ('<ul class="horizontal">');
        foreach ($options as $id=>$label){
            print ('<li style="width:'.$width[$column_number].'px;"><label>');
            print ('<input class="check" type="checkbox" name="'.$name.'[]" value="'.$id.'"');
            if (in_array($id, $checked)){
                print (' checked="checked"');
            }
            print (' />'.$label.'</label></li>');
            $break++;

            if ($break >= 3){
                $break = 0;
                print ('</ul><ul class="horizontal">');
            }
        }
        print ('</ul>');
    }

    /**
     * チェック済みの出力
     *
     * @access public
     * @param array $options
     * @param mixed $checked
     * @param integer $column_number
     * @return void
     */
    public static function checkedList($options, $checked=array(), $column_number=3)
    {
        if (!is_array($checked)){
            $checked = explode(',', $checked);
        }
        $width = array(
            '1'=> '382',
            '2'=> '186',
            '3'=> '122',
        );

        $break = 0;
        print ('<ul class="horizontal" style="width:388px;">');
        foreach ($options as $id=>$label){
            if (in_array($id, $checked)){
                print ('<li style="width:'.$width[$column_number].'px;">');
                print ($label);
                print ('</li>');

                $break++;
                if ($break >= 3){
                    $break = 0;
                    print ('</ul>');
                    print ('<ul class="horizontal">');
                }
            }
        } // foreach ($options as $id=>$label)
        print ('</ul>');
    }

    /**
     * 日付のセレクト出力
     *
     * @access public
     * @param string $name
     * @param string $checked
     * @param integer $start
     * @param integer $end
     * @return void
     */
    public static function dateSelect($name, $checked=null, $start=DATE_START_YEAR, $end=null)
    {
        $checked   = joinDate($checked);
        if (empty($checked)){
            $selected = array(
                'year'=>  null,
                'month'=> null,
                'day'=>   null,
            );
        } else {
            $timestamp = strtotime($checked);
            $selected = array(
                'year'=>  date('Y', $timestamp),
                'month'=> date('n', $timestamp),
                'day'=>   date('j', $timestamp),
            );
        }
        $end = empty($end)? date('Y'):$end;

        /* 年 */
        print ('<select name="'.$name.'[year]">');
        print ('<option label="" value="">'._('Year').'</option>');
        for ($year=$end; $year>=$start; $year--){
            print ('<option label="'.$year.'" value="'.$year.'"');
            if ($selected['year'] == $year){
                print (' selected="selected"');
            }
            print ('>'.$year.'</option>');
        }
        print ('</select>&nbsp;/&nbsp;');

        /* 月 */
        $months = array(
             1=>_('January'),   2=>_('February'), 3=>_('March'),  4=>_('April'),      5=>_('May'),
             6=>_('June'),      7=>_('July'),     8=>_('August'), 9=>_('September'), 10=>_('October'),
            11=>_('November'), 12=>_('December'),
        );
        print ('<select name="'.$name.'[month]">');
        print ('<option label="" value="">'._('Month').'</option>');
        foreach ($months as $id=>$label){
            print ('<option label="'.$label.'" value="'.$id.'"');
            if ($selected['month'] == $id){
                print (' selected="selected"');
            }
            print ('>'.$label.'</option>');
        }
        print ('</select>&nbsp;/&nbsp;');

        /* 日 */
        print ('<select name="'.$name.'[day]">');
        print ('<option label="" value="">'._('Day').'</option>');
        for ($day=1; $day<=31; $day++){
            print ('<option label="'.$day.'" value="'.$day.'"');
            if ($selected['day'] == $day){
                print (' selected="selected"');
            }
            print ('>'.$day.'</option>');
        }
        print ('</select>'."\r\n");
    }

    /**
     * リッチエディタ用出力
     *
     * @access public
     * @param string $str
     * @return void
     */
    public static function editorBody($str)
    {
        /* プラグインによる処理 */
        echo loadPlugin::exec()->outputEditorBody($str);
    }

    /**
     * hiddenタグの出力
     *
     * @access public
     * @param string $name
     * @param mixed $values
     * @return void
     */
    public static function hidden($name, $values)
    {
        if (!is_array($values)){
            print ('<input type="hidden" name="'.$name.'"');
            print (' value="'.$values.'" />'."\r\n");
            return ;
        }

        foreach ($values as $key=>$value){
            $key = $name.'['.$key.']';
            HTML::hidden($key, $value);
        }
    }

    /**
     * HTMLタグを有効にした出力
     *
     * @access public
     * @param string $str
     * @return void
     */
    public static function htmlBody($str)
    {
        /* プラグインによる処理 */
        echo loadPlugin::exec()->outputHtmlBody($str);
    }

    /**
     * チェック済みの出力
     *
     * @access public
     * @param array $options
     * @param mixed $checked
     * @return void
     */
    public static function mobileCheckedList($options, $checked=array())
    {
        if (!is_array($checked)){
            $checked = explode(',', $checked);
        }

        foreach ($options as $id=>$label){
            if (in_array($id, $checked)){
                print ($label.'<br>');
            }
        } // foreach ($options as $id=>$label)
    }
    /**
     * チェックボックスの出力
     *
     * @access public
     * @param string $name
     * @param array $options
     * @param mixed $checked
     * @return void
     */
    public static function mobileCheckbox($name, $options, $checked=array())
    {
        if (!is_array($checked)){
            $checked = explode(',', $checked);
        }

        foreach ($options as $id=>$label){
            print ('<label><input class="check" type="checkbox" name="'.$name.'[]" value="'.$id.'"');
            if (in_array($id, $checked)){
                print (' checked="checked"');
            }
            print (' />'.$label.'</label><br>');
        }
    }

    /**
     * ページャー
     *
     * @access public
     * @param array $pager
     * @param array $requests
     * @param string $separator
     * @return void
     */
    public static function mobilePager($pager, $requests=array(), $separator='&nbsp;')
    {
        $requests = array_merge($requests, $pager['param']);
        if (isSet($requests['page'])){
            unset($requests['page']);
        }

        $request  = http_build_query($requests);
        $self     = getUrlSelf();

        print ('<table  border="0" width="'.Theme::WIDTH.'">');
        print ('<tr>');

        /* << 前へ */
        print ('<td align="right"><font size="'.Theme::FONT_SIZE.'">');
        if ($pager['prev'] > 0){
            print ('<a href="'.$self.US.'page='.$pager['prev'].'&amp;'.$request.'">&lt;&lt;'. _('Prev') .'</a>');
        } else {
            print ('&nbsp;');
        }
        print ('</font></td>');

        /* ページリンク */
        print ('<td align="center"><font size="'.Theme::FONT_SIZE.'">');
        print ($separator);
        self::_setPager($pager, $request, $separator);
        print ('</font></td>');

        /* 次へ >> */
        print ('<td align="left"><font size="'.Theme::FONT_SIZE.'">');
        if ($pager['next'] <= $pager['max_page']){
            print ('<a href="'.$self.US.'page='.$pager['next'].'&amp;'.$request.'">'. _('Next') .'&gt;&gt;</a>');
        } else {
            print ('&nbsp;');
        }
        print ('</font></td>');

        print ('</tr></table>');
    }

    /**
     * リッチエディタ用出力
     *
     * @access public
     * @param string $name
     * @param string $value
     * @param string $title
     * @param string $size
     * @return void
     */
    public static function mobileRichEditor($name, $value, $title, $size='large')
    {
        /* プラグインによる処理 */
        $value = loadPlugin::exec()->outputEditorBody($value);
        
        $area   = 'rEditor';
        $width  = ($size == 'large')? '480':'380';
        $height = ($size == 'large')? '300':'200';
        
        $value = str_replace('<br></br>', "\r\n", $value);
        $value = str_replace('<br>', "\r\n", $value);
        
        print ('<textarea name="'.$name.'">');
        print (htmlspecialchars($value, ENT_QUOTES, 'UTF-8', false));
        print ('</textarea>');
    }

    /**
     * 改行を<br>に変換
     *
     * @access public
     * @param string $str
     * @return void
     */
    public static function nl2br($str)
    {
        print(nl2br($str));
    }

    /**
     * セレクトオプションの出力
     *
     * @access public
     * @param array $options
     * @param mixed $selected
     * @return void
     */
    public static function options($options, $selected=null)
    {
        if (!is_array($options)){
            return ;
        }
        foreach ($options as $id=>$label){
            print ('<option label="'.$label.'" value="'.$id.'"');
            if ($selected == $id){
                print (' selected="selected"');
            }
            print ('>'.$label.'</option>');
        }
    }

    /**
     * ページャー
     *
     * @access public
     * @param array $pager
     * @param array $requests
     * @param string $separator
     * @return void
     */
    public static function pager($pager, $requests=array(), $separator='&nbsp;')
    {
        $requests = array_merge($requests, $pager['param']);
        if (isSet($requests['page'])){
            unset($requests['page']);
        }

        $request = http_build_query($requests);
        $self    = getUrlSelf();

        print ('<ul class="horizontal" style="width:520px;">');

        /* << 前へ */
        print ('<li style="width:80px; text-align:right;">');
        if ($pager['prev'] > 0){
            print ('<a href="'.$self.US.'page='.$pager['prev'].'&amp;'.$request.'">');
            print ('<img src="'.BASE_URL.'resource/img/icons/resultset_previous.gif" width="16" height="16" align="absmiddle" alt="<<" />');
            print ('</a>');            
            print ('<a href="'.$self.US.'page='.$pager['prev'].'&amp;'.$request.'">'. _('Prev') .'</a>');
        } else {
            print ('&nbsp;');
        }
        print ('</li>');

        /* ページリンク */
        print ('<li style="width:350px; text-align:center;">');
        print ($separator);
        HTML::_setPager($pager, $request, $separator);
        print ('</li>');

        /* 次へ >> */
        print ('<li style="width:80px; text-align:left;">');
        if ($pager['next'] <= $pager['max_page']){
            print ('<a href="'.$self.US.'page='.$pager['next'].'&amp;'.$request.'">'. _('Next') .'</a>');
            print ('<a href="'.$self.US.'page='.$pager['next'].'&amp;'.$request.'">');
            print ('<img src="'.BASE_URL.'resource/img/icons/resultset_next.gif" width="16" height="16" align="absmiddle" alt=">>" />');
            print ('</a>');
        }
        print ('</li>');

        print ('</ul>');
    }

    /**
     * プレーンボディ出力
     *
     * @access public
     * @param string $str
     * @return void
     */
    public static function plainBody($str)
    {
        echo strip_tags($str);
    }

    /**
     * ラジオボタンの出力
     *
     * @access public
     * @param string $name
     * @param array $options
     * @param mixed $checked
     * @param string $separator
     * @return void
     */
    public static function radio($name, $options, $checked=null, $separator='&nbsp;')
    {
        foreach ($options as $id=>$label){
            print ('<label>');
            print ('<input class="check" type="radio" name="'.$name.'" value="'.$id.'"');
            if ($checked == $id){
                print (' checked="checked"');
            }
            print (' />'.$label.'</label>');
            print ($separator);
        }
    }

    /**
     * リファレンスの出力
     *
     * @access public
     * @param string $table
     * @param mixed $id
     * @return void
     */
    public static function reference($table, $id, $column=null)
    {
        if (empty($column)){
            $pos = strpos($table, '_');
            if ($pos === false){
                $column = 'label';
            } else {
                $column = substr($table, $pos+1);
            }
        } // if (empty($column))
        

        $row = RKT_DB::getRow($table, $id, $column);
        print ($row[$column]);
    }

    /**
     * 必須項目の出力
     *
     * @access public
     * @return void
     */
    public static function requires()
    {
        $nonce = RKT_Crypt::getNonce('manipNonce');
        print ('<input name="_mpnnc" type="hidden" value="'.$nonce.'" />');

        if (SID !== ''){
            $sid = htmlspecialchars(session_id(), ENT_QUOTES);
            print ('<input name="'.RKT_session::SESSION_KEY.'" type="hidden" value="'.$sid.'" />');
        }
    }

    /**
     * リッチエディタ用出力
     *
     * @access public
     * @param string $name
     * @param string $value
     * @param string $title
     * @param string $size
     * @return void
     */
    public static function richEditor($name, $value, $title, $size='large')
    {
        /* プラグインによる処理 */
        $value = loadPlugin::exec()->outputEditorBody($value);
        
        $area   = 'rEditor';
        $width  = ($size == 'large')? '480':'380';
        $height = ($size == 'large')? '300':'200';
        
        print ('<textarea id="'.$area.'" name="'.$name.'" cols="40" rows="6">');
        print ($value);
        print ('</textarea>');
        print ('<script type="text/javascript">');
        print ('YAHOO.util.Event.onContentReady("'.$area.'", function() {');
        print ("editorType = '".$size."';");
        print ('richEditor("'.$area.'", "'.$title.'", "'.$width.'", "'.$height.'");');
        print ('});');
        print ('</script>');
    }

    /**
     * 指定文字数に丸める
     *
     * @access public
     * @param string $str
     * @param integer $length
     * @param string $trimmarker
     * @param string $encoding
     * @return void
     */
    public static function strimWidth($str, $length=200, $trimmarker="....", $encoding=NULL)
    {
        $str = strip_tags($str);
        $str = mb_strimwidth($str, 0, $length, $trimmarker);

        /* $str = wordwrap($str, 30, '<wbr>', true); */
        $result = '';
        $start  = 0;    
        $chunk  = $width = 30;
        $length = mb_strlen($str);    
        while ($length > 0){
            if ($length < $width){
                $chunk = $length;
            }
            $result .= mb_substr($str, $start, $chunk);
            $result .= '<wbr>';
            $start  += $width;
            $length -= $width;
        }
        print ($result);
    }

    /**
     * 日付のセレクト出力
     *
     * @access public
     * @param string $name
     * @param string $checked
     * @return void
     */
    public static function timeHidden($name, $checked=null)
    {
        $checked   = joinDate($checked);
        $checked   = empty($checked)? 'now':$checked;
        $timestamp = strtotime($checked);

        $hour    = date('H', $timestamp);
        $minute  = date('i', $timestamp);
        $seconds = date('s', $timestamp);
        print ('<input type="hidden" name="'.$name.'[hour]" value="'.$hour.'" />');
        print ('<input type="hidden" name="'.$name.'[minute]" value="'.$minute.'" />');
        print ('<input type="hidden" name="'.$name.'[seconds]" value="'.$seconds.'" />');
    }

    /**
     * 絶対パス用SID付加
     *
     * @access private
     * @parmas string $string
     * @return string
     */
    public static function transSessionID($string)
    {
        $pattern = '(href=\"'.preg_quote(BASE_URL, '/').
                   '(?:%[0-9a-f]{2}|[-a-z0-9_.!~*\'()\/:@\&=+$,;])*)+'.
                   '(\?(?:%[0-9a-f]{2}|[-a-z0-9_.!~*\'()\/:@\&=+$,;])*)?'.
                   '(\#(?:(?:%[0-9a-f]{2}|[-a-z0-9_.!~*\'();\/?:@\&=+$,])*))?\"';
        $func = array(__CLASS__, '_addSessionID');
        $string = preg_replace_callback('/'.$pattern.'/i', $func, $string);

        return $string;
    }

    /**
     * SID付加
     *
     * @access private
     * @parmas array $matches
     * @return string
     */
    private static function _addSessionID($matches)
    {
        $href = $matches[1];
        if (empty($matches[2])){
            $href .= '?'.SID;
        } else {
            $href .= $matches[2].'&'.SID;
        }
        $href .= empty($matches[3])? '"':$matches[3].'"';
    
        return $href;
    }

    /**
     * ページ送り情報配列の設定
     *
     * @access private
     * @param array $pager
     * @param string $request
     * @param string $separator
     * @return void
     */
    private function _setPager($pager, $request, $separator)
    {
        $self = getUrlSelf();
        
        /* 現在のページより左がわのページャーを取得 */
        $page  = $pager['page'] - HTML::PAGER_WIDTH;
        $page  = ($page <= 0)? 1:$page;
        for ($page; $page<$pager['page']; $page++){
            print ('<a href="'.$self.US.'page='.$page.'&amp;'.$request.'">'.($page).'</a>');
            print ($separator);
        }

        /* 現在のページャーを取得 */
        print ('<strong>'.($pager['page']).'</strong>');
        print ($separator);


        /* 現在のページより右がわのページャーを取得 */
        $max_page = $pager['page'] + HTML::PAGER_WIDTH;
        $max_page = ($max_page >= $pager['max_page'])? $pager['max_page']:$max_page;
        for ($page++; $page<=$max_page; $page++){
            print ('<a href="'.$self.US.'page='.$page.'&amp;'.$request.'">'.($page).'</a>');
            print ($separator);
        }
    }
} // HTML
?>
