#
type cgiinit >/dev/null 2>&1 || . ./s4-funcs.sh

blog_genform() {
  #
  t=$1 
}

blog_writable() (
  # $1=articleid $2=user
  blogowner=`getvalbyid blog owner "$1"`
  [ x"$blogowner" = x"$2" ] || isuser "$blogowner" || ismember "$2" "$blogowner"
)
blog_readable() {
  # $1=articleid $2=user
  mode=`getgroupattr $grp regmode`
}
blog_notify_reply() (
  # $1=articleid $2=ReplyingUser $3=WrittenText $4(optional)=Action
  blogowner=`getvalbyid blog owner "$1"`
  [ x"$2" = x"$blogowner" ] && return # If author=blogowner, unnecessary
  blogtitle=`getvalbyid blog title "$1"`
  blogurl="$urlbase?replyblog+$1"
  action=${4:-書き込み}
  mode=`getvalbyid blog notify "$1"`
  case $mode in
    admin)
      if isgroup "$blogowner"; then
	emails=`getgroupadminmails $blogowner`
      else
	emails=`collectemail $blogowner`
      fi
      notifyto=`getpar notifyto`
      if [ -n "$replyto" ]; then
	emails=$emails" `email4groupbyuid \"$blogowner\" $notifyto`"
      fi
	;;
    no)		return ;;
    *)		emails=`collectemail $blogowner` ;;
  esac
  err notify: user=$user Admins=`getgroupadmins $blogowner` Mode=$mode Emails="[$emails]"
  SMAIL_TO="`echo "$blogowner" | nkf -jM | tr -d '\n'` readers <$admin>" \
	  smail "$emails" "${action}通知 $urlbase"<<EOF
[$blogtitle]板に${action}がありました。
場所: $blogurl
題目: $blogtitle
筆者: `gecos $2`
内容:
`echo "$3"|sed 's/^/> /'`
EOF
)
blog_showentry() {
  # $1=table $2=rowid
  # if [ -n "$2" ]; then
  #   if [ -n "$imgcached" ]; then
  #     bstmpdir=$tmpdir/$imgcached/$thumbxy
  #   else
  #     bstmpdir=$tmpd
  #     # tmpd=`mktempd`
  #     # tmpfiles=$tmpfiles" $tmpd"
  #   fi
  # fi
  td=`getcachedir "article/$2"`
  tbl=${1%%[!A-Z0-9a-z_]*} rowid=${2%%[!A-Z0-9a-z_]*}
err rowid=$rowid, '$2'=$2
  ts=${tbl}_s tm=${tbl}_m
  at=article as=article_s am=article_m
  serial=$(($(date +%s)-1420038000))s$$
  blog_writable $rowid $user && iswritable=true || iswritable=false
  # This function grasps blog entry definiton directly.
  # blog:   id
  # blog_s: title,ctime,heading
  # blog_m: *article

  # 2015-10-05 check readable
  if ! $iswritable; then
    blogowner=`getvalbyid blog owner "$2"`
    # err blogowner=$blogowner
    if isgroup $blogowner; then
      regmode=`getgroupattr $blogowner regmode`
      # err regmode=$regmode
      if [ x"$regmode" = x"moderated" ]; then
	if ! ismember $user $blogowner; then
	  echo "加入してからどうぞ" | html p
	  return
	fi
      fi
    fi
  fi

  err "SELECT id from $tbl where rowid=$rowid"
  id=`query "select id from $tbl where rowid=$rowid;"`
err id=$id
err "select val from $ts where key='title' and id='$id';"


  #(1)Display root article
  cat<<EOF
<form class="replyblog" action="$myname?replyblog+${rowid}#bottom" method="POST" enctype="multipart/form-data">
<table class="bloghead">
EOF

  href="<a href=\"?editheading+$rowid\"> 編集 </a>"
  if $iswritable; then
    href2="<a href=\"?lshandout+$rowid\"> 提出状況 </a>"
    href3="(<a href=\"?gethandout+$rowid\">ファイル取得</a>)"
  fi
  cat<<EOF | sq -html $db \
      | sed -e "s|\(<TR><TD>\),e,|\1 $href |" \
	    -e "s|,s,\(</TD>\)|$href2$href3\1|"
-- select val from $ts where key="title" and id="$id";
select
 coalesce((select ",e," from blog where rowid=$rowid and author='$user'),'')
||val||" "
||case (select val from $ts where key="mode" and id="$id")
  when 'report-closed' then "レポート提出用(自身のファイルのみ参照可),s,"
  when 'report-open' then "レポート提出用,s,"
  else ""
  end
 from $ts where key="ctime" and id="$id";
select val from $ts where key="heading" and id="$id";
EOF
  cat<<EOF
</table>
<table class="blog_replies">
EOF

  #(2)Display following articles
textform='<div><table class="b">
<tr><td><textarea name="text" cols="40" rows="4"></textarea></td></tr>
<tr><td>添付ファイル: <input type="file" name="image" multiple></td></tr>
</table>
<input type="submit" value="送信">
<input type="reset" value="リセット"></div>
'
  ## 6/11の次: articleを出して行く
: <<EOF
シリアル:id:p:serial:
blogID:blogid:f:blog(id):
筆者:author:s:owner
時刻:ctime:s:stamp:
参照元:parent:s:parent: 
パス:path:s:path:
本文:text:s:textarea:cols="60" rows="8"
画像:image:m:image:
stage:stage:x:hidden:value="replyblog"

article(id, blogid, author)
article_s: Visible = ctime, text	Invisible = parent, path
article_m: image

article	=	hoge|1433812374x20849|yuuji@gentei.org
article_s =	hoge|ctime|string|2015-06-13 12:27:34|
		hoge|text|string|Shall we dance?|
EOF
  ## 
  ## 
err "select id from $at where blogid='$id';"
#  arts=`sq $db "select a.rowid,a.id,
#-- coalesce(b.gecos, a.author)
# a.author from $at a
# LEFT JOIN (select name,val as gecos from user_s where key='gecos') b
# on a.author=b.name where blogid='$id'";`
  arts=`query "select rowid,id,author from $at where blogid='$id';"`
# err  arts="[$arts]"
  number=0
  hrefhome0="<a href=\"?home"
  for a in $arts; do
    arid=${a%%\|*} aid=`echo "$a"|cut -d'|' -f2` author=${a##*\|} imgs=""
    ## err a=$a, aid=$aid, author=$author
    ## err td=$td
    val=`getvalbyid article image "$arid" "$td"`
    ## err val="[$val]" and td as follows:
    
    if [ -n "$val" ]; then
      hrfb="$myname?showattc+article_m"
      imgs="<br>"$(echo "$val"\
			|while read fn; do

			   #data=`percenthex $td/$fn`
			   #ct=`cat $td/$fn.content-type`
			   sz=`cat $td/$fn.size`
			   ri=`cat $td/$fn.rowid`
	##  err fn=$fn ct=$ct ri=$ri ls::: "`ls -lF $td/`"
			   iconhref2 $td/$fn "$hrfb+$ri" "$fn" "$fn($sz)"
			   echo "<br>"
			 done)
      imgs=`echo "$imgs"|tr -d '\n'`	# kill newlines for sed
    fi

    ### number=$((number+1))
#    reply="<input type=\"radio\" name=\"parent\" class=\"replybtn\" \
# value=\"$number\">"
    getgecos="(select rowid from user where name='$author')||':'||\
	coalesce((select val from user_s \
	where name='$author' and key='gecos'), '$author')||',[/a],'"
    href="$myname?editart+$arid+$rowid"
    link="<a href=\"$href\">編集</a>"
    cat<<EOF | sq -html $db \
	| sed -e "s|,n,\([0-9]*\):|,n,$hrefhome0+\1\">|" \
	      -e 's|,\[/a\],|</a>|' \
	      -e 's/,n,/<br>/g' -e "s|,i,|$imgs|" \
	      -e "s|<TR>\(<TD>\)|<TR id=\"$aid\">\1|" \
	      -e "s|^href=\([-A-Za-z0-9,.:/~_%#&+?]*\)|<a &>\1</a>|" \
	      -e "s|\(<TR.*>\)\(<TD>\),e,|\1\2$link|"
select
  coalesce((select ",e," from article where id='$aid' and author='$user'),"")
  ||
  max(case key when 'ctime' then ",n,"||val||
  ",n,"||$getgecos end) as TIME,
--  max(case key when 'parent' then val||"への返信" end) as REPLYTO,
  max(case key when 'text' then val||",i," end) as TEXT
  from article_s where id = '$aid'
  group by id order by TIME;
EOF
  done
  echo "</table>"

  
  $iswritable && cat<<EOF
<div class="blogcomment">
<p>コメント記入</p>
<input type="hidden" name="blogid" value="$id">
<input type="hidden" name="stage" value="replyblog">
<input type="hidden" name="serial" value="$serial">
$textform
</div>
EOF
  echo "</form><p id=\"bottom\"></p>"
  # Record access log
  acclog blog $rowid
}

blog_showentry2() {
  # $1=table $2=rowid
  # if [ -n "$2" ]; then
  #   if [ -n "$imgcached" ]; then
  #     bstmpdir=$tmpdir/$imgcached/$thumbxy
  #   else
  #     bstmpdir=$tmpd
  #     # tmpd=`mktempd`
  #     # tmpfiles=$tmpfiles" $tmpd"
  #   fi
  # fi
  td=`getcachedir "article/$2"`
  tbl=${1%%[!A-Z0-9a-z_]*} rowid=${2%%[!A-Z0-9a-z_]*}
err rowid=$rowid, '$2'=$2
  ts=${tbl}_s tm=${tbl}_m
  at=article as=article_s am=article_m
  serial=$(($(date +%s)-1420038000))s$$
  blog_writable $rowid $user && iswritable=true || iswritable=false
  # This function grasps blog entry definiton directly.
  # blog:   id
  # blog_s: title,ctime,heading
  # blog_m: *article

  # 2015-10-05 check readable
  if ! $iswritable; then
    blogowner=`getvalbyid blog owner "$2"`
    # err blogowner=$blogowner
    if isgroup $blogowner; then
      regmode=`getgroupattr $blogowner regmode`
      # err regmode=$regmode
      if [ x"$regmode" = x"moderated" ]; then
	if ! ismember $user $blogowner; then
	  echo "加入してからどうぞ" | html p
	  return
	fi
      fi
    fi
  fi
  case `getvalbyid blog notify "$2"` in # "all", "admin" or "no" (or NULL)
    admin)	notifyto=1 ;;
    *)		notifyto="" ;;
  esac

  err "SELECT id from $tbl where rowid=$rowid"
  id=`query "select id from $tbl where rowid=$rowid;"`
err id=$id
err "select val from $ts where key='title' and id='$id';"


  #(1)Display root article
  cat<<EOF
<form class="replyblog" action="$myname?replyblog+${rowid}#bottom" method="POST" enctype="multipart/form-data">
<table class="bloghead">
EOF

  href="<a href=\"?editheading+$rowid\"> 編集 </a>"
  if $iswritable; then
    href2="<a href=\"?lshandout+$rowid\"> 提出状況 </a>"
    href3="(<a href=\"?gethandout+$rowid\">ファイル取得</a>)"
  fi
  href4='<a href="#bottom"> 末尾へ</a>'
  cat<<EOF | sq -html $db \
      | sed -e "s|\(<TR><TD>\),e,|\1 $href |" \
	    -e "s|,s,|$href2$href3|" \
	    -e "s|,t,\(</TD\)>|$href4\1|"
-- select val from $ts where key="title" and id="$id";
select
 coalesce((select ",e," from blog where rowid=$rowid and author='$user'),'')
||val||" "
||case (select val from $ts where key="mode" and id="$id")
  when 'report-closed' then "レポート提出用(自身のファイルのみ参照可),s,"
  when 'report-open' then "レポート提出用,s,"
  else ""
  end || ',t,'
 from $ts where key="ctime" and id="$id";
select val from $ts where key="heading" and id="$id";
EOF
  cat<<EOF
</table>
<table class="blog_replies">
EOF

  lkhome="<a href=\"$myname?home" lke='">'
  lkedit="<a href=\"$myname?editart"
  if false; then
    sq -html $db<<EOF |
WITH a_s AS (
  SELECT id,
         max(CASE key WHEN 'ctime' THEN val END) TIME,
         max(CASE key WHEN 'text' THEN val END) TEXT
  FROM article_s
  GROUP by id
)
SELECT	'id:'||a.id,
	CASE author
	WHEN '$user' THEN 'ed:'||a.rowid||':'||$rowid
	ELSE 'e0:'
	END edit,
	'at:'||(SELECT rowid FROM user WHERE name=author)||':'
	     ||coalesce((SELECT val FROM user_s
			 WHERE name=author AND key='gecos'),
			author),
	'ti:'||s.TIME,
	'te:'||s.TEXT,
	'im:'||(SELECT group_concat(hex(bin)
FROM (select rowid,id,author from article where blogid in
     (select id from blog where rowid=$rowid)) a
  LEFT JOIN
     a_s s
  ON a.id=s.id;
EOF
  sed -e "s|^<TR><TD>id:\(.*\)</TD>|<TR id=\"\1\"><TD>|" \
      -e "/^<TR/N" -e 's/\n//' \
      -e "s|<TD>ed:\([0-9]*\):\(.*\)</TD>|$lkedit+\1+\2${lke}編集</a>|" \
      -e "s|<TD>e0:</TD>||" \
      -e "s|^<TD>at:\([0-9]*\):\(.*\)</TD>|$lkhome+\1$lke\2</a>|" \
      -e "s|^<TD>ti:\(.*\)</TD>|\1</TD>|" \
      -e "s|^<TD>te:\(.*\)|<TD>\1|"
  else
    hlink="$myname?home" elink="$myname?editart"
    catlink="$myname?showattc+article_m"
    deficon="img/file-icon.png"
    sq $db<<EOF |
WITH a_s AS (
  SELECT id,
         max(CASE key WHEN 'ctime' THEN val END) TIME,
         max(CASE key WHEN 'text' THEN val END) TEXT
  FROM article_s
  GROUP by id
)
SELECT	a.id,
	CASE author
	WHEN '$user' THEN a.rowid||'+'||$rowid
	ELSE ''
	END edit,
	CASE -- 「通知送信」ボタンの有無
	WHEN '$notifyto' = '' THEN ''	-- 不要モードならなし
	WHEN '$user' = author THEN ''	-- 筆者自身ならなし
	ELSE "yes"
	END notify,
	(SELECT rowid FROM user WHERE name=author) user_rid,
	coalesce((SELECT val FROM user_s
			 WHERE name=author AND key='gecos'),
			author) uname,
	s.TIME,
	hex(s.TEXT),
	(SELECT group_concat(rowid||':'||length(bin)||':'||hex(val), ' ')
	 FROM article_m
	 WHERE id=a.id AND key='image') imxgids
FROM (select rowid,id,author from article where blogid in
     (select id from blog where rowid=$rowid)) a
  LEFT JOIN
     a_s s
  ON a.id=s.id;
EOF
    while IFS='|' read id edit notify uid uname tm hte imgids; do
      nt="<label style=\"font-size: 70%;\"><input type=\"checkbox\"
	 name=\"notifyto\" value=\"$uid\">返信通知送信</label>"
      cat<<EOF |
<tr id="$id">
<td>${edit:+<a href="$elink+$edit">編集</a>}
<a href="$hlink+$uid">$uname</a>
$tm
${notify:+$nt}</td><td>`echo "$hte"|unhexize|htmlescape`
EOF
      sed -e "s|^href=\([-A-Za-z0-9,.:/~_%#&+?]*\)|<a &>\1</a>|"
      for i in $imgids; do
	mrid=${i%%:*}; i=${i#*:}; sz=`size_h ${i%%:*}`
	fn=`echo "${i#*:}"|unhexize`
	fnb=$fn"(${sz})"
	# echo r=$mrid fn=$fn
	case "$fn" in
	  *.[Pp][Nn][Gg]|*.[Jj][Pp][Gg]|*.[Jj][Pp][Ee][Gg])
	    sq $db "SELECT hex(bin) FROM article_m WHERE rowid=$mrid" \
		| unhexize \
		| convert -define jpeg:size=100x100 -resize 100x100'>' - jpeg:- \
		| hexize \
		| sed -e 's/\(..\)/%\1/g' \
	    	      -e "s|^|<a href=\"$catlink+$mrid\"><img src=\"data:image/jpeg,|" \
		      -e "s|\$|\">$fnb</a>|"
	    ;;
	  *)
	    echo "<a href=\"$catlink+$mrid\"><img src=\"$deficon\">$fnb</a>"
	    ;;
	esac
      done
    done
  fi

  textform='<div><table class="b">
<tr><td><textarea name="text" cols="40" rows="4"></textarea></td></tr>
<tr><td>添付ファイル: <input type="file" name="image" multiple></td></tr>
</table>
<input type="submit" value="送信">
<input type="reset" value="リセット"></div>
'
  echo '</table>'
  
  $iswritable && cat<<EOF
<div class="blogcomment">
<p>コメント記入</p>
<input type="hidden" name="blogid" value="$id">
<input type="hidden" name="stage" value="replyblog">
<input type="hidden" name="serial" value="$serial">
$textform
</div>
EOF
  echo "</form><p id=\"bottom\"></p>"
  # Record access log
  acclog blog $rowid
}

lshandout() {
  # $1=rowid of blog
  if ! blog_writable $1 $user; then
    echo "メンバー以外は利用できません。" | html p; return
  fi
  time=`getvalbyid blog ctime $1|colrm 11`
  owner=`getvalbyid blog owner $1`
  title=`getvalbyid blog title $1`
  ge=`gecos $owner`
  lshandoutsub $owner "$@" \
      |m4 -D_TITLE_="提出状況" \
	  -D_FORMHEAD_="$time [$title]@${ge:-$owner}" \
	  -D_FORM_="syscmd(cat)" -D_DUMPHEAD_= -D_DUMPTABLE_= \
	  $layout/html.m4.html $layout/form+dump-whead.m4.html
}
lshandoutsub() {
  # $1=owner $2=rowid of blog
  if isgroup $1; then
    sample="(select user from grp_mem where gname='$1')"
  else
    sample="(select distinct author as user from arts)"
    echo "(集計は板への投稿者のみ)" | html p
  fi
  sql="with arts as (select id,author from article \
	    where blogid=(select id from blog where rowid=$2))\
      select (select rowid from user where name=c0.user)||'	'|| \
	      coalesce((select val from user_s where name=c0.user \
			and key='gecos'),\
		      c0.user) as 'メンバー',\
	     sum(case when c1.key is not null then 1 else 0 end)\
		 as 'コメント記入',\
	     sum(case when c2.key is not null then 1 else 0 end)\
		 as 'ファイルの提出'\
	 from $sample c0 \
	        left join (select id,author from arts) a\
		on c0.user=a.author\
	        left join (select id,key from article_s where key='text') c1\
		on a.id=c1.id left join (select id,key from article_m ) c2\
		on c1.id=c2.id group by c0.user order by c0.user;"
    err ishandoutsub: sql="$sql"
    echo '<table class="b td2r td3r">'
    hrb="<a href=\"?home+"
    echo "$sql" | sq -header -html $db \
	| sed -e "s,\(<TR><TD>\)\([^	]*\)	\(.*\)</TD>,\1$hrb\2\">\3</TD>," -e 's,<TD>0</TD>,<TD class="warn">0</TD>,'
    echo '</table>'
}
gethandout() {
  # $1=rowid of blog
  if ! blog_writable $1 $user; then
    echo "メンバー以外は利用できません。" | html p; return
  fi
  i=0
  bd=$tmpd/archive.$$
  mkdir $bd
  query "select m.rowid,author,m.val from article a join article_m m\
	 on a.id=m.id where blogid=(select id from blog where rowid=$1)\
	 and m.key in ('image', 'document', 'binary');" \
      | while IFS='|' read rowid author filename; do
	  # err isfilereadable $user article_m $rowid
	  isfilereadable $user article_m $rowid || continue
	  # err ok
	  i=$((i+1))
	  dir=`printf $bd/%03d $i`
	  mkdir $dir
	  query "select quote(bin) from article_m where rowid=$rowid;" \
	      | unhexize > $dir/$filename
	done
  if [ ! -d $bd/001 ]; then
    contenttype; echo
    echo "取得できるファイルがありませんでした。" | html p
    return
  fi
  (cd $bd
   err cdto$bd; (pwd; ls -lFa) 1>&3
   tar zcf .archive.tar.gz * && mv .archive.tar.gz archive.tar.gz
  )
  arc=$bd/archive.tar.gz
  echo "Content-type: application/x-gzip"
  echo "Content-Length: `cat $arc|wc -c`"
  echo "Content-Disposition: filename=\"archive.tar.gz\""
  echo
  cat $arc
}
lsmyfile() {	# $1(optional)=SortBy
  case "$1" in
    ""|CTIME-DESC)
      		by="CTIME"	ord="DESC" ;;
    CTIME*)	by="CTIME"	;;
    FILE*)	by="FILE"	;;
    OWNER*)	by="OWNER"	;;
    TITLE*)	by="TITLE"	;;
  esac
  case "$1" in
    *DESC)	ord="DESC" ;;
  esac
  case "$ord" in
    DESC)	lkod="" 	jord="降順" ;;
    *)		lkod="-DESC"	jord="昇順" ;;
  esac
  sql="select m.val||'/'||m.rowid FILE,
	      coalesce(
		case when (select name from user where name=bs.owner)
			 is not null
		     then (select val from user_s where name=bs.owner
				and key='gecos')
		     when (select gname from grp where gname=bs.owner)
			 is not null
		     then (select val from grp_s where gname=bs.owner
				and key='gecos')
		     else
			null
		 end,
		 bs.owner
		) OWNER,
	      a_s.val CTIME,
	      ',t,'||bs.title||':'||b.rowid||'#'||a.id TITLE
	 from (select rowid,id,val from article_m where id
		 in (select id from article where author='$user')
		and type like 'file:%')
	m left join article a on m.id=a.id
	  left join article_s a_s on a.id=a_s.id and a_s.key='ctime'
	  left join (select id,
			max(case key when 'owner' then val end) as owner,
		        max(case key when 'title' then val end) as title
			from blog_s group by id)
		     bs on a.blogid=bs.id
	  left join blog b on bs.id=b.id
	  where m.val is not null order by $by $ord;"
  err lshandoutbyauthor: sql=`echo "$sql"`
  title="個人提出ファイル"
  m4 -D_TITLE_=$title $layout/html.m4.html
  hra="<a href=\"?lsmyfile+"
  hrb="<a href=\"?showattc+article_m+"
  hrc="<a href=\"?replyblog+"
  (echo '<table class="b">'
   echo "$sql"|sq -html -header $db ) \
      | sed -e "s|\(<TR><TD>\)\([^/]*\)/\([0-9]*\)|\1$hrb\3\">\2</a>|" \
	    -e "s|,t,\(.*\):\([^<]*\)\(</TD>\)|$hrc\2\">\1</a>\3|" \
	    -e "s|\(<TH>\)\([A-Z]*\)\(</TH>\)|\1$hra\2$lkod\">\2</a>|" \
      | m4 -D_TITLE_=$title -D_FORM_="<p>($by$jord)</p>" \
	   -D_DUMPTABLE_="syscmd(cat)" $layout/form+dump.m4.html
  echo '</table>'
}
searchart() {
  kwd=`getpar kwd`
  if [ -z "$kwd" ]; then
    echo "検索語を指定してください" | html p; return
  fi
  for k in `echo "$kwd" | sed "s/'/''/g"`; do
    kc=$kc${kc:+" AND "}"s.val LIKE '%$k%'"
  done
  kwd=`echo "$kwd"|htmlescape`
  owner=`getpar owner`
  owner=${owner:-$1}
  echo "「$kwd」による検索結果" | html p
  if [ -n "$owner" ]; then
    cond="where key='owner' and val='$owner'"
    if isuser $owner; then
      echo "(`linkhome $owner` さんの記録からの検索)" | html p
    else
      linkhome $owner 1>&3
      echo "(`linkhome $owner` グループからの検索)" | html p
    fi
  fi
  # article_s:	id=article-id, key='text', val='TEXT'
  # article:	id=article-id, blogid=blogkd
  # blog:		id=blog-id, author=LeaderAuthor
  # blog_s:		id=blog-id, key='title', val='BLOG-TITLE'
  # WANT: blog-ROWid,article-id,val(TEXT)
  sql="select b.rowid||'#'||x.id as '',
		  b.title as TITLE,
		  substr(x.val, 0, 80) as TEXT
	from (select blog.rowid,blog.*,bs.val as title from blog join blog_s bs
		on blog.id=bs.id and bs.key='title') b
	  join
	    (select a.id,a.blogid,s.val from article a join article_s s
		 on a.id=s.id where $kc)
	     x on b.id=x.blogid
	 where b.id in (select id from blog_s
	$cond);"
  sedopt="s,<TR><TD>\([^<]*\)</TD>,<TR><TD><a\
 href=\"?replyblog+\1\">VIEW</a></TD>,"
  cat<<EOF
<table class="b searchart">
`sq -header -html $db "$sql"|sed "$sedopt"`
</table>
EOF
}
listblog() (
  # $1={user,group}
  qow=`sqlquote $1`
  cond="where a.id in (select id from blog_s where key='owner' and val=$qow) order by ctime desc"
  DT_CHLD=article:blogid
  cgi_form searchart<<EOF
<label>`cgi_text kwd`という語を含む記事をこの一覧から検索</label>
`cgi_hidden owner $user`
EOF
  dumptable html blog 'ctime title heading' "$cond"
)

blog_addentry() {
  # $1=GRPname(if it is a group)
  grprowid=$1
  rowid=`getpar rowid`
  err blog_addentry0: rowid=$rowid
  if [ -n "$grprowid" ]; then
    owner=`getgroupbyid $grprowid`
  else
    owner=`getpar owner`
  fi
  err blog-add: \$1=$1 rowid=$rowid owner=$owner
  if isgroup $owner; then
    groupmode=1 listing=$owner guide="[${owner}]" GF_OWNER=$owner
  else
    usermode=1 listing=$user guide="[個人]"
  fi

  if [ -n "`getpar title`" ]; then
    if [ "$usermode" ]; then
      err usermode: user=$user owner=$owner
      if [ x"$user" != x"$owner" ]; then
	echo "他人の日記は書けません" | html p
	return 2
      fi
    elif [ "$groupmode" ]; then	# if write to group log
      grp=$owner #\`getpar grp\`
      err ismember: $user $grp
      if ! ismember "$user" "$grp"; then
	echo "(話題作成はこのグループに加入してから)" | html p
	return 3
      fi
    fi
    par2table $formdir/blog.def
    serial=`getpar serial`
    err SERIAL: $serial ROWID=$rowid listing=$listing
    id=""
    if [ -n "$rowid" ]; then
      # Here, id becomes NULL when removal of entries at par2table
      id=`query "select rowid from blog where rowid=$rowid;"`
    elif [ -n "$serial" ]; then
      # If new blog leader created, traverse to its head.
      id=`query "select rowid from blog where id='$serial';"`
      err new-Leader: "select rowid from blog where id='$serial';" id=$id
    fi
    if [ -n "$id" ]; then
      ## If new aritcle is entered, JUMP to blog_reply
      blog_reply $id
      return
    fi
  fi
  echo "${guide}新規話題作成"	> $tmpd/title.$$
  listblog $listing		> $tmpd/listblog.$$
  genform $formdir/blog.def \
      | m4 -D_TITLE_="spaste(\`$tmpd/title.$$')" \
	   -D_FORMHEAD_="序文は簡単に詳しくはコメントに" \
	   -D_DUMPHEAD_="これまでの蓄積" \
	   -D_FORM_="syscmd(\`cat')" \
	   -D_DUMPTABLE_="spaste(\`$tmpd/listblog.$$')" \
	   $layout/html.m4.html \
	   $layout/form+dump-whead.m4.html
}

blog_reply() {
  rowid=$1
err  rowid=$1

  if [ -z "$rowid" ]; then
    echo "表示する日記番号が未指定です。" | html p
    return
  fi
  title=`getvalbyid blog title $rowid`
  owner=`getvalbyid blog owner $rowid`
  if isuser "$owner"; then
    subtitle="`gecos $owner` さんの話題"
  else
    grprowid=`query "select rowid from grp where gname=\"$owner\";"`
    subtitle="グループ <a href=\"?grp+$grprowid\">$owner</a> での話題"
  fi
  if [ -z "$title" ]; then
    echo "日記番号指定が無効です。" | html p
    return
  fi

  text=`getpar text`
  if [ -n "$text" ]; then
    if blog_writable $rowid $user; then
      par2table $formdir/article.def
      st=$?		# ; err par2t-st=$st
      case $st in
	0|4)
	  [ "$st" = "4" ] && act="書込削除"
	  blog_notify_reply $rowid $user "$text" $act ;;
      esac
    else
      title="$title(加入してないので書き込み不可)"
    fi
  fi
  def=$formdir/article.def
  echo "$title" > $tmpd/title.$$
  echo "$subtitle" > $tmpd/subtitle.$$
  ${BLOG_SHOW:-blog_showentry} blog $rowid \
      | m4 -D_TITLE_="spaste(\`$tmpd/title.$$')" -D_BODYCLASS_=general \
	   -D_FORMHEAD_="spaste(\`$tmpd/subtitle.$$')" \
	   -D_FORM_='' \
	   -D_DUMPTABLE_="syscmd(cat)" -D_DUMPHEAD_="" \
	   $layout/html.m4.html $layout/form+dump-whead.m4.html
}
