<?php
//
//  Comic Comments
//  -------------------
//  - Original Author: Steve H <http://comiccms.com/>
//  - Modified by: Erik L
//  - License: GPL 3 <http://www.gnu.org/copyleft/gpl.html>
//  - Created: April 2009
//  - Updated: March 2011
//
//  Designed for ComicCMS 0.2    <http://comiccms.com/>
//
class pl_comiccomment extends ComicCMS {
    var $id = 'comiccomment';
    var $version = '0.2';
    var $forversion = array('0.2');
    var $template = array('comic');
    
    var $lang = array(
        '_lang'=>'en',
        'en'=>array(
            '_title'=>'Comic Comments',
            '_desc'=>'Comment system to allow guests to comment on your comics',
            '_author'=>'Erik L, with help from Steve H',
			
			'manageuse'=>'Manage recent comments',
			'deletecomment'=>'Delete Comment',
			'prevoffset'=>'Previous {{info}}',
			'nextoffset'=>'Next {{info}}',
			
			'nocomments'=>'No comments to display. Click the section titles below to view info on integrating comments into your site.',
			'recaptchaex'=>'Public comments without CAPTCHA are a fast track to getting flooded with spam. Make sure you install the reCAPTCHA plugin and enable it for comic comments in the Edit Plugin page here.',
			'display'=>'Displaying Comments',
			'displayex'=>'Comic comments integrate into the template system as foreach lists. Paste the following code into your template page anywhere that comic variables are available to get started:',
			'addcomment'=>'Adding Comments',
			'addcommentex'=>'To allow visitors to add comments you must put comment forms on your site pages. You can paste the following code into your template page anywhere comic variables are available. Please note the <strong>{{plugin:recaptcha}}</strong> line, you must only include this if you have the recaptcha plugin and recaptcha enabled in the comment settings.',
            
			'gotourl'=>'URL to send user to on successful comment add',
            'recaptcha'=>'Use the reCAPTCHA service to block out spam comments (requires the reCAPTCHA plugin)',
			'reverse'=>'Display comments in reverse date order',
            'allowguest'=>'Allow guest visitors to leave comments',
			'recaptchauser'=>'Require recaptcha authentication for logged in users',
            
            'delete'=>'Be sure to erase all mention of {{comic_comment}} variables from your templates before deleting.',
			'delcomments'=>'That includes all of your comments!',
			
			
			'commentbyuser'=>'This comment was created by the user: {{info}}',
			'editcomment'=>'Edit Comment',
			'commentedited'=>'Comment Edited',
			'commentdeleted'=>'Comment Deleted',
			
			'tryagain'=>'Add Comment',
			'name'=>'Name',
			'email'=>'Email',
			'post'=>'Comment',
			'submit'=>'Add Comment',
			'website'=>'Website',
			
			'badrecaptcha'=>'Recaptcha verification failed, please try again',
			'badcomicid'=>'Comic ID not recognised',
			'noname'=>'Name was blank. Please log in or input a name',
			'badlogin'=>'To post under that name you must be logged in as {{info}}, please try again',
			'noguest'=>'Sorry, guest commenting is disabled. You must be logged in to comment.',
			'nopost'=>'Comment not long enough, please try again',
			'badorigin' => 'Your referring page seems to be located on another server. This is likely an error, so please check your html.',
           'badpost'=>'Comment contained likely spam content (HTML tags/entities are banned). Please try again if you are NOT a spammer or spambot :)',
           'banhtml' => 'Ban HTML content from posts by guests',
            'logbad' => 'Log banned posts to disk',
        ),
    );
    
    var $settings = array(
        'gotourl'=>'http:///?id={{comic_id}}#comments',
		'allowguest'=>true,
        'recaptcha'=>false,
		'reverse'=>true,
		'recaptchauser'=>false,
	'banhtml'=>false,
	'logbad'=>false,
    );
    
    ////////////////////////////////////////////////////////////
    // Generate default form fields
    ////////////////////////////////////////////////////////////
    function fields($switch,$extra=false) {
        switch ($switch) {
            case 'edit':
                return array(
					'gotourl'=>array('type'=>'text','title'=>$this->lang('gotourl')),
                    'recaptcha'=>array('type'=>'checkbox','title'=>$this->lang('recaptcha')),
					'reverse'=>array('type'=>'checkbox','title'=>$this->lang('reverse')),
					'allowguest'=>array('type'=>'checkbox','title'=>$this->lang('allowguest')),
					'recaptchauser'=>array('type'=>'checkbox','title'=>$this->lang('recaptchauser')),
                 'banhtml'=>array('type'=>'checkbox','title'=> $this->lang('banhtml')), 
                   'logbad'=>array('type'=>'checkbox','title'=> $this->lang('logbad')),
                );
                break;
			
			case 'editcomment':
				$r = array();
				if (!$extra) {
					$r['name'] = array('type'=>'text','title'=>$this->lang('name'));
                    $r['email'] = array('type'=>'text','title'=>$this->lang('email'));
				}
				$r['post'] = array('type'=>'textarea','title'=>$this->lang('post'),'class'=>'resizeTextarea');
                return $r;
                break;
			
			case 'deletecomment':
				return array();
				break;
        }
    }
    
    
    
    ////////////////////////////////////////////////////////////
    // Plugin display pages
    ////////////////////////////////////////////////////////////
    function d_use($admin,$data=false) {
		if (!$this->settings['recaptcha'] && !$this->settings['banhtml'] ) $admin->addwarning($this->lang('recaptchaex'));
		$justlist = false;
		if (setvar($offset,'g','offset')) {
			$justlist = true;
		} else $offset = 0;
        if (!is_numeric($offset)) $offset = 0;
        $offset--;
        if ($offset<0) $offset=0;
		$admin->addline('<div id="accordian" style="width:750px; margin:30px auto;">');
		$admin->addline('  <h2>'.$this->lang('manageuse').'</h2>');
		$admin->addline('  <div class="accordian">');
		$this->db();
		$comments = plaintext($this->db->get('batch','-'.$offset,-15));
		if (parse_dbresult($comments)) {
        	if (isset($comments[$offset])) unset($comments[$offset]);
			
			// Display comments
                $list = new admin_editlist;
                foreach ($comments as $comment) {
		    $cid = $comment['id'];
		    $comicdata = $this->getComic($comment['comicid']);
		    $ttl = '';
		    if (isset($comicdata)) $ttl = substr($comicdata['title'],0,50);
                    $list->add(array(
                        'id'=>($comment['flags']==0)?$cid:-$cid,
                        'url'=>'?p=plugin:edit&amp;plugin='.$this->id.'&amp;page=edit&amp;comment='.$cid,
                        'title'=>'[#'.$comment['comicid'].':'.$ttl.'] '.substr($comment['post'],0,50).(strlen($comment['post'])>50?'...':''),
                        'delete'=>'?p=plugin:edit&amp;plugin='.$this->id.'&amp;page=delete&amp;comment='.$cid,
                        'delete_title'=>$this->lang('deletecomment'),
                    ));
                }
                $admin->addline($list->render());
                
                // Display links
                $prevurl = ($offset>0?'?p=plugin:use&amp;plugin='.$this->id.'&amp;offset=' . (($offset-15)>0?($offset-15):0):false);
                $nexturl = ($comment['isfirst']?false:'?p=plugin:use&amp;plugin='.$this->id.'&amp;offset=' . ($offset+15));
            
                $admin->addline(($prevurl?'<a href="' . $prevurl . '" class="twonav_1">' . $this->lang('prevoffset',15) . '</a>':'<span class="twonav_1">' . $this->lang('prevoffset',0) . '</span>'));
                $admin->addline(($nexturl?'<a href="' . $nexturl . '" class="twonav_2">' . $this->lang('nextoffset',15) . '</a>':'<span class="twonav_2">' . $this->lang('nextoffset',0) . '</span>'));
		} else {
			$admin->addline('    <p>'.$this->lang('nocomments').'</p>');
		}
		$admin->addline('  </div>');
		
		if (!$justlist) {
			$admin->addline('  <h2>'.$this->lang('display').'</h2>');
			$admin->addline('  <div class="accordian">');
			$admin->addline('    <p>'.$this->lang('displayex').'</p>');
			$admin->addline('
<pre style="font-size:10px;">
&lt;div id="comments"&gt;
{{foreach:comic_comment:reverse}}
  &lt;div class="commentpost"&gt;
    {{if:comment_author_email}}&lt;img src="http://www.gravatar.com/avatar/{{comment_author_email:md5}}?s=45" alt="Gravatar" title="Posted by {{comment_author_name}}" class="newsavatar"/&gt;{{endif}}
    &lt;span class="commentdetail"&gt;Posted at {{comment_hour}}:{{comment_minute}}&lt;br /&gt;{{comment_weekday:shortname}} {{comment_day}} {{comment_month:shortname}} {{comment_year}}&lt;br /&gt; by {{comment_author_name}}&lt;/span&gt;
        {{comment_post:rich}}
  &lt;/div&gt;
{{endeach:comic_comment}}
&lt;/div&gt;
</pre>');
			$admin->addline('  </div>');
			
			$admin->addline('  <h2>'.$this->lang('addcomment').'</h2>');
			$admin->addline('  <div class="accordian">');
			$admin->addline('    <p>'.$this->lang('addcommentex').'</p>');
			$admin->addline('
<pre style="font-size:10px;">
{{if:comic_tag:!==closed}}
&lt;form action="http:///admin/?type=action&amp;a=comiccomment&amp;id={{comic_id}}" method="post" class=dottedbox&gt;
  &lt;input type="text" name="name"  tabindex="1" /&gt;&lt;label for="comment_name"&gt;&lt;small&gt;NAME &mdash; &lt;a href="http://gravatar.com"&gt;Get a Gravatar&lt;/a&gt;&lt;/small&gt;&lt;/label&gt; &lt;br /&gt;
  &lt;input type="text" name="email"  tabindex="2" /&gt;&lt;label for="comment_email"&gt;&lt;small&gt;EMAIL &mdash; Required / not published &l;/small&gt;&lt;/label&gt;&lt;br /&gt;
  &lt;input type="text" name="website"  tabindex="3"  /&gt;&lt;label for="comment_websites"&gt;&lt;small&gt;WEBSITE&lt;/small&gt;&lt;/label&gt;&lt;br /&gt;
  &lt;label for="comment_post"&gt;Comment&lt;/label&gt;&lt;br /&gt;
  &lt;textarea name="post"  cols="50" rows="6" tabindex="4" &gt;&lt;/textarea&gt;&lt;br /&gt;
  {{plugin:recaptcha}}
  &lt;input type="submit" value="Add Comment" /&gt;
 &lt;/form&gt;
{{else}}
&lt;h2&gt;&lt;em&gt;This discussion thread is closed &lt;/em&gt;&lt;/h2&gt;
{{endif}}
</pre>');
			$admin->addline('  </div>');
		}
		
		$admin->addline('</div>');
		
		$admin->addjavascript('new Accordion($(\'accordian\').getElements(\'h2\'),$(\'accordian\').getElements(\'div.accordian\'), {
		opacity: 0,
		onActive: function(h) {h.setStyles({\'cursor\':\'default\',\'background-color\':\'#fff\'});},
		onBackground: function(h) {h.setStyles({\'cursor\':\'pointer\',\'background-color\':\'#eef\'});}
	});');
    }
    function d_edit($admin,$data=false) {
		if (setvar($page,'g','page')) {
			switch ($page) {
				case 'edit': return $this->d_editcomment($admin,$data); break;
				case 'delete': return $this->d_deletecomment($admin,$data); break;
			}
		}
		
        $this->settings = ($data?$data:$this->settings);
        $admin->genform($this->fields('edit'),$this->settings);
    }
    function p_edit($admin,$data) {
		if (setvar($page,'g','page')) {
			switch ($page) {
				case 'edit': return $this->p_editcomment($admin,$data); break;
				case 'delete': return $this->p_deletecomment($admin,$data); break;
			}
		}
		
        if (!$admin->readform($data,$this->fields('edit'))) return false;
        
		if ($data['reverse']!=$this->settings['reverse']) {
			// Rebuild templates
			$templatecpu = load_cpu('template');
			$pages = $templatecpu->get_content('{{foreach:comic_comment');
			foreach ($pages as $page) $templatecpu->end_event('edit',$page['fileid'],$page);
		}
		
        $this->settings = $data;
        $this->save();
        return true;
    }
    function d_delete($admin,$data=false) {
        $admin->addwarning($this->lang('delete'));
        $admin->genform(array('fullremove'=>'checkbox',array('type'=>'html','html'=>'<p>'.$this->lang('delcomments').'</p>')),array());
    }
    function p_delete($admin,$data) {
        if (!$admin->readform($data,array('fullremove'=>'checkbox'))) return false;
        
        $this->delete($data['fullremove']);
        return true;
    }
    
	
	
	
	function d_editcomment($admin,$data=false) {
		$this->db();
		if (!setvar($commentid,'g','comment')) return false;
		$comment = $this->db->get($commentid);
		if (!parse_dbresult($comment)) return true;
		
		$admin->newpage('edit','plugin='.$this->id.'&amp;page=edit&amp;comment=' . $commentid);
		
		if ($comment['user']) {
			$user = $admin->cpu('user','get',$comment['user']);
			$admin->addline('<p style="text-align:center; font-weight:bold;">'.$this->lang('commentbyuser',$user['name']).'</p>');
		}
		
		$admin->genform($this->fields('editcomment',$comment['user']),$comment,array('title'=>$this->lang('editcomment')));
	}
	function p_editcomment($admin,$data=false) {
		$this->db();
		if (!setvar($commentid,'g','comment')) return false;
		$comment = $this->db->get($commentid);
		if (!parse_dbresult($comment)) return true;
		
		if (!$admin->readform($data,$this->fields('editcomment',$comment['user']))) return $this->d_editcomment($admin);
		
		$comment['post'] = $data['post'];
		if (!$comment['user']) {
			$comment['name'] = $data['name'];
			$comment['email'] = $data['email'];
		}
		
		$this->db->save($comment,$comment['id']);
		
		$comiccpu = load_cpu('comic');
		$comiccpu->end_event('edit',$comiccpu->get($comment['comicid']));
		
		$admin->addgoodmessage($this->lang('commentedited'));
		
		return true;
	}
	
	
	
	function d_deletecomment($admin,$data=false) {
		$this->db();
		if (!setvar($commentid,'g','comment')) return false;
		$comment = $this->db->get($commentid);
		if (!parse_dbresult($comment)) return true;
		
		$admin->newpage('edit','plugin='.$this->id.'&amp;page=delete&amp;comment=' . $commentid);
		
		if ($comment['user']) $user = plaintext($admin->cpu('user','get',$comment['user']));
		
		$nbbc = load_class('nbbc');
		$admin->genform($this->fields('deletecomment'),$comment,array('title'=>$this->lang('deletecomment'),
		'html'=>$nbbc->richtext($comment['post']).'<p style="font-weight:bold;">~ '.($comment['user']?$user['name']:plaintext($comment['name'])).'</p>'));
	}
	function p_deletecomment($admin,$data=false) {
		$this->db();
		if (!setvar($commentid,'g','comment')) return false;
		$comment = $this->db->get($commentid);
		if (!parse_dbresult($comment)) return true;
		
		if (!$admin->readform($data,$this->fields('deletecomment'))) return $this->d_deletecomment($admin);
		
		$this->db->delete($comment['id']);
		$this->removefromindex($comment['id']);	
		$comiccpu = load_cpu('comic');
		$comiccpu->end_event('edit',$comiccpu->get($comment['comicid']));
		
		$admin->addgoodmessage($this->lang('commentdeleted'));
		
		return true;
	}
	

    
    
    ////////////////////////////////////////////////////////////
    // Template merge functions
    ////////////////////////////////////////////////////////////
    function comic_trigger($tpl) {
        if (strpos($tpl,'{{foreach:comic_comment')!==false) return true;
		if (strpos($tpl,'{{comic_commentnum')!==false) return true;
		if (strpos($tpl,'{{if:comic_commentnum')!==false) return true;
        return false;
    }
    function comic_extra($comic) {
        $comic['comment'] = array();
        if ($comic['id']) {
            $this->db();
	    $const = $this->loadconstants();
	    if (!isset($const) || !in_array('comicid_idx',$const) ) {
		$idx = $this->indexon(0,true);
		if (isset($idx)) {
			$this->saveconstants(array('comicid_idx'=> $idx));
		}
	    } else {
		$idx=$const['comicid_idx'];
	    }

            $comments = $this->search($comic['id'],'comicid',false,$idx);
            if (parse_dbresult($comments)) {
                foreach ($comments as $k => $comment) {
                    $user = false;
                    if ($comment['user']!=0) {
                        $cpu = load_cpu('user');
                        if ($user = $cpu->get($comment['user'])) $comment['author'] = $user;
                    }
                    if (!$user) {
                        $comment['author'] = array(
                            'name'=>$comment['name'],
                            'email'=>$comment['email'],
                        );
                    }
		    $ts = $comment['timestamp'];
                    $comic['comment'][] = array(
			'year'=> date('Y',$ts),
			'month'=> date('m',$ts),
			'day'=> date('d',$ts),
			'weekday'=> date('w',$ts),
			'hour'=> date('H',$ts),
			'minute'=> date('i',$ts),
                        'post'=>$comment['post'],
                        'author'=>$comment['author'],
			'flags'=>$comment['flags'],
			'comictitle'=>$comment['comictitle'],
			'website'=>$comment['website'],
                    );
                }
            }
        }
		if (!$this->settings['reverse']) $comic['comment'] = array_reverse($comic['comment']);
        $comic['commentnum'] = count($comic['comment']);
        return $comic;
    }
    
    
    
    ////////////////////////////////////////////////////////////
    // Action functions
    ////////////////////////////////////////////////////////////
    function a_comiccomment($input) {
		// First initiate the comment
		$comment = array(
			'comicid'=>(int) $input['id'],
			'timestamp'=>date('U'),
			'post'=>$_POST['post'],
			'comictitle'=>$_POST['comictitle'],
			'website'=>$_POST['website'],
		);
		
		// Then check comic
		$comiccpu = load_cpu('comic');
		if ( (!$comment['comicid']) || (!$comic = $comiccpu->get($comment['comicid'])) ) return $this->error('badcomicid');
		
		// Then check for users
		$usercpu = load_cpu('user');
		if ( (!$_POST['name']) || ($usercpu->search($_POST['name'],'name')) ) {
			$authcpu = load_cpu('auth');
			if ( ($authcpu->get('loggedin')) && ( (!$_POST['name']) || (strtolower($_POST['name'])==strtolower($authcpu->get('user','name'))) ) ) {
				$comment['user'] = $authcpu->get('user','id');
				$comment['name'] = '';
				$comment['email'] = '';
			} else return $this->error('badlogin',$_POST['name']);
		} else {
			// Guest
			if (!$this->settings['allowguest']) return $this->error('noguest');
			$comment['user'] = 0;
			$comment['name'] = $_POST['name'];
			$comment['email'] = $_POST['email'];
		}
		if ( (strlen($_SERVER['HTTP_REFERER'])) && (stristr($_SERVER['HTTP_REFERER'],$_SERVER['SERVER_NAME'])=== FALSE) ) return $this->error('badorigin');
		// Now check the captcha
        if ( ($this->settings['recaptcha']) && ( ($this->settings['recaptchauser']) || ($comment['user']==0) ) ) {
			$recaptcha = load_plugin('recaptcha');
			if (!$recaptcha->validate($_POST['recaptcha_challenge_field'],$_POST['recaptcha_response_field'])) {
				return $this->error('badrecaptcha',$recaptcha->error);
			}
		}
           if (($comment['user']==0) && ($this->settings['banhtml'])) {
                $p = str_replace(array("\r\n", "\n", "\r","\t"," "),array(),$comment['post']);
               if (((strlen(strip_tags($p)) < strlen($p)) || (strpos($p, "&") !== false) || (strpos($p, "http:")!== false) )) {
                if ($this->settings['logbad']) {
                $handle = fopen("BADLOG.txt", "a");
               $s='';
               foreach ($comment as $k => $v) {
                         $s = $s . "\t" . $k."=>".rawurlencode($v);
                         }
               $ts = date("D M j G:i:s T Y");
               fwrite($handle,($ts."\t".$_SERVER['REMOTE_ADDR'].":".$_SERVER['REMOTE_PORT'].$s."\n"));
               fclose($handle);
                  }
               return $this->error('badpost');
               }
       }


		// Then check/add the comment
		if (!$comment['post']) return $this->error('nopost');
		$this->db();
		$newid = $this->db->save($comment);
		
		//manually update the index
		$this->addtoindex($newid,$comment['comicid']);
		// Refresh Cache
		$comiccpu->end_event('edit',$comic);
		
		// And then go somewhere else...
		header('Location: '.str_replace(array("\n","\r",'{{comic_id}}','http:///'),array('','',$comment['comicid'],get_config('baseurl')),$this->settings['gotourl']));
    }
	function error($errcode,$extra=false) {
		if ( ($errcode=='badlogin') && (!$extra) ) $errcode = 'noname';
		echo '<strong style="display:block; font-size:20px; text-align:center; color:#b00; padding:2em 1em; background-color:#fdc;">'.$this->lang($errcode,$extra).'</strong>';
		
		$comicid = (int) $_GET['id'];
		if ($comicid) {
			$name = plaintext($_POST['name']);
			$email = plaintext($_POST['email']);
			$post = plaintext($_POST['post']);
			$website = plaintext($_POST['website']);

			echo '<h2>'.$this->lang('tryagain').'</h2>';
			echo '<form action="?type=action&amp;a='.$this->id.'&amp;id='.$comicid.'" method="post">';
			echo '<label for="comment_name">'.$this->lang('name').'</label><input type="text" name="name" id="comment_name" value="'.$name.'" /><br />';
			echo '<label for="comment_email">'.$this->lang('email').'</label><input type="text" name="email" id="comment_email" value="'.$email.'" /><br />';
			echo '<label for="comment_email">'.$this->lang('website').'</label><input type="text" name="website" id="comment_website" value="'.$website.'" /><br />';
			echo '<label for="comment_post">'.$this->lang('post').'</label><br /><textarea name="post" id="comment_post" cols="50" rows="6">'.$post.'</textarea><br />';
			if ($this->settings['recaptcha']) {
				$recaptcha = load_plugin('recaptcha');
				echo $recaptcha->get_html().'<br />';
			}
			echo '<input type="submit" value="'.$this->lang('submit').'" />';
			echo '</form>';
		}
	}
	function addtoindex($key,$id) {
		$con = $this->loadconstants();
		$con['comicid_idx'][$key] = $id;
		$this->saveconstants($con);
	}
	function removefromindex($key) {
		$con = $this->loadconstants();
		unset($con['comicid_idx'][$key]);
		$this->saveconstants($con);
	}
    ////////////////////////////////////////////////////////////
    // Index items   
    //    indexon(col#) will return a map of all id => value for the column # indicated
    //    Use the incremental option for servers with losts of data and short page timeouts.
    //        Each time you do a page load, the index will pick up from where is was stopped.
    ////////////////////////////////////////////////////////////
    function indexon($attribute,$incremental=false) {
	$this->db();
        $id = $this->db->lastid();

        $result = array();
        if($incremental) {
          $C = $this->loadconstants();
          $flg = (isset($C['INDEXON_'.$attribute.'_FLG'])?$C['INDEXON_'.$attribute.'_FLG']:0);
          if ($flg>0) {
                $id = $C['INDEXON_'.$attribute.'_ID'];
                $result=$C['INDEXON_'.$attribute.'_IDX'];
           } else {
        }
        }
        while ($id > 0) {
            if ( (!isset($file)) || ($id < $file->data['firstid']) ) {
                 $this->db->clearcache(); //deal with memory issues
                //save our progress
                if ($incremental) $this->saveconstants(array('INDEXON_'.$attribute.'_FLG' => 1, 'INDEXON_'.$attribute.'_ID' =>  $id, 'INDEXON_'.$attribute.'_IDX' => $result));
                // Load new file if needed
                $file = $this->db->itemfile($id,true,true);
                if (!$file) return NULL;
            }
            // Quick search
            $line = $file->read(($id-$file->data['firstid']));
            if (is_string($attribute)) {
                $comic = $this->db->loaddata($line,$id);
                $result[$id]=$comic[$attribute];
            } else {
                $ex = explode("|",$line);
                $result[$id]=$ex[$attribute];
            }
            $id--;
        }
        if ($incremental) $this->saveconstants(array('INDEXON_'.$attribute.'_FLG' => 0, 'INDEXON_'.$attribute.'_ID' =>  $id, 'INDEXON_'.$attribute.'_IDX' => 0));
        return $result;
    }
    
    
    ////////////////////////////////////////////////////////////
    // Comment database
    ////////////////////////////////////////////////////////////
    var $db = false;
    function db() {
        if (!$this->db) {
            import('.../lib/db/file/idbase.php');
            $this->db = new db_flib_idbase;
            $this->db->perfile = 25;
            $this->db->filepath = $this->setting_dir();
            $this->db->layout = array(
                'comicid'=>'int',
                'timestamp'=>'int',
                'user'=>'int',
                'name'=>'string',
                'email'=>'string',
                'post'=>'string',
		'flags'=>'int',
		'website'=>'string',
		'parent'=>'int',
		'children'=>'string',
            );
        }
    }
    
    ////////////////////////////////////////////////////////////
    // Commic database
    ////////////////////////////////////////////////////////////
    var $cdb = false;
    function getComic($comicid) {
        if (!$this->cdb) {
            import('.../lib/db/file/comic.php');
            $this->cdb = new db_comic;
        }
	if ($this->cdb) {
		$ci = $this->cdb->get('single',$comicid);
		if (count($ci)==1) return array('title'=> "ACCESS ERROR:".$ci['result']);
		else return $ci;
	} else return array('title'=>"$comicid:");    
}
 
    
    
    ////////////////////////////////////////////////////////////
    // Load constants
    ////////////////////////////////////////////////////////////

    function constantspath() {
	return makepath($this->db->filepath.'constants.dta');
	}

    function loadconstants() {
        $uri = $this->constantspath();
        if (is_readable($uri)) {
                if(!$obj=unserialize(file_get_contents($uri))) return NULL;
                return $obj;
        } else return NULL;
  }
   function saveconstants($a) {
        $orig = $this->loadconstants();
        if (isset($orig)) {
                $a = array_merge($orig,$a);
         }
        $uri =$this->constantspath();
        $handle = fopen($uri, "w");
        if ($handle) {
                fwrite($handle,serialize($a));
                fclose($handle);
        }
}
    
 ////////////////////////////////////////////////////////////
    // Search items
    //    search('foo') will find all items with foo anywhere in their fields
    //    search('foo','title') will find all items with foo as the title
    //
    // With $match = false only return if attribute is the query
    //
    // Search is still primitive, please put as little strain on it as possible
    ////////////////////////////////////////////////////////////
    function search($find,$attribute=false,$partial=false,$useindex=false) {
       $id = $this->db->lastid();
        $result = array();
        for (; $id > 0; $id--) {
           if ($useindex && $useindex[$id]!=$find) continue;
            if ( (!isset($file)) || ($id < $file->data['firstid']) ) {
                // Load new file if needed
                $file = $this->db->itemfile($id,true,true);
                if (!$file) return array('result'=>'error');
            }
            // Quick search
            $line = $file->read(($id-$file->data['firstid']));
            if (strpos(' '.strtolower($line),strtolower($find))) {
                // In depth search & format
                $comic = $this->db->loaddata($line,$id);
                if (!$attribute) {
                    $result[$id] = $comic;
                } elseif (is_array($comic[$attribute])) {
                    if (in_array($find,$comic[$attribute])) $result[$id] = $comic;
                } elseif ( ($partial) && (strpos(' '.strtolower($comic[$attribute]),strtolower($find))) ) {
                    $result[$id] = $comic;
                } elseif (strtolower($comic[$attribute])==strtolower($find)) {
                    $result[$id] = $comic;
                }
            }
        }

        // Format response
        if (!isset($result['result'])) $result['result'] = (empty($result)?'empty':'good');
        return $result;
    }
    
    
    
}
?>
