<?php

/**
  * BLOG:CMS: PHP/MySQL Personal Content Management System (CMS)
  * http://blogcms.com/
  * ----------------------------------------------------------------
  *
  * Copyright (C) 2003-2005 Radek HULÁN
  * http://hulan.cz/contact/
  *
  * ----------------------------------------------------------------
  * This program is free software; you can redistribute it and/or
  * modify it under the terms of the GNU General Public License
  * as published by the Free Software Foundation; either version 2
  * of the License, or (at your option) any later version.
**/

class NP_Table extends NucleusPlugin {

	function getName() 		{ return 'Table'; }
	function getAuthor()  	{ return 'Radek HULAN'; }
	function getURL()  		{ return 'http://hulan.cz/blog/'; }
	function getVersion() 	{ return '0.1'; }
	function getDescription() { return 'Plugin to create multiple tables, add, edit, delete items, display a table in XHTML by %++Table(tablename)++% in article body / more or by <%Table(tablename)%> as a skinvar! There are 2 optional parameters, sortcolumnname, and ASC/DESC/NONE sorting order, e.g. %++Table(tablename,columnname,asc)++%';	}

	function supportsFeature($what) {
		switch($what)
		{ case 'SqlTablePrefix':
				return 1;
			default:
				return 0; }
	}

  function _getColumns(){ return intval($this->getOption('columns')); }
  
	function install() {
		$this->createOption('quickmenu', 'Show in quick menu', 'yesno', 'yes');
		$this->createOption('columns', 'Maximum number of columns', 'text', '5');
	}
	
	function getTableList() {
		return array(sql_table('plug_table_head'),sql_table('plug_table_row'),sql_table('plug_table_item'));
	}

	function getEventList() {
		return array('PreItem', 'QuickMenu');
	}
	
	function hasAdminArea() {
		return 1;
	}
	
	function event_QuickMenu(&$data) {
		// only show when option enabled
		if ($this->getOption('quickmenu') != 'yes') return;
		global $member;
		// only show to admins
		if (!($member->isLoggedIn() && $member->isAdmin())) return;
		array_push(
			$data['options'], 
			array(
				'title' => 'Lists',
				'url' => $this->getAdminURL(),
				'tooltip' => 'Create lists and tables, Add, Edit, Delete Items.'
			)
		);
	}

  function cmp ($a,$b) {
   global $sortrowid,$sorttype,$sortorder;
   if ($sorttype==1) 
     return $sortorder*strcmp($a[$sortrowid],$b[$sortrowid]);
   else
     if ($a[$sortrowid]>$b[$sortrowid]) 
       return $sortorder; 
     else 
       if ($a[$sortrowid]<$b[$sortrowid]) return -1*$sortorder; else return 0;
  } 

  function _printTable($tablename,$rowname,$typ){
    // get table id and templates
    $tablename=sql_escape(sql_unescape($tablename));
    $query=sql_query("select tableid, theader, titem1, titem2, tfooter, title, description from ".sql_table('plug_table_head')." where title='$tablename'");
    if (!$row=sql_fetch_object($query)) return "<br /><br /><p style='color:red'>Error: specified table '$tablename' was not found! Check your syntax!</p><br /><br />";
    $tableid=strval($row->tableid);
    // templates
    $theader=sql_unescape($row->theader);
    $titem1=sql_unescape($row->titem1);
    $titem2=sql_unescape($row->titem2);
    $tfooter=sql_unescape($row->tfooter);
    // header
    $from=array('<%tabletitle%>','<%tabledescription%>');
    $to  =array(sql_unescape($row->title),sql_unescape($row->description));
    for ($i=0;$i<sizeof($from);$i++) $theader=str_replace($from[$i],$to[$i],$theader);
    // footer
    for ($i=0;$i<sizeof($from);$i++) $tfooter=str_replace($from[$i],$to[$i],$tfooter);
    // total rows
    $query=sql_query("select count(rowid) as total from ".sql_table('plug_table_row')." where tableid=$tableid");
    $row=sql_fetch_object($query);
    $numrows=$row->total;
    // from items array template
    $from=array();
    $query=sql_query("select rowid, rowtitle from ".sql_table('plug_table_row')." where tableid=$tableid order by rowid asc");
    while ($row=sql_fetch_object($query)) $from[]='<%'.sql_unescape($row->rowtitle).'%>';
    // read all items into an array
    $query=sql_query(
      "select i.itemid as xitemid, i.rowid as xrowid, i.itemtext as xitemtext, i.itemint as xitemint, r.rowtype as xrowtype ".
      " from ".sql_table('plug_table_row')." r, ".sql_table('plug_table_item')." i ".
      " where r.tableid=$tableid and r.tableid=i.tableid and r.rowid=i.rowid ".
      " order by xitemid asc,xrowid asc");
    $first=true;
    $itemnumber=0;
    $results=array();
    // create array
    while ($arr=sql_fetch_row($query)){
      if (intval($arr[4])==1) $value=sql_unescape($arr[2]); else $value=$arr[3];
      $results[$itemnumber][$arr[1]-1]=$value;
      if ($arr[1]==$numrows) $itemnumber++;
    }
    // prepare sort options
    if (strtolower(substr($typ,0,1))!='n') {
      global $sortrowid,$sorttype,$sortorder;
      $query=sql_query("select rowid, rowtype from ".sql_table('plug_table_row')." where rowtitle='$rowname' and tableid=$tableid");
      if ($row=sql_fetch_object($query)) {
        $sortrowid=$row->rowid-1; 
        $sorttype=$row->rowtype;
      } else {
        $sortrowid=0; 
        $query=sql_query("select rowid, rowtype from ".sql_table('plug_table_row')." where rowid=1 and tableid=$tableid");
        if (!$row=sql_fetch_object($query)) return "<br /><br /><p style='color:red'>Error: specified table '$tablename' was not found! Check your syntax!</p><br /><br />";
        $sorttype=intval($row->rowtype);
      }
      if (strtolower(substr($typ,0,1))=='a') $sortorder=1; else $sortorder=-1;
      // sort it!
      usort($results, array("NP_Table", "cmp")); 
    }
    // print sorted items
    $first=true;
    $fullitem="";
    for ($i=0;$i<$itemnumber;$i++){
      $to=array();
      for ($rowid=0;$rowid<$numrows;$rowid++) $to[]=$results[$i][$rowid];
      if ($first) $temp=$titem1; else $temp=$titem2;
      $first=!$first;
      for ($j=0;$j<sizeof($from);$j++) $temp=str_replace($from[$j],$to[$j],$temp);
      $fullitem.=$temp;
    }
    // return results
    return $theader.$fullitem.$tfooter;
  }

	function doSkinVar($skinType, $table='', $row='', $typ='asc') {
	  echo $this->_printTable($table,$row,$typ);
	}
	
	function event_PreItem($data) {
	  $parts=array('body','more');
	  foreach ($parts as $part){
	    $pos1=strpos($data['item']->$part,"%++Table("); 
	    while ($pos1!==false) {
	      $pos2=strpos(substr($data['item']->$part,$pos1+9),")++%"); 
        if ($pos2===false) break;
        $table=substr($data['item']->$part,$pos1+9,$pos2);
        $row='';
        $typ='asc';
        if (!(strpos($table,',')===false)) {
          $row=substr($table,strpos($table,',')+1);
          $table=substr($table,0,strpos($table,','));
        }
        if (!(strpos($row,',')===false)) {
          $typ=substr($row,strpos($row,',')+1);
          $row=substr($row,0,strpos($row,','));
        }
        $s=$this->_printTable($table,$row,$typ);
        $data['item']->$part=substr($data['item']->$part,0,$pos1).$s.substr($data['item']->$part,$pos1+$pos2+13);
        $pos1=strpos($data['item']->$part,"%++Table("); 
	    } 
	  }
	}

}
?>