<?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_FancierURL extends NucleusPlugin{
    var $title = null;

  function getName()  { return 'FancierURL'; }
  function getAuthor() { return 'Dave St.Germain, mod by Radek HULAN'; }
  function getURL()     { return 'http://pobblelabs.org/software/nucleusplugins/'; }
  function getVersion() { return '0.6'; }
  function getDescription() {
      return 'Improves FancyURLs by allowing more descriptive URLs.';
  }
	function supportsFeature($feature) {
		switch($feature) {
			case 'SqlTablePrefix':
				return 1;
			default:
				return 0;
		}
	}
  function getEventList() {
    return array(
      'PreAddItem',
      'PostAddItem',
      'PreUpdateItem',
      'PrePluginOptionsEdit',
      'PostPluginOptionsUpdate',
      'PostAddCategory'
    );
  }

	function event_PreAddItem(&$data) {
	  $this->title = $data['title'];
	}

	function event_PostAddItem(&$data) {
		$q = 'UPDATE ' . sql_table('item') . ' SET iurltitle=\'' . $this->_makefancyTitle($this->title, $data['itemid']) . '\' WHERE inumber=' . strval($data['itemid']);
		sql_query($q);
	}

	function event_PreUpdateItem(&$data) {
		/* old title */
		$query=sql_query('SELECT iurltitle FROM '.sql_table('item').' WHERE inumber='.strval($data['itemid']));
		if ($row=sql_fetch_object($query)) $oldtitle=$row->iurltitle;
		/* new title */
		$newtitle=$this->_makefancyTitle($data['title'], $data['itemid']);
		$q = 'UPDATE ' . sql_table('item') . ' SET iurltitle=\'' . $newtitle . '\' WHERE inumber=' . strval($data['itemid']);
		sql_query($q);
		/* save history of iurltitles */
		if ($newtitle!=$oldtitle){
			$q=sql_query('SELECT count(*) as total FROM '.sql_table('plugin_fancierurl').' WHERE inumber='.strval($data['itemid']).' AND iurltitle=\''.$oldtitle.'\'');
			$row=sql_fetch_object($q);
			if ($row->total==0){
				$q='INSERT INTO '.sql_table('plugin_fancierurl').' (inumber,iurltitle) VALUES ('.strval($data['itemid']).',\''.$oldtitle.'\')';
				sql_query($q);
			}
		}
	}

	function event_PrePluginOptionsEdit(&$data) {
		if ($data['plugid'] == $this->getID()) {
			foreach($data['options'] as $option) {
				if ($option['name'] == 'spaceReplace') $this->spaceReplace = $option['value'];
			}
		}
	}

	function event_PostPluginOptionsUpdate(&$data) {
		if ($data['plugid'] == $this->getID() && $this->getOption(spaceReplace) !== $this->spaceReplace) {
			$this->_updateDB();
		}
	}

	function event_PostAddCategory($blog) {
	  $q = "UPDATE ".sql_table('category')." SET iurltitle='".$this->_makefancyCategory($blog['name'])."' WHERE  catid=".$blog['catid'];
	  sql_query($q);
	}

  function setCONF(){
	  global $CONF;
    if ( !isset($CONF['URLMode']) ) {
      $conf_query=sql_query("select value from ".sql_table("config")." where name='URLMode'");
      if ($conf_row=sql_fetch_object($conf_query)) $CONF['URLMode']=$conf_row->value;
    }
  }

	function doTemplateVar(&$item) {
	  $this->setCONF();
		echo fancyLink($item->itemid);
	}

	function doTemplateCommentsVar(&$item) {
	  $this->setCONF();
		echo fancyLink($item->itemid);
	}

	function doSkinVar($skinType, $linktype) {
	  $this->setCONF();
		switch($skinType) {
			case 'archive':
				global $archivenext, $archiveprev;
				$next = implode('/', explode('-', $archivenext));
				$prev = implode('/', explode('-', $archiveprev));

				if ($linktype == 'prevlink') {
					echo $this->_makeLink($prev);
				} else if ($linktype == 'nextlink') {
					echo $this->_makeLink($next);
				}
				break;
			default:
				global $itemidprev, $itemidnext;
				if ($linktype == 'prevlink')
          echo fancyLink($itemidprev);
				else if ($linktype == 'nextlink')
          echo fancyLink($itemidnext);
				else {
					global $itemid;
					echo fancyLink($itemid);
				}
				break;
		}
	}

	function install() {
		$this->createOption('archiveName','The name of the "archive" file','text','archive');
		$this->createOption('itemName','The name of the "item" file','text','item');
		$this->createOption('spaceReplace','The character which replaces spaces in URL titles','select','-', 'underscore|_|dash|-');
		$this->createOption('linktype','Create simple links /item/title?','yesno','yes');
		$this->_updateDB();
	}

	function getTableList() {	return array(sql_table('plugin_fancierurl')); }

	function _updateDB() {
	  // item
		$q = 'SELECT inumber, ititle FROM '. sql_table('item');
		$res = sql_query($q);
		while($row = sql_fetch_object($res)) {
			$q = 'UPDATE ' . sql_table('item') . ' SET iurltitle=\'' . $this->_makefancyTitle($row->ititle, $row->inumber) . '\' WHERE inumber=' . $row->inumber;
			sql_query($q);
		}
		sql_free_result($res);
		// category
		$q = 'SELECT catid, cname FROM '. sql_table('category');
		$res = sql_query($q);
		while($row = sql_fetch_object($res)) {
			$q = 'UPDATE ' . sql_table('category') . ' SET iurltitle=\'' . $this->_makefancyCategory($row->cname) . '\' WHERE catid=' . $row->catid;
			sql_query($q);
		}
		sql_free_result($res);
	}

	function _makeLink($archive) {
		global $CONF,$catid,$blogid;
		$link = $CONF['ItemURL'] . '/'. $this->getOption(archiveName) .'/' . $blogid . '/'. $archive;
    // category active?
    if ($catid>0) {
      $query=sql_query("select iurltitle from ".sql_table("category")." where catid=".strval($catid));
      if ( ($row=sql_fetch_object($query)) && (!empty($row->iurltitle)) )
        $link.='/category/'.$row->iurltitle;
      else
        $link.='/category/'.$catid;
    }
		return $link;
	}

	function _makefancyCategory($title) {
		$title = trim($title);
		$title = preg_replace('/\&(.*?);/','',$title);
		$title = strip_tags($title);
		$title = iso2ascii($title);
		$title = strtolower($title);
		preg_match_all('/[a-zA-Z0-9]+/', $title, $nt);
		$urltitle = implode($this->getOption('spaceReplace'), $nt[0]);
		return strtolower($urltitle);
	}

	function _makefancyTitle($title, $id) {
		$title = trim($title);
		$title = preg_replace('/\&(.*?);/','',$title);
		$title = strip_tags($title);
		$title = iso2ascii($title);
		$title = strtolower($title);
		preg_match_all('/[a-zA-Z0-9]+/', $title, $nt);
		$urltitle = implode($this->getOption('spaceReplace'), $nt[0]);
		if (empty($urltitle)) $urltitle=strval($id);
		$res = sql_query("SELECT inumber FROM ".sql_table('item')." WHERE iurltitle='$urltitle' AND inumber !=$id");
		if (sql_num_rows($res) > 0) {
			return strtolower($urltitle . $this->getOption(spaceReplace) . $id);
		} else {
			return strtolower($urltitle);
		}
	}
}
?>