<?
// Your agreement with TNuG gives you a limited license to access and use this library.
// You may access the library for your own private or business use.
// You may not reproduce, copy, or redistribute, whole or in part, any of the library that constitutes the TNuG's library functions without written permission.

// Object Template Stripped Version
// Version 0.3h

// Version 0.3h - Changed methods system and added proclayout
//              - removed header/footer, never used
//              - added sorting of results
// Version 0.3g - Update to select optimization, changed text to number field
// Version 0.3f - Update to select optimization, added fieldname
// Version 0.3e - Multiple DB Support by declaration of $SQL_APP_DB
// Version 0.3d - Large record select optimize by full flag in getpictureformfields
// Version 0.3c - fixed typo in edit patch
// Version 0.3b - fixed typo
//              - start of security patch to edit($id)
// Version 0.3a - getpictureformfields added prepend
//              - massing beginnings
//              - cleaned up & simplified dir & field navigate
//              - moved unnessicary examples to addon to reduce filesize
// Version 0.3 - Page_nav fix
//             - Header Var hook to interface
// Version 0.2.9a - templat_query typo
// Version 0.2.9 - Made remove use view
//               - Created specific groups
// Version 0.2.8a - Fixed some case issues
// Version 0.2.8 - Fixed colors again, added cancel buttons
//                - Fixed find, added picture_ prefix to ses vars to allow layering
//		  - Added Search Form in display, Added LookUp on selects
// Version 0.2.7h - Fixed colors and removed display field ordering
//                - cleaned up search header/footer
//		  - fixed sql search
// Version 0.2.7g - add color in trs
// Version 0.2.7f - Fixed lotsa Errors
// Version 0.2.7e - Paging with search is fixed
//                - New Find/Search/PickRec selection integration
//                - REFixed ugly validation bug wif exit;
// Version 0.2.7d - Speed Ups: change upd to pull 0 instead of $id,
//                - add cache to getpictureform, allow passing of $row
// Version 0.2.7c - Fixed ugly validation bug wif exit; made searches have no rpp
// Version 0.2.7b - messed with pagenav
// Version 0.2.7a - Added Define loaded and Netscape 4.x hack
//
// Version 0.2.7 - Rearranged PagNav, Add RPP, and fixed some var declarations
//               - Fixed <tr> in display
// Version 0.2.6 - Fixed Next/Prev Error -Neuro.
//		 - Add new paging nav - Neuro.
// Version 0.2.5 - prepended picture to search_header and search_footer - Neuro.
//               - Also changed picture_view to use public group - Neuro.
//		 - removed $id from ins - Neuro.
// 		 - Fixed form cache error - Neuro.
//		 - Smore search syntax - Neuro.
// Version 0.2.4 - Added default HIDNUM for IDs to make methods work - Neuro.

function picture_stats($f,$mode=0) {
include "imgstat.php";
colorstats($f,$mode);
}

function getlayout($pictureid=0,$row="") {
global $filename,$myauth,$auth_sid;
global $glob_layout; // norm layout
global $glob_anon; // anon layout
global $glob_header; // used for norm & anon
global $glob_footer;

$glob_layout='';
if ($row['flood']) {
$glob_layout.='<h1>FLOOD PROTECTION ENGAGED</h1>';
}
if ($row['notfinished']) {
$glob_layout.='
<p><b>THIS PICTURE IS UNFINISHED.<br> IT CAN ONLY BE SEEN BY THE MODERATORS AND OWNER OF THE PICTURE.</b><br>

';
}
if ($row['originalid']) {
$res2=sqlexec("select allowcontinue from pictures where pictureid=".$row['originalid']);
list($allowcont)=sqlgetrow($res2);
if ($allowcont || useringroup(array('administrator'))) {
$glob_layout.='Continued from [<A
HREF="'.geturl($filename.'?obj=picture&action=view&id='.$row['originalid']).'">'.$row['originalid'].'</A>],
<A
HREF="'.geturl($filename.'?obj=picture&action=showcont&id='.$row['originalid']).'">Click
here to see the series...</A><br>';
}
/*
$glob_layout.='
Original:
<img src="data/'.$row['originalid'].'.png" width="<width>" height="<height>" alt="<title>" border="0" hspace="8" vspace="8">
';
*/
}

$glob_layout.='
<img src="data/<pictureid>.png" width="<width>" height="<height>" alt="<title>" border="0" hspace="8" vspace="8"><br>';
$glob_layout.='&nbsp;<A
HREF="'.geturl($filename.'?obj=picture&action=view&id='.$row['pictureid'],0).'" class="info">&nbsp;link&nbsp;</a>';
$glob_layout.='&nbsp;<A
HREF="'.geturl($filename.'?obj=picture&action=stats&id=data/'.$row['pictureid'].'.png').'" class="info">&nbsp;Color Stats&nbsp;</A>';

if ($row['anim']) {
if ($row['userid']==$myauth['id']) {
$row['allowanim']=1; $row['allowcontinue']=1;
//if (useringroup(array('administrator'))) {
if ($row['usespainter']) {
$glob_layout.="&nbsp;<A
HREF=\"".geturl('draw2.php3?action=replace&id='.$row['pictureid'])."\" class=\"info\">&nbsp;Refine&nbsp;</A>
\n";
} else {
$glob_layout.="&nbsp;<A
HREF=\"".geturl('draw.php3?action=replace&id='.$row['pictureid'])."\" class=\"info\">&nbsp;Refine&nbsp;</A>
\n";
}
//}
}
if ($row['allowanim']) {
$glob_layout.='&nbsp;<A
HREF="'.geturl($filename.'?obj=picture&action=animate&id='.$row['pictureid']).'" class="info">&nbsp;Animate&nbsp;</A>';
}
if ($row['allowcontinue']) {
if ($row['usespainter']) {
$glob_layout.='&nbsp;<A
HREF="'.geturl('draw2.php3?action=continue&id='.$row['pictureid'].'&anim='.$row['anim']).'" class="info">&nbsp;Continue&nbsp;</A>';
} else {
$glob_layout.='&nbsp;<A
HREF="'.geturl('draw.php3?action=continue&id='.$row['pictureid'].'&anim='.$row['anim']).'" class="info">&nbsp;Continue&nbsp;</A> ';
}
}
}
$seen_data=getuserflagcache();
if ($seen_data[1]['picture'][$row['pictureid']]) {
$type='remove'; $symbol='-'; $val=0;
} else {
$type='add'; $symbol='+'; $val=1;
}
$glob_layout.='&nbsp;<A
HREF="'.geturl($filename.'?obj=auth_user&action=set&type=1&table=picture&id='.$row['pictureid'].'&val='.$val).'"
class="info">&nbsp;'.$symbol.'&nbsp;</A>';
if ($seen_data[1]['user'][$row['userid']]) {
$type='remove'; $symbol='-'; $val=0;
} else {
$type='add'; $symbol='+'; $val=1;
}

if ($row['notfinished']) {
$glob_layout.='<table width="100%" border="0" cellpadding="0" cellspacing="8" align="center">
	  <tr>
	    <td>

		<p><font style="color:#DED7AD; font-size:8pt;">Title: <b><title></b>&nbsp;<br>
		Artist: <b>
<A HREF="'.geturl('interface.php3?obj=picture&action=search&strict=1&name='.$row['name']).'"><name></A></b>&nbsp;&nbsp;<a href="<homepage>" class="info" title="Homepage">&nbsp;hp&nbsp;</a>
 &nbsp;<a href="<email>" class="info" title="Email">&nbsp;em&nbsp;</a>
 &nbsp;<a href="'.geturl('interface.php3?obj=auth_user&action=set&table=user&type=1&val='.$val.'&id='.$row['userid']).'"
class="info" title="'.$type.' favorite artist">&nbsp;'.$symbol.'&nbsp;</a>
<br>

    (';
} else {
$glob_layout.='<table width="100%" border="0" cellpadding="0" cellspacing="8" align="center">
	  <tr>
	    <td>

		<p><font style="font-size:8pt;">Title: <b><title></b>&nbsp;<br>
		Artist: <b>
<A HREF="'.geturl('interface.php3?obj=picture&action=search&strict=1&name='.$row['name']).'"><name></A></b>&nbsp;
 &nbsp;<a href="<homepage>" class="info" title="Homepage">&nbsp;hp&nbsp;</a>
 &nbsp;<a href="<email>" class="info" title="Email">&nbsp;em&nbsp;</a>
 &nbsp;<a href="'.geturl('interface.php3?obj=auth_user&action=set&table=user&type=1&val='.$val.'&id='.$row['userid']).'"
class="info" title="'.$type.' favorite artist">&nbsp;'.$symbol.'&nbsp;</a>
';
}

if (useringroup(array('administrator'))) {
$glob_layout.=' &nbsp;<a href="#" class="info">IP <ipaddress></a>';
}
$glob_layout.='<br>';
if (useringroup(array('administrator'))) {
$glob_layout.='<b>Started:&nbsp;</b><start> - ';
}
$glob_layout.='<b>Finished:&nbsp;</b><stop></p>

       <p><authorcomments><br>
	 </tr>

';
// start anon content
$glob_anon='<img src="data/<pictureid>.png" width="<width>" height="<height>" alt="<title>" border="0" hspace="8" vspace="8"><br>
';
$glob_anon.='
&nbsp;<A class="info" HREF="'.geturl($filename.'?obj=picture&action=view&id='.$row['pictureid'],0).'">Link</A>
';
$glob_anon.='&nbsp;<A
HREF="'.geturl($filename.'?obj=picture&action=stats&id=data/'.$row['pictureid'].'.png').'" class="info">&nbsp;Color Stats&nbsp;</A>';
$glob_anon.='<table width="100%" border="0" cellpadding="0" cellspacing="8" align="center">
	  <tr>
	    <td>

		<p><font>Title: <b><title></b><br>
    Artist: <b>Anonymous</b><br>';
if (useringroup(array('administrator'))) {
$glob_anon.='<b>Started:&nbsp;</b><start> - ';
}
$glob_anon.='<b>Finished:&nbsp;</b><stop><br>
    </center></p>
    <p><b>Artist\'s Comments:</b><br>
    <authorcomments></p>
';
// end anon conent
$glob_header=''; // before layout
$glob_footer='<tr>
	    <td bgcolor="#DED7AD"><img src="image/space.gif" width="1" height="1" border="0" alt=""></td>
	  </tr>
    </table>
	<p>&nbsp;<a href="http://oekaki.kenshin.net/002" class="info2">&nbsp;click here to reload the page&nbsp;</a>&nbsp;&nbsp;<a href="'.geturl($filename.'?obj=comment&action=new&pictureid='.$pictureid).'" class="info2">&nbsp;comment&nbsp;</a></p>
	<table width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#5A596B"><tr><td><img src="image/space.gif" width="1" height="1" border="0" alt=""></td></tr></table>
	';
if ($row['flood']) {
$glob_footer.='';
}
}

if (defined("ALREADY_LOADED_picture_INTERFACE")) return;
define("ALREADY_LOADED_picture_INTERFACE",1);

// Interface Override
// $finish['method'] = "contact_view();";
// Authwrapper Override - Not working
// $security['method'] = array('users' => "''",'groups' => "''");

// $SQL_APP_DB = '';

// Header Msgs
$header=array();
$header['new']="New picture";
$header['edit']="Edit picture";
$header['remove']="Remove picture";
$header['browse']="Browse pictures";
$header['ins']="Browse pictures";
$header['upd']="Browse pictures";
$header['del']="Browse pictures";
$header['search']="Search pictures";
$header['search_form']="Search pictures";
$header=array();

function getpictureformfields($form,$row,$prepend='',$full=1) {
  global $filename;
  $form->setgroup(array('new','edit','search','view','mass','editac'));
  // Netscape 4.x Bug Hack (ns returns ' ', on <input hidnum name> (no val))
  if (isset($row['pictureid'])) {
    $form->addcontrol('HIDNUM',$prepend.'pictureid',$row['pictureid']);
  }
//  print_r($row);
  $form->setgroup(array('display'));
  $form->addcontrol('NUMBER',$prepend.'pictureid',$row['pictureid']);
  $form->setgroup(array('search','display','view','mass'));
  $form->addcontrol('NUMBER',$prepend.'width',$row['width'],'Width:','',4);
  $form->addcontrol('NUMBER',$prepend.'height',$row['height'],'Height:','',4);
#  $form->setgroup(array('new','edit'));
  $form->addcontrol('HIDNUM',$prepend.'userid',$row['userid']);
  $form->addcontrol('DATETIME',$prepend.'start',$row['start'],'Start:');
  $form->addcontrol('TEXT',$prepend.'stop',$row['stop'],'Stop:');
$form->setgroup(array('new','edit','search','display','view','mass','editac'));
  $form->addcontrol('TEXT',$prepend.'title',$row['title'],'Title:','',128);
$form->setgroup(array('new','edit','search','display','view','mass'));
  $form->addcontrol('TEXT',$prepend.'name',$row['name'],'Name:','',128);
$form->addcontrol('TEXT',$prepend.'email',$row['email'],'Email:','',128);
$form->addcontrol('TEXT',$prepend.'homepage',$row['homepage'],'Homepage:','',128);
  $form->setgroup(array('new','edit','search','display','view','mass','editac'));
$form->addcontrol('HTMLEDIT',$prepend.'authorcomments',$row['authorcomments'],'Comments:','',' ROWS=5 COLS=60');
$form->addcontrol('checkbox',$prepend.'gallery',$row['gallery'],'Include in your gallery?:');
$form->addcontrol('CHECKBOX',$prepend.'allowcontinue',$row['allowcontinue'],'Allow others to continue picture:');
$form->addcontrol('TEXT',$prepend.'contpass',$row['contpass'],'Password to Continue(optional, leave blank so that anyone can continue):');
$form->addcontrol('CHECKBOX',$prepend.'allowanim',$row['allowanim'],'Allow others to view animation:');
  $form->setgroup(array('new','edit','search','display','view','mass'));
$form->addcontrol('CHECKBOX',$prepend.'anonymous',$row['anonymous'],'Post Anonymously?');
  $form->setgroup(array('new','edit','search','display','view','mass','editac'));
//global $myauth;
//if ($myauth['username']!='anonymous') {
  $form->addcontrol('CHECKBOX','notfinished',0,'Not Finished:','',0,0);
  $form->addcontrol('HTML','','NOTE: to use this, you must be LOGGED IN or
you will not be able to make the picture public.');
//}
//  echo $form->debugform();
if (useringroup(array('administrator'))) {
  $form->setgroup(array('display'));
  $form->addcontrol('html',$prepend.'ipaddress',$row['ipaddress']);
}
  $form->setgroup(array('new','edit','search','display','view','mass','editac'));
  return $form;
}

function picturetopmethods() {
#global $filename;
# if (useringroup(array('admin'))) {
#echo ' | <A HREF="'.geturl($filename.'?obj=picture&action=new').'">Add new picture</A>';
#echo '<br>';
# }
}

function getpictureformmethods($form) {
/*
  global $pickrec,$ses;
  $sid=getauthses();
  if (!isset($pickrec)) {
  $pickrec=$ses->get_var($sid,'picture_pickrec');
  } else {
  $ses->set_var($sid,'picture_pickrec',$pickrec);
  }
#  $form->addmethod($filename . '?obj=picture&action=edit&id=', 'edit picture', 'pictureid',0);
#  $form->addmethod($filename . '?obj=picture&action=remove&id=', 'remove picture', 'pictureid',0);
# }
  if ($pickrec) {
    $form->addmethod($filename . '?obj=picture&action=return&id=', 'select', 'pictureid',3);
  }
*/
  return $form;
}

function getpictureform($pictureid,$action,$name,$params="",$cache="") {
  global $conn,$SYND,$filename,$NeuroOekakiUserid;
  if (empty($pictureid)) {
    # Defaults
    // NEVER USED
    $row['int']=0; #$row['userid']=$NeuroOekakiUserid;
    $row['varchar']='';
    $row['date']=date('Y-m-d');
  } else {
    if ($cache == "") {
      $sql="select * from pictures where pictureid=$pictureid";
      $result=sqlexec($sql,$conn,0);
      $row=sqlgetrow($result);
    } else {
      $row=$cache;
    }
  }
  $form=new form(geturl("$filename?obj=picture&id=" . $pictureid . "&action=" .$action . $params) ,"POST",1,1,1);
  if (empty($action)) { $full=0; } else { $full=1; }
  $form=getpictureformfields($form,$row,'',$full);
  if (!$full) {
    $form=getpictureformmethods($form);
  }
  $form->conn=$conn;
  // End
  $form->addcontrol("SUBMIT","submit",$name);
  return $form;
}

function picture_return($id) {
global $DEBUG_LEVEL,$ses;
    if (($DEBUG_LEVEL & 16) == 16) {
      $name="formdata_pictureid";
    } else {
      $name='pictureid';
    }
    $sid=getauthses();
    $ses->clear_var($sid,'picture_pickrec');
?>
<Script Language="JavaScript">
<!--
// Forget everything we are doing
// and close this window.
  window.opener.<? echo $name; ?>_ItemInEdit.value = <? echo $id?>;
  opener.focus();
  window.close();
//-->
</Script>
<?
}

function picture_debug() {
  $form=getpictureform(0,'','');
  $form->debugform();
}

function picture_del($pid="") {
  // Put all relationships here
  global $ses,$auth_sid,$reason,$REMOTE_ADDR,$noreason;
  if (!$noreason) {
  $reason=trim($reason);
  if (empty($reason)) {
    echo "<center><h2>HAHAHAHAHHAHAH, yea right, deletion without a
reason, you make Neuro LAFFF!</h2></center>\n";
    include "appshutdown.php3";
    exit;
  }
  if (strlen($reason)<16) {
    echo "<Center><h2>Your reason isn't good enough (how about explaining
more)</h2></center><br>\n";
    include "appshutdown.php3";
    exit;
  }
  }
  $id=(int)$ses->get_var($auth_sid,'picture_remove_id');
  $fp=fopen("delete.log","a");
  fputs($fp,"$REMOTE_ADDR - Deleting $id because $reason\n");
  fclose($fp);
#  echo "Deleteing [$id]<br>\n";
  sqlexec("delete from pictures where pictureid=$id");
  sqlexec("delete from comments where pictureid=$id");
  sqlexec("update pictures set originalid=0 where originalid=$id");
  log_transac("picture","remove",$id,"");
}

function picture_new($id=0, $params="") {
  $form=getpictureform(0,'ins','Add picture',$params);
  echo $form->generate("edit",array('new'));
}

function picture_upd($pid) {
  global $filename;
  $name=httpform_get("name");
if (!useringroup(array('administrator'))) {
  if (eregi('pink',$name)) {
    $name=eregi_replace('pink','salmon',$name);
    httpform_set('name',$name);
  }
}
  $form=getpictureform(0,'','');
  $check=$form->check_results(array('edit'));
  if (is_array($check)) {
    $ok=1;
    while(list($key,$val)=each($check)) {
            if ($val != "") {  echo $val . ' is not a valid value<br>'; $ok=0; }
    }
    if (!$ok) { exit; }
  }
  global $ses,$auth_sid;
  $id=(int)$ses->get_var($auth_sid,'picture_edit_id');
  $form->update_table("pictures","pictureid='$id'",array('edit'));
  log_transac("picture","edit",$id,"");
}

function picture_browse() {
  //global $SYND;
  //picture_display(" where syndicateid=$SYND");
  global $ses;
  $sid=getauthses();
if (useringroup(array('administrator'))) {
  $sql="select * from pictures where stop!='0000-00-00' and flood=0 order by stop desc";
} else {
  $sql="select * from pictures where stop!='0000-00-00' and notfinished=0 and flood=0 order by stop desc";
}
#  echo "<!-- saaving [$sql] in [$sid] -->\n";
  $ses->set_var($sid,'picture_query',$sql);
  picture_display();
}

function picture_pagnav($start,$ttlrow) {
global $filename,$rpp,$action,$id,$obj;
echo '<p><center>';
  $obj='picture';
  if ($rpp == 0) { return; }
  if ($ttlrow<$rpp) { return; }
  $back = $start-$rpp; if ($back < 0) { $back=0; }
  $next = $start+$rpp;
  $action="display";
  $id=0;
#  echo "obj[$obj]act[$action]<br>\n";
#  echo "begin[0]start[$start]ttlrow[$ttlrow]<br>\n";
#  echo "back[$back]next[$next]<br>\n";
  if ($start == 0 ) {
    echo '<a href="'.geturl($filename.'?obj='.$obj.'&start='.$next.'&id='.$id.'&action='.$action). '">Next '.$rpp.'</A> | ';
    echo '<a href="'.geturl($filename.'?obj='.$obj.'&start='.($ttlrow-$rpp).'&id='.$id.'&action='.$action) . '">End</A>';
  } elseif ( $ttlrow < $next )  {
    echo '<a href="'.geturl($filename.'?obj='.$obj.'&start=0'.'&id='.$id.'&action='.$action) . '">Beginning</A> | ';
    echo '<a
href="'.geturl($filename.'?obj='.$obj.'&start='.$back.'&id='.$id.'&action='.$action)
. '">Prev '.$rpp.'</A>';
  } else {
    echo '<a href="'.geturl($filename.'?obj='.$obj.'&start=0'.'&id='.$id.'&action='.$action) . '">Beginning</A> | ';
    echo '<a href="'.geturl($filename.'?obj='.$obj.'&start=' .
$back.'&id='.$id.'&action='.$action) . '">Prev '.$rpp.'</A> | <a
href="'.geturl($filename . '?obj='.$obj.'&start=' .
$next.'&id='.$id.'&action='.$action).'">Next '.$rpp.'</A> | ';
    echo '<a href="'.geturl($filename.'?obj='.$obj.'&start='.($ttlrow-$rpp).'&id='.$id.'&action='.$action) . '">End</A>';
  }
echo '</center><br>';
}

function picture_display($result=0) {
  global $filename,$conn,$start,$rpp,$action,$start,$ses,$sortby;
#  echo "sortby[$sortby]<br>\n";
  $sid=getauthses();
//  $testname=httpform_get('name');
  if (empty($start)) { $start = 0; }
  if ($result==0) {
    $sql=$ses->get_var($sid,'picture_query');
#  echo "<!-- loading [$sql] in [$sid] -->\n";
    #echo "Found Query [$sql] [$sid]<br>\n";
    if (empty($sql)) {
      $sql="select * from pictures";
      $ses->set_var($sid,'picture_query',$sql);
    }
#    echo "<!-- sort by [$sortby] -->\n";
    if ($sortby) {
##      echo "<!-- SQL[$sql] [$sid] -->\n";
      if (eregi('order[[:space:]]+by',$sql)) {
        # be careful of limit and order by
//        if (useringroup(array('administrator'))) echo "sortby[$sortby]<Br>\n";
	$sql=substr($sql, 0, strpos($sql,'order by'))." order by $sortby";
//        if (useringroup(array('administrator'))) echo "sortby[$sortby]<Br>\n";
      }
    }
#   echo "<!-- SQL[$sql] -->\n";
// What's wrong with Loop done? paging
    $loopdone=1;
// ah, this:
    $cntsql=eregi_replace('^select.*from','select count(*) from',$sql);
//    $cntsql=substr($sql, 0, strpos($cntsql,'order by'));
// was commented out, why?
// don't sort a count! (in case of order by mxts)
    if (eregi('order by',$sql)) {
      $cntsql=substr($cntsql, 0, strpos(strtolower($cntsql),'order by'));
    }
/*    if (useringroup(array('administrator'))) {
      echo "cnt[$cntsql] sql[$sql]<br>\n";
    } */
#    echo "<!-- cnt[$cntsql] -->\n";
    $result=sqlexec($cntsql,$conn);
    list($cnt)=sqlgetrow($result);
#    echo "rpp[$rpp] start[$start]<Br>\n";
    if ($start) { $p1=$start; $p2=$rpp; } else { $p1=$rpp; $p2=''; }
    $result=sqlexec($sql,$conn,0,$p1,$p2);
#    echo getsqlq();
#    $result=sqlexec($sql,$conn,0);
  }
  if (!isset($pickrec)) { $pickrec=0; }
  if ($loopdone) {
    $ttlrow=$cnt;
  } else {
    $ttlrow=sqlgetnumrows($result);
  }
  picture_pagnav($start,$ttlrow);
#  picture_search_form();
  picturetopmethods();
global $glob_layout,$glob_anon,$glob_header,$glob_footer;
global $myauth;
#  echo '<table border=3><tr>';
#  $form=getpictureform(0,'','');
  # aligns = 1 top/left, 2 center, 3 bot/right
  # showfields($groups,$link='',$align=0,$valign=0,$colors=array('ffffff','eeeeee'))
#  echo $form->showfields(array('display'),$filename.'?obj=picture&action=display&start=0&sortby=',0,0,array('',''));
#  echo '</tr>';
  $end = $start+$rpp; if ($start == $end) { $end=$ttlrow; }
#start: <start><br>
#  global $strict; $strict=1;
  include_once "interfaces/comment.php3";
#  httpform_set('name','');
#  httpform_set('email','');
  global $pictureid,$myauth;
#  global $starttime; $timer=$starttime;
$seen_data=getuserflagcache();

if(!$loopdone) {
for ($count = 0; $count < $start; $count++) { sqlgetrow($result); }
}
  for ($count = $start; (($count <= $end) && ($row=sqlgetrow($result))); $count++) {
#if (useringroup(array('administrator'))) {
#$diff=get_timer($timer);
#$timer=set_timer();
#echo "<h6>Took [$diff] secs</h6>\n";
#}
#    echo "artist is [".$row['userid']."]<br>\n";
getlayout($row['pictureid'],$row);
$layout=$glob_layout;
$anonlayout=$glob_anon;
echo $glob_header;
    $pictureid=$row['pictureid'];
    $form=new form();
    $form=getpictureformfields($form,$row,'',0);
/*
if (useringroup(array('administrator'))) {
  if ($row['anim']) {
#    echo "<A HREF=\"".geturl($filename.'?obj=picture&action=animate&id='.$row['pictureid'])."\">I'M NOT ANIMATED TO EXPLODE!</A><br>\n";
#    echo "<A HREF=\"".geturl('draw.php3?action=continue&id='.$row['pictureid'])."\">Insert 25› to continue</A><br>\n";
    if ($row['userid']==$myauth['id']) {
#      echo "<A HREF=\"".geturl('draw.php3?action=replace&id='.$row['pictureid'])."\">Insert 25› to finish & replace</A><br>\n";
    }
  }
}
*/
#    echo "Pic is [".$row['pictureid']."]<br>\n";
#    httpform_set('pictureid',$row['pictureid']);
if (!$seen_data[0]['picture'][$row['pictureid']]) {
  if ($myauth['id']) {
  $myauth['id']=(int)$myauth['id'];
  $row['picutreid']=(int)$row['pictureid'];
  $res=sqlexec("replace into app_seen (obj,objid,userid,type) values ('picture',".$row['pictureid'].",".$myauth['id'].",0)");
  }
}

echo $form->proclayout($row['anonymous']?$anonlayout:$layout,'view',array('display'));

// Viewing Own Picture
  if ($row['userid']==$myauth['id']) {
    echo '&nbsp;<A HREF="'.geturl($filename .
'?obj=picture&action=editac&id='.$row['pictureid']).'" class="info">&nbsp;Edit&nbsp;</a>';
    echo '&nbsp;<A HREF="'.geturl($filename .'?obj=picture&action=remove&noreason=1&id='.$row['pictureid']).'" class="info" title="HADOOOOOOKEN!">&nbsp;Delete&nbsp;</a>';
  }

// Admin
if (useringroup(array('administrator'))) {
    echo '&nbsp;<A HREF="'.geturl($filename .'?obj=picture&action=edit&id='.$row['pictureid']).'" class="info2" title="*sigh* Damned kids and their new-fangled toys...">&nbsp;Mod:Edit&nbsp;</a>';
    echo '&nbsp;<A HREF="'.geturl($filename .'?obj=picture&action=remove&id='.$row['pictureid']).'" class="info2" title="HADOOOOOOKEN!">&nbsp;KILL.&nbsp;</a>';
if ($row['anim']) {
    echo "&nbsp;<A HREF=\"".geturl($filename.'?obj=picture&action=animate&id='.$row['pictureid'])."\" class=\"info2\" title=\"EWW, naked is GROSS! >:O\">&nbsp;Animate&nbsp;</a>\n";
if ($row['usespainter']) {
    echo "&nbsp;<A HREF=\"".geturl('draw2.php3?action=continue&id='.$row['pictureid'])."\" class=\"info2\" title=\"Let's DANCING!\">&nbsp;Continue&nbsp;</a>\n";
    //echo "&nbsp;<A HREF=\"".geturl('draw2.php3?action=replace&id='.$row['pictureid'])."\">[Replace]</A><br>\n";
} else {
    echo "&nbsp;<A HREF=\"".geturl('draw.php3?action=continue&id='.$row['pictureid'])."\" class=\"info2\" title=\"Let's DANCING!\">&nbsp;Continue&nbsp;</a>\n";
    //echo "&nbsp;<A HREF=\"".geturl('draw.php3?action=replace&id='.$row['pictureid'])."\">[Replace]</A><br>\n";
}
}
}

    $sql="select * from comments where pictureid=".$row['pictureid']." order by timestamp";
#echo $sql;
    $res2=sqlexec($sql);
#    echo "There are [".sqlgetnumrows($res2)."] [$res2]<br>\n";
#    $ses->set_var($sid,'comment_query',$sql);
    $oldrpp=$rpp; $oldstart=$start;
    $rpp=0; $start=0;
    comment_display($res2);
    $rpp=$oldrpp; $start=$oldstart;
#    comment_search();
/*
    if (($count-1)%2) { $color='ffffff'; } else { $color='eeeeee'; }
    echo "<tr bgcolor=\"#$color\">";
    $form=getpictureformmethods($form);
    echo $form->showdata(array('display'),'','<td>','</td>',1);
    echo "</tr>";
*/
echo $glob_footer;
  }
#  echo '</table>';
  picture_pagnav($start,$ttlrow);
}

// PrePost edit
function picture_edit($id,$params="") {
  picture_view($id);
  $form=getpictureform($id,'upd','Update picture',$params);
  global $ses,$auth_sid;
  $ses->set_var($auth_sid,'picture_edit_id',$id);
#  $form->addcontrol('HIDDEN','id',$id);
/*  $form->control--;
  $form->addcontrol('CHECKBOX','notfinished',0,'Not Finished:');
  $form->addcontrol('submit','','Update picture'); */
  echo $form->generate("edit",array('edit'));
# echo $form->proclayout($picture,'edit');
}

// AC = Author Comments
// Edit after posting of picture
function picture_editac($id,$params="") {
  picture_view($id);
  $form=getpictureform($id,'upd','Update picture',$params);
  global $ses,$auth_sid;
  $ses->set_var($auth_sid,'picture_edit_id',$id);
#  $form->addcontrol('HIDDEN','id',$id);
  echo $form->generate("edit",array('editac'));
# echo $form->proclayout($picture,'edit');
}

function picture_ins() {
  $form=getpictureform(0,'','');
  $check=$form->check_results(array('new'));
  if (is_array($check)) {
    $ok=1;
    while(list($key,$val)=each($check)) {
            if ($val != "") {  echo $val . ' is not a valid value<br>'; $ok=0; }
    }
    if (!$ok) { exit; }
  }
  $id=$form->insert_results('pictures',array('new'));
  log_transac("picture","inserted",$id,"");
  return $id;
}

function picture_remove($id, $params='') {
  global $filename,$noreason;
  $params.="&noreason=$noreason";
  global $ses,$auth_sid;
  $ses->set_var($auth_sid,'picture_remove_id',$id);
  picture_animate($id);
  echo '<br><br><center><b>Are you sure you would like to remove this record?<b><br><br>';
  echo '<table><tr><td>';
  echo '<FORM ACTION="'.geturl($filename.'?obj=picture&action=del'.$params) .  '" METHOD="POST">';
if (!$noreason) {
  echo 'Reason: <INPUT TYPE=text name="reason">';
}
  echo '<INPUT type="submit" value="Yes">';
  echo '</form></td><td>';
  echo '<FORM ACTION="'.geturl($filename.'?obj=picture&action=display'.$params).'" METHOD="POST">';
  echo '<INPUT type="submit" value="No">';
  echo '</form>';
  echo '</td></tr></table></center>';
}

function picture_view($id) {
global $ses,$auth_sid,$rpp;
global $glob_layout,$glob_anon,$glob_header,$glob_footer;
$res=sqlexec("select * from pictures where pictureid=$id");
$row=sqlgetrow($res);
$form=getpictureform($id,'','','',$row);
#echo $form->generate("view",array('view'));
    include_once "interfaces/comment.php3";
$rpp=0;
getlayout($id,$row);
$layout=$glob_layout;
$anonlayout=$glob_anon;
global $myauth;
if ($myauth['id']) {
$myauth['id']=(int)$myauth['id'];
$id=(int)$id;
$res=sqlexec("replace into app_seen (obj,objid,userid,type) values ('picture',$id,".$myauth['id'].",0)");
}
// View Header
echo $glob_header;
if ($row['anonymous']) {
    echo $form->proclayout($anonlayout,'view',array('display'));
} else {
    echo $form->proclayout($layout,'view',array('display'));
}

if (useringroup(array('administrator'))) {
    echo '&nbsp;<A HREF="'.geturl($filename .
'?obj=picture&action=edit&id='.$row['pictureid']).'" class="info2" title="*sigh* Damned kids and their new-fangled toys...">&nbsp;Mod:Edit&nbsp;</a>';
    echo '&nbsp;<A HREF="'.geturl($filename .
'?obj=picture&action=remove&id='.$row['pictureid']).'" class="info2" title="HADOOOOOOKEN!">&nbsp;KILL.&nbsp;</a>';
}
    $sql="select * from comments where pictureid=$id order by timestamp";
    $res2=sqlexec($sql);
    $ses->set_var($auth_sid,'comment_query',$sql);
echo ''; // Before comments
    comment_display($res2);
echo ''; // After comments
echo $form->getmethod('','',0);
echo $glob_footer;

}

function picture_find() {
global $ses;
$ses->set_var(getauthses(),'picture_pickrec',1);
picture_search_form();
}

function picture_search_form() {
	$form=getpictureform(0,'search','Search');
#	$form->addcontrol('checkbox','strict',0,'Strict:');
	echo $form->generate("edit",array('search'));
}

function picture_search() {
global $rpp,$strict,$ses,$yourhack;
#global $stop; echo "stop[$stop]<Br>\n";
if (empty($strict)) { $strict=0; }
	$form=getpictureform(0,'','');
        $form->addcontrol('text','originalid');
//echo "[$yourhack] [".useringroup(array('administrator'))."]<br>\n";
if (($yourhack==1) || (useringroup(array('administrator')))) {
//        echo "Show all<br>\n";
//        $form->debugform();
	$result=$form->get_search_results('pictures',array('search'),'
and stop!="0000-00-00" and anonymous=0 and flood=0 order by
stop',$strict);
} else {
//        echo "Hiding<br>\n";
	$result=$form->get_search_results('pictures',array('search'),'
and stop!="0000-00-00" and notfinished=0 and flood=0 and anonymous=0 order
by stop',$strict);
}
// don't need to rpp 0 if searching pictures since there is probably a lot
// esp since picture_query
//	$oldrpp=$rpp; $rpp=0;
        $sql=getsqlq();
	$ses->set_var(getauthses(),'picture_query',$sql);
	picture_display($result);
//	$rpp=$oldrpp;
}

function picture_listartist() {
global $field,$starttime;
if (useringroup(array('administrator'))) {
$res=sqlexec("select name, count(*) as cnt from pictures where
stop!='0000-00-00' and flood=0 and notfinished=0 and anonymous=0
group by name
order by cnt desc");
} else {
$res=sqlexec("select name, count(*) as cnt from pictures where
stop!='0000-00-00' and anonymous=0 and flood=0 group by name order
by name");
}
//echo "diff[".get_timer($starttime)."]<br>\n";
?><br><center>
<?
for($c=65; $c<91; $c++) {
$char[chr($c)]="<A HREF=\"#".strtolower(chr($c))."\">".chr($c)."</A>";
}
echo join(' | ',$char);
//echo "diff[".get_timer($starttime)."]<br>\n";
?>
</center>
<?
?><br><br><table align="center" border="0" cellpadding="0" cellspacing="0"
border="0"
width="550" bgcolor="#A82800"><tr>
<td><table width="550" border="0"
cellpadding="2" cellspacing="1">
<tr><th bgcolor="#ffffff"><font
style="font-size:10pt;">Name</font></th><th bgcolor="#ffffff"><font
style="font-size:10pt;">Pictures</font></th><th
bgcolor="ffffff"><font style="font-size:10pt;">Favorites</font></th></tr>
<?
$seen_data=getuserflagcache();
while($row=sqlgetrow($res)) {
//echo "diffbl[".get_timer($starttime)."]<br>\n";
if ($old!=strtolower(substr($row['name'],0,1))) {
  $old=strtolower(substr($row['name'],0,1));
  $anch="<A name=\"".urlencode(htmlentities($old))."\">";
} else {
  $anch="";
}
echo '<tr><td bgcolor="#ffffff">'.$anch.'<A
HREF="'.geturl('interface.php3?obj=picture&action=search&strict=1&name='.$row['name']).'">';
//echo "diffml[".get_timer($starttime)."]<br>\n";
if (!$row['name']) { $row['name']="(none)"; }
$res2=sqlexec("select userid from auth_users where
name='".addslashes($row['name'])."'");
list($uid)=sqlgetrow($res2);
if ($seen_data[1]['user'][$uid]) {
$type='remove'; $symbol='-'; $val=0;
} else {
$type='add'; $symbol='+'; $val=1;
}
echo $row['name'].'</a></td><td
bgcolor="#ffffff">'.$row['cnt'].'</td><td bgcolor="ffffff" align=center><a
href="'.geturl('interface.php3?obj=auth_user&action=set&table=user&type=1&id='.$uid.'&val='.$val).'"
class="info">&nbsp;'.$symbol.'&nbsp;</a></td></tr>';
//echo "diffal[".get_timer($starttime)."]<br>\n";
}
echo '</table></td></tr></table>';
//echo "diff[".get_timer($starttime)."]<br>\n";
}

function picture_listdate() {
$res=sqlexec("select date_format(stop,'%Y-%m-%d') as stop, count(*) as cnt
from pictures where stop!='0000-00-00' and flood=0 and notfinished=0
group by stop order by stop");
while(list($key,$cnt)=sqlgetrow($res)) {
  $pic[$key]=$cnt;
  $db[$key]=1;
}
$res=sqlexec("select date_format(timestamp,'%Y-%m-%d') as stop, count(*) as cnt
from comments group by stop order by timestamp");
while(list($key,$cnt)=sqlgetrow($res)) {
  $com[$key]=$cnt;
  $db[$key]=1;
}
ksort($db);
?><br><br><table align="center" width="400" border="0" cellpadding="0"
cellspacing="0"
bgcolor="#A82800">
<tr>
  <td>
  <table width="400" cellpadding="2" cellspacing="1" border="0">
<tr>
<th bgcolor="#ffffff"><font style="font-size:10pt;">Date</font></th>
<th bgcolor="#ffffff"><font style="font-size:10pt;">Pics</font></th>
<th bgcolor="#ffffff"><font style="font-size:10pt;">Comments</font></th>
</tr>
<?
foreach($db as $key=>$cnt) {
  echo '<tr><td bgcolor="#ffffff">';
  $dkey=$key;
  if (empty($dkey)) { $dkey="(none)"; }
  if ($dkey=='0000-00-00') { $dkey="(none)"; }
  echo $dkey.'</a></td>';
  echo '<td bgcolor="#ffffff">';
  echo '<A HREF="'.geturl('interface.php3?obj=picture&action=search&stop='.$row['stop']).'">';
  echo $pic[$key].'</a></td>';
  echo '<td bgcolor="#ffffff">'.$com[$key].'</td>';
  echo '</tr>';
}
echo '</table></td></tr></table>';
}

function picture_mostcomments() {
$res=sqlexec("select c.pictureid, p.title, p.stop, p.name, count(*) as cnt
from
comments c, pictures p where c.pictureid=p.pictureid group by
pictureid order by cnt desc limit 100");
?><br><br><table align="center" width="400" border="0" cellpadding="0"
cellspacing="0"
bgcolor="#A82800">
<tr>
  <td>
  <table width="400" cellpadding="2" cellspacing="1" border="0">
<tr>
<th bgcolor="#ffffff"><font style="font-size:10pt;">Title</font></th>
<th bgcolor="#ffffff"><font style="font-size:10pt;">By</font></th>
<th bgcolor="#ffffff"><font style="font-size:10pt;">Date</font></th>
<th bgcolor="#ffffff"><font style="font-size:10pt;">Comments</font></th>
</tr>
<?
while($row=sqlgetrow($res)) {
echo '<tr><td bgcolor="#ffffff"><A
HREF="'.geturl('interface.php3?obj=picture&action=view&id='.$row['pictureid']).'">';
if (empty($row['title'])) { $row['title']="(none)"; }
echo $row['title'].'</a></td>
<td bgcolor="#ffffff"><A
HREF="'.geturl('interface.php3?obj=picture&action=search&name='.$row['name']).'">'.$row['name'].'</A></td>
<td bgcolor="#ffffff">'.$row['stop'].'</td>
<td bgcolor="#ffffff">'.$row['cnt'].'</td>
</tr>';
}
echo '</table></td></tr></table>';
}

function picture_lastcomment() {
global $auth_sid,$ses;
global $sort;
$sql="select p.*,max(timestamp) as mxts from pictures p, comments c
where p.pictureid=c.pictureid and p.flood=0 and p.notfinished=0 group by
p.pictureid order by
mxts $sort";
$ses->set_var($auth_sid,'picture_query',$sql);
$res=sqlexec($sql);
#echo "aut_sid is[$auth_sid] [$sort]<br>\n";
picture_display($res);
}

function picture_your() {
global $NeuroOekakiUserid;
?><br><br><center><b>
<?
$res=sqlexec("select * from pictures where userid=$NeuroOekakiUserid
and stop !='0000-00-00'");
$cnt=sqlgetnumrows($res);
list($name,$email,$hp)=getnfo($NeuroOekakiUserid);
echo $name;
?>'s pictures:</b> [<? echo $cnt; ?>]<br>
<table align="center" width="400" border="0" bgcolor="#A82800" cellpadding="0"cellspacing="0">
<tr>
<td><table width="400" cellpadding="2" cellspacing="1" border="0">
<tr><th bgcolor="#ffffff"><font
style="font-size:10pt;">Title</font></th>
<th bgcolor="#ffffff"><font style="font-size:10pt;">Finished</font></th>
<th bgcolor="#ffffff"><font
style="font-size:10pt;">Comments</font></th><th
bgcolor="#ffffff"><font style="font-size:10pt;">Last
Comment</font></th>
</tr> <? while($row=sqlgetrow($res)) {
$res2=sqlexec("select pictureid,count(*),max(timestamp) from comments
where pictureid=".$row['pictureid']." group by pictureid");
list($pid,$cnt,$mxts)=sqlgetrow($res2);
$cnt=(int)$cnt;
echo
'<tr><td bgcolor="#ffffff"><A
HREF="'.geturl('interface.php3?obj=picture&action=editac&id='.$row['pictureid']).'">-
'.$row['title'].'</A></td><td
bgcolor="#ffffff">'.($row['notfinished']?'Not Yet':'Done').'</td><td
bgcolor="#ffffff">'.$cnt.'</td><td bgcolor="#ffffff">'.$mxts.'</td></tr>';
} ?></table></td></tr></table></center>
<?
httpform_set('userid',$NeuroOekakiUserid);
global $yourhack;
$yourhack=1;
picture_search();
}

function picture_animate($pid) {
$res=sqlexec("select * from pictures where pictureid=$pid");
$row=sqlgetrow($res);
?>
<script language="JavaScript">
<!--

function setspeed(reference){
	document.paintbbs.speed = reference.value;
}

function setspeed2(reference){
 var pch=document.pch;
 pch.setSpeed(reference.value);
}

//-->
</script>
<center>
<table width="1" border="0" cellspacing="10" cellpadding="0">
<tr>
<td>
<img src="data/<? echo $row['pictureid']; ?>.png">
</td>
<td width="1">
<? if ($row['usespainter']) {
$func='setspeed2';
?>
<applet
 name="pch"
 code="pch2.PCHViewer.class"
 codebase="./";
 archive="viewer/PCHViewer.jar"
 width="<? echo $row['width']; ?>"
 height="<? echo $row['height']; ?>"
>
<param name="speed" value="-1">
<param name="pch_file" value="data/<? echo $row['pictureid']; ?>.pch">

<param name="buffer_progress" value="false">
<param name="buffer_canvas" value="false">

<param name="res.zip" value="viewer/res/res.zip">
<param name="tt.zip" value="viewer/res/tt.zip"

<param name=tt_size value=31>
<param name=image_width value="<?=$row['width'] ?>">
<param name=image_height value="<?=$row['height'] ?>">
<param name="run" value="false">
</applet>
<? } else {
$func='setspeed';
?>
<applet code="pbbs.PaintBBS.class" archive="PaintBBS.jar" name="paintbbs"
width="<? echo $row['width']; ?>" height="<? echo $row['height']; ?>">
<param name="viewer" value="true">
<param name="speed" value="10">
<param name="pch_file" value="<? echo "data/".$row['pictureid'].".pch"; ?>">
</applet>
<? } ?>
</center>

</td>
<td width="1" valign="top">
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="right"><b>Pixel By Pixel</b> </td>
<td><input type="radio" name="speed" value="1000" onclick="<?=$func?>(this)"></td>
</tr>
<tr>
<td align="right"><b>Slow-mo</b> </td>
<td><input type="radio" name="speed" value="100" onclick="<?=$func?>(this)"></td>
</tr>
<tr>
<td align="right"><b>medium</b> </td>
<td><input type="radio" name="speed" value="10" checked onclick="<?=$func?>(this)"></td>
</tr>
<tr>
<td align="right"><b>med-fast</b> </td>
<td><input type="radio" name="speed" value="5" checked onclick="<?=$func?>(this)"></td>
</tr>
<tr>
<td align="right"><b>fast</b> </td>
<td><input type="radio" name="speed" value="1" onclick="<?=$func?>(this)"></td>
</tr>
</table>
</td>
</tr>
</table>
</center>
<?
}

function picture_showcont($orgid) {
picture_view($orgid);
httpform_set('originalid',$orgid);
picture_search();
}

function picture_kwsearch() {
global $rpp,$strict,$ses;
$keywords=stripslashes(httpform_get('keywords'));
$add=where_sql($keywords, array('p.title','p.authorcomments','c.comment'),
&$kwwords);
$sql="select distinct p.* from pictures p, comments c where
p.flood=0 and p.notfinished=0 and p.pictureid=c.pictureid and $add";
/*
if (useringroup(array('administrator'))) {
echo "kw[$keywords]<br>\n";
  echo "DBG[$sql]<br>\n";
}*/
//	$oldrpp=$rpp; $rpp=0;
	$ses->set_var(getauthses(),'picture_query',$sql);
	picture_display($result);
//	$rpp=$oldrpp;
}

function where_sql($search, $fields, &$words) {

  if (!isset($search)) {
    $search = '';
  }

  $sql = ' (('; // vim indent fix: ))

  $search = eregi_replace(' and | or ',' ',$search);
  $search = ereg_replace('  ',' ',$search);
  $search = trim($search);
  $searchtext = $search;

  if(!get_magic_quotes_gpc()) {
    $search = addslashes($search);
  } else {
    $searchtext=stripslashes($search);
  }
  $searchtext = htmlentities($searchtext);

  if($search!="") {
    $toknum = 0;
    $tokens = array();
    if($match != 3) {

      $inquotedstring = 0;
      $params = split(" ", $search);
      $tokens[$toknum] = "";

      for($i=0; $i<count($params); $i++) {

        if(!isset($tokens[$toknum])) {
          $tokens[$toknum] = "";
        }
        $param = $params[$i];

        if(ereg('^"', $param) || ereg('^[+-]"', $param)) {
          $inquotedstring = 1;
        }

        if($inquotedstring == 1) {
          $tokens[$toknum] .= ereg_replace('"', "", $param) . " ";
        } else {
          $tokens[$toknum++] = $param;
        }

        if(ereg('"$', $param)) {
          $inquotedstring = 0;
          $tokens[$toknum] = chop($tokens[$toknum]);

          if($tokens[$toknum]=="") {
            unset($tokens[$toknum]);
          } else {
            $toknum++;
          }
        }
      }

    } else { // match == 3
      $tokens[$toknum] = ereg_replace('"', "", chop($search));
    }

    if(count($tokens)==0)  {
      unset($tokens);
    }
  }

  if(@is_array($tokens)) {
    if(isset($x)) {
      list($id,$action,$start_num,$top_id)=explode(",", $x);
      if($action==1)
        $prevtopid=$top_id;
    }

    for($i=0; $i<count($tokens); $i++) {
      for($x=0; $x<count($fields); $x++) {
        $token = ereg_replace(" $", "", $tokens[$i]);
        if(ereg("^\\+", $token)) {
          $token = ereg_replace("^\\+", "", $token);
          $sql .= "$fields[$x] like '%$token%'";
          if($x<count($fields)-1) {
            $sql .= " and ";
          }
        } elseif(ereg("^\\-", $token)) {
          $token = ereg_replace("^\\-", "", $token);
          $sql .= "$fields[$x] not like '%$token%'";
          if($x<count($fields)-1) {
            if($match==1) {
              $sql .= ") and (";
            } else{
              $sql .= ") and (";
            }
          }
        } elseif(trim($token)!="") {

          $sql .= "$fields[$x] like '%$token%'";
          if($x<count($fields)-1) {
            $sql .= " or ";
          }
        }
      }
      if($i<count($tokens)-1) {
        if($match==1) {
          $sql .= ") and (";
        } else {
          $sql .= ") or (";
        }
      } else {
        $sql .= ")";
      }
    }
  }
  $sql .= ')';

  while(list($key,$word)=each($params)) {
    $word=str_replace("+","",$word);
    $word=str_replace("-","",$word);
    $word=str_replace('"',"",$word);
    $words[]=$word;
  }

  return $sql;
}

?>
