Index: inc/core/class.dc.auth.php
===================================================================
--- inc/core/class.dc.auth.php	(revision 852)
+++ inc/core/class.dc.auth.php	(revision 527)
@@ -75,5 +75,8 @@
 			'publish' => __('publish entries and comments'),
 			'delete' => __('delete entries and comments'),
-			'contentadmin' => __('manage all entries and comments')
+			'contentadmin' => __('manage all entries and comments'),
+			'categories' => __('manage categories'),
+			'media' => __('manage their own media items'),
+			'media_admin' => __('manage all media items')
 		);
 	}
Index: inc/core/class.dc.blog.php
===================================================================
--- inc/core/class.dc.blog.php	(revision 877)
+++ inc/core/class.dc.blog.php	(revision 836)
@@ -55,4 +55,7 @@
 	
 	private $post_status = array();
+	private $comment_status = array();
+	
+	private $categories;
 	
 	/** @var boolean Disallow entries password protection */
@@ -92,5 +95,10 @@
 			$this->post_status['0'] = __('unpublished');
 			$this->post_status['1'] = __('published');
-						
+			
+			$this->comment_status['-2'] = __('junk');
+			$this->comment_status['-1'] = __('pending');
+			$this->comment_status['0'] = __('unpublished');
+			$this->comment_status['1'] = __('published');
+			
 			# --BEHAVIOR-- coreBlogConstruct
 			$this->core->callBehavior('coreBlogConstruct',$this);
@@ -137,4 +145,13 @@
 	}
 	
+	/**
+	Returns an array of available comment status codes and names.
+	
+	@return	<b>array</b> Simple array with codes in keys and names in value
+	*/
+	public function getAllCommentStatus()
+	{
+		return $this->comment_status;
+	}
 	
 	/**
@@ -167,4 +184,451 @@
 		$this->core->callBehavior('coreBlogAfterTriggerBlog',$cur);
 	}
+	
+	/**
+	Updates comment and trackback counters in post table. Should be called
+	every time a comment or trackback is added, removed or changed its status.
+	
+	@param	id		<b>integer</b>		Comment ID
+	@param	del		<b>boolean</b>		If comment is delete, set this to true
+	*/
+	public function triggerComment($id,$del=false)
+	{
+		$id = (integer) $id;
+		
+		$strReq = 'SELECT post_id, comment_trackback '.
+				'FROM '.$this->prefix.'comment '.
+				'WHERE comment_id = '.$id.' ';
+		
+		$rs = $this->con->select($strReq);
+		
+		$post_id = $rs->post_id;
+		$tb = (boolean) $rs->comment_trackback;
+		
+		$strReq = 'SELECT COUNT(post_id) '.
+				'FROM '.$this->prefix.'comment '.
+				'WHERE post_id = '.(integer) $post_id.' '.
+				'AND comment_trackback = '.(integer) $tb.' '.
+				'AND comment_status = 1 ';
+		
+		if ($del) {
+			$strReq .= 'AND comment_id <> '.$id.' ';
+		}
+		
+		$rs = $this->con->select($strReq);
+		
+		$cur = $this->con->openCursor($this->prefix.'post');
+		
+		if ($rs->isEmpty()) {
+			return;
+		}
+		
+		if ($tb) {
+			$cur->nb_trackback = (integer) $rs->f(0);
+		} else {
+			$cur->nb_comment = (integer) $rs->f(0);
+		}
+		
+		$cur->update('WHERE post_id = '.(integer) $post_id);
+	}
+	//@}
+	
+	/// @name Categories management methods
+	//@{
+	public function categories()
+	{
+		if (!($this->categories instanceof dcCategories)) {
+			$this->categories = new dcCategories($this->core);
+		}
+		
+		return $this->categories;
+	}
+	
+	/**
+	Retrieves categories. <var>$params</var> is an associative array which can
+	take the following parameters:
+	
+	- post_type: Get only entries with given type (default "post")
+	- cat_url: filter on cat_url field
+	- cat_id: filter on cat_id field
+	- start: start with a given category
+	- level: categories level to retrieve
+	
+	@param	params	<b>array</b>		Parameters
+	@return	<b>record</b>
+	*/
+	public function getCategories($params=array())
+	{
+		$c_params = array();
+		if (isset($params['post_type'])) {
+			$c_params['post_type'] = $params['post_type'];
+			unset($params['post_type']);
+		}
+		$counter = $this->getCategoriesCounter($c_params);
+		
+		$without_empty = $this->core->auth->userID() == false; # For public display
+		
+		$start = isset($params['start']) ? (integer) $params['start'] : 0;
+		$l = isset($params['level']) ? (integer) $params['level'] : 0;
+		
+		$rs = $this->categories()->getChildren($start,null,'desc');
+		
+		# Get each categories total posts count
+		$data = array();
+		$stack = array();
+		$level = 0;
+		$cols = $rs->columns();
+		while ($rs->fetch())
+		{
+			$nb_post = isset($counter[$rs->cat_id]) ? (integer) $counter[$rs->cat_id] : 0;
+			
+			if ($rs->level > $level) {
+				$nb_total = $nb_post;
+				$stack[$rs->level] = (integer) $nb_post;
+			} elseif ($rs->level == $level) {
+				$nb_total = $nb_post;
+				$stack[$rs->level] += $nb_post;
+			} else {
+				$nb_total = $stack[$rs->level+1] + $nb_post;
+				if (isset($stack[$rs->level])) {
+					$stack[$rs->level] += $nb_total;
+				} else {
+					$stack[$rs->level] = $nb_total;
+				}
+				unset($stack[$rs->level+1]);
+			}
+			
+			if ($nb_total == 0 && $without_empty) {
+				continue;
+			}
+			
+			$level = $rs->level;
+			
+			$t = array();
+			foreach ($cols as $c) {
+				$t[$c] = $rs->f($c);
+			}
+			$t['nb_post'] = $nb_post;
+			$t['nb_total'] = $nb_total;
+			
+			if ($l == 0 || ($l > 0 && $l == $rs->level)) {
+				array_unshift($data,$t);
+			}
+		}
+		
+		# We need to apply filter after counting
+		if (isset($params['cat_id']) && $params['cat_id'] !== '')
+		{
+			$found = false;
+			foreach ($data as $v) {
+				if ($v['cat_id'] == $params['cat_id']) {
+					$found = true;
+					$data = array($v);
+					break;
+				}
+			}
+			if (!$found) {
+				$data = array();
+			}
+		}
+		
+		if (isset($params['cat_url']) && ($params['cat_url'] !== '') 
+			&& !isset($params['cat_id']))
+		{
+			$found = false;
+			foreach ($data as $v) {
+				if ($v['cat_url'] == $params['cat_url']) {
+					$found = true;
+					$data = array($v);
+					break;
+				}
+			}
+			if (!$found) {
+				$data = array();
+			}
+		}
+		
+		return staticRecord::newFromArray($data);
+	}
+	
+	/**
+	Retrieves a category by its ID.
+	
+	@param	id		<b>integer</b>		Category ID
+	@return	<b>record</b>
+	*/
+	public function getCategory($id)
+	{
+		return $this->getCategories(array('cat_id' => $id));
+	}
+	
+	/**
+	Retrieves parents of a given category.
+	
+	@param	id		<b>integer</b>		Category ID
+	@return	<b>record</b>
+	*/
+	public function getCategoryParents($id)
+	{
+		return $this->categories()->getParents($id);
+	}
+	
+	/**
+	Retrieves first parent of a given category.
+	
+	@param	id		<b>integer</b>		Category ID
+	@return	<b>record</b>
+	*/
+	public function getCategoryParent($id)
+	{
+		return $this->categories()->getParent($id);
+	}
+	
+	/**
+	Retrieves all category's first children
+	
+	@param	id		<b>integer</b>		Category ID
+	@return	<b>record</b>
+	*/
+	public function getCategoryFirstChildren($id)
+	{
+		return $this->getCategories(array('start' => $id,'level' => $id == 0 ? 1 : 2));
+	}
+	
+	private function getCategoriesCounter($params=array())
+	{
+		$strReq =
+		'SELECT  C.cat_id, COUNT(P.post_id) AS nb_post '.
+		'FROM '.$this->prefix.'category AS C '.
+		'JOIN '.$this->prefix."post P ON (C.cat_id = P.cat_id AND P.blog_id = '".$this->con->escape($this->id)."' ) ".
+		"WHERE C.blog_id = '".$this->con->escape($this->id)."' ";
+		
+		if (!$this->core->auth->userID()) {
+			$strReq .= 'AND P.post_status = 1 ';
+		}
+		
+		if (!empty($params['post_type'])) {
+			$strReq .= 'AND P.post_type '.$this->con->in($params['post_type']);
+		}
+		
+		$strReq .= 'GROUP BY C.cat_id ';
+		
+		$rs = $this->con->select($strReq);
+		$counters = array();
+		while ($rs->fetch()) {
+			$counters[$rs->cat_id] = $rs->nb_post;
+		}
+		
+		return $counters;
+	}
+	
+	/**
+	Creates a new category. Takes a cursor as input and returns the new category
+	ID.
+	
+	@param	cur		<b>cursor</b>		Category cursor
+	@return	<b>integer</b>		New category ID
+	*/
+	public function addCategory($cur,$parent=0)
+	{
+		if (!$this->core->auth->check('categories',$this->id)) {
+			throw new Exception(__('You are not allowed to add categories'));
+		}
+		
+		$url = array();
+		if ($parent != 0)
+		{
+			$rs = $this->getCategory($parent);
+			if ($rs->isEmpty()) {
+				$url = array();
+			} else {
+				$url[] = $rs->cat_url;
+			}
+		}
+		
+		if ($cur->cat_url == '') {
+			$url[] = text::tidyURL($cur->cat_title,false);
+		} else {
+			$url[] = $cur->cat_url;
+		}
+		
+		$cur->cat_url = implode('/',$url);
+		
+		$this->getCategoryCursor($cur);
+		$cur->blog_id = (string) $this->id;
+		
+		# --BEHAVIOR-- coreBeforeCategoryCreate
+		$this->core->callBehavior('coreBeforeCategoryCreate',$this,$cur);
+		
+		$this->categories()->addNode($cur,$parent);
+		
+		# --BEHAVIOR-- coreAfterCategoryCreate
+		$this->core->callBehavior('coreAfterCategoryCreate',$this,$cur);
+		$this->triggerBlog();
+		
+		return $cur->cat_id;
+	}
+	
+	/**
+	Updates an existing category.
+	
+	@param	id		<b>integer</b>		Category ID
+	@param	cur		<b>cursor</b>		Category cursor
+	*/
+	public function updCategory($id,$cur)
+	{
+		if (!$this->core->auth->check('categories',$this->id)) {
+			throw new Exception(__('You are not allowed to update categories'));
+		}
+		
+		if ($cur->cat_url == '')
+		{
+			$url = array();
+			$rs = $this->categories()->getParents($id);
+			while ($rs->fetch()) {
+				if ($rs->index() == $rs->count()-1) {
+					$url[] = $rs->cat_url;
+				}
+			}
+			
+			
+			$url[] = text::tidyURL($cur->cat_title,false);
+			$cur->cat_url = implode('/',$url);
+		}
+		
+		$this->getCategoryCursor($cur,$id);
+		
+		# --BEHAVIOR-- coreBeforeCategoryUpdate
+		$this->core->callBehavior('coreBeforeCategoryUpdate',$this,$cur);
+		
+		$cur->update(
+		'WHERE cat_id = '.(integer) $id.' '.
+		"AND blog_id = '".$this->con->escape($this->id)."' ");
+		
+		# --BEHAVIOR-- coreAfterCategoryUpdate
+		$this->core->callBehavior('coreAfterCategoryUpdate',$this,$cur);
+		
+		$this->triggerBlog();
+	}
+	
+	/**
+	DEPRECATED METHOD. Use dcBlog::setCategoryParent and dcBlog::moveCategory
+	instead.
+	
+	@param	id		<b>integer</b>		Category ID
+	@param	order	<b>integer</b>		Category position
+	*/
+	public function updCategoryOrder($id,$order)
+	{
+		return;
+	}
+	
+	/**
+	Set a category parent
+	
+	@param	id		<b>integer</b>		Category ID
+	@param	parent	<b>integer</b>		Parent Category ID
+	*/
+	public function setCategoryParent($id,$parent)
+	{
+		$this->categories()->setNodeParent($id,$parent);
+		$this->triggerBlog();
+	}
+	
+	/**
+	Set category position
+	
+	@param	id		<b>integer</b>		Category ID
+	@param	sibling	<b>integer</b>		Sibling Category ID
+	@param	move		<b>integer</b>		Order (before|after)
+	*/
+	public function setCategoryPosition($id,$sibling,$move)
+	{
+		$this->categories()->setNodePosition($id,$sibling,$move);
+		$this->triggerBlog();
+	}
+	
+	/**
+	Deletes a category.
+	
+	@param	id		<b>integer</b>		Category ID
+	*/
+	public function delCategory($id)
+	{
+		if (!$this->core->auth->check('categories',$this->id)) {
+			throw new Exception(__('You are not allowed to delete categories'));
+		}
+		
+		$strReq = 'SELECT COUNT(post_id) AS nb_post '.
+				'FROM '.$this->prefix.'post '.
+				'WHERE cat_id = '.(integer) $id.' '.
+				"AND blog_id = '".$this->con->escape($this->id)."' ";
+		
+		$rs = $this->con->select($strReq);
+		
+		if ($rs->nb_post > 0) {
+			throw new Exception(__('This category is not empty.'));
+		}
+		
+		$this->categories()->deleteNode($id,true);
+		$this->triggerBlog();
+	}
+	
+	/**
+	Reset categories order and relocate them to first level
+	*/
+	public function resetCategoriesOrder()
+	{
+		if (!$this->core->auth->check('categories',$this->id)) {
+			throw new Exception(__('You are not allowed to reset categories order'));
+		}
+		
+		$this->categories()->resetOrder();
+		$this->triggerBlog();
+	}
+	
+	private function checkCategory($title,$url,$id=null)
+	{
+		$strReq = 'SELECT cat_id '.
+				'FROM '.$this->prefix.'category '.
+				"WHERE cat_url = '".$this->con->escape($url)."' ".
+				"AND blog_id = '".$this->con->escape($this->id)."' ";
+		
+		if ($id !== null) {
+			$strReq .= 'AND cat_id <> '.(integer) $id.' ';
+		}
+		
+		$rs = $this->con->select($strReq);
+		
+		if (!$rs->isEmpty()) {
+			throw new Exception(__('Category URL must be unique.'));
+		}
+	}
+	
+	private function getCategoryCursor($cur,$id=null)
+	{
+		if ($cur->cat_title == '') {
+			throw new Exception(__('You must provide a category title'));
+		}
+		
+		# If we don't have any cat_url, let's do one
+		if ($cur->cat_url == '') {
+			$cur->cat_url = text::tidyURL($cur->cat_title,false);
+		}
+		
+		# Still empty ?
+		if ($cur->cat_url == '') {
+			throw new Exception(__('You must provide a category URL'));
+		} else {
+			$cur->cat_url = text::tidyURL($cur->cat_url,true);
+		}
+		
+		# Check if title or url are unique
+		$this->checkCategory($cur->cat_title,$cur->cat_url,$id);
+		
+		if ($cur->cat_desc !== null) {
+			$cur->cat_desc = $this->core->HTMLfilter($cur->cat_desc);
+		}
+	}
+	//@}
 	
 	/// @name Entries management methods
@@ -179,4 +643,8 @@
 	- post_url: Get entry with given post_url field
 	- user_id: (integer) Get entries belonging to given user ID
+	- cat_id: (string or array) Get entries belonging to given category ID
+	- cat_id_not: deprecated (use cat_id with "id ?not" instead)
+	- cat_url: (string or array) Get entries belonging to given category URL
+	- cat_url_not: deprecated (use cat_url with "url ?not" instead)
 	- post_status: (integer) Get entries with given post_status
 	- post_selected: (boolean) Get select flaged entries
@@ -193,4 +661,7 @@
 	- sql_only : return the sql request instead of results. Only ids are selected
 	
+	Please note that on every cat_id or cat_url, you can add ?not to exclude
+	the category and ?sub to get subcategories.
+	
 	@param	params		<b>array</b>		Parameters
 	@param	count_only	<b>boolean</b>		Only counts results
@@ -226,15 +697,18 @@
 			
 			$strReq =
-			'SELECT P.post_id, P.blog_id, P.user_id, post_dt, '.
-			'post_tz, post_creadt, post_upddt, post_format, '.
+			'SELECT P.post_id, P.blog_id, P.user_id, P.cat_id, post_dt, '.
+			'post_tz, post_creadt, post_upddt, post_format, post_password, '.
 			'post_url, post_lang, post_title, '.$content_req.
 			'post_type, post_meta, post_status, post_selected, post_position, '.
+			'post_open_comment, post_open_tb, nb_comment, nb_trackback, '.
 			'U.user_name, U.user_firstname, U.user_displayname, U.user_email, '.
-			'U.user_url ';
+			'U.user_url, '.
+			'C.cat_title, C.cat_url, C.cat_desc ';
 		}
 		
 		$strReq .=
 		'FROM '.$this->prefix.'post P '.
-		'INNER JOIN '.$this->prefix.'user U ON U.user_id = P.user_id ';
+		'INNER JOIN '.$this->prefix.'user U ON U.user_id = P.user_id '.
+		'LEFT OUTER JOIN '.$this->prefix.'category C ON P.cat_id = C.cat_id ';
 		
 		if (!empty($params['from'])) {
@@ -246,5 +720,10 @@
 		
 		if (!$this->core->auth->check('contentadmin',$this->id)) {
-			$strReq .= 'AND ((post_status = 1) ';
+			$strReq .= 'AND ((post_status = 1 ';
+			
+			if ($this->without_password) {
+				$strReq .= 'AND post_password IS NULL ';
+			}
+			$strReq .= ') ';
 			
 			if ($this->core->auth->userID()) {
@@ -282,4 +761,25 @@
 		if (!empty($params['user_id'])) {
 			$strReq .= "AND U.user_id = '".$this->con->escape($params['user_id'])."' ";
+		}
+		
+		if (isset($params['cat_id']) && $params['cat_id'] !== '')
+		{
+			if (!is_array($params['cat_id'])) {
+				$params['cat_id'] = array($params['cat_id']);
+			}
+			if (!empty($params['cat_id_not'])) {
+				array_walk($params['cat_id'],create_function('&$v,$k','$v=$v." ?not";'));
+			}
+			$strReq .= 'AND '.$this->getPostsCategoryFilter($params['cat_id'],'cat_id').' ';
+		}
+		elseif (isset($params['cat_url']) && $params['cat_url'] !== '')
+		{
+			if (!is_array($params['cat_url'])) {
+				$params['cat_url'] = array($params['cat_url']);
+			}
+			if (!empty($params['cat_url_not'])) {
+				array_walk($params['cat_url'],create_function('&$v,$k','$v=$v." ?not";'));
+			}
+			$strReq .= 'AND '.$this->getPostsCategoryFilter($params['cat_url'],'cat_url').' ';
 		}
 		
@@ -354,12 +854,13 @@
 		}
 		
-		$posts = $this->con->select($strReq);
-		$posts->core = $this->core;
-		$posts->extend('rsExtPost');
+		$rs = $this->con->select($strReq);
+		$rs->core = $this->core;
+		$rs->_nb_media = array();
+		$rs->extend('rsExtPost');
 		
 		# --BEHAVIOR-- coreBlogGetPosts
-		$this->core->callBehavior('coreBlogGetPosts',$posts);
-		
-		return $posts;
+		$this->core->callBehavior('coreBlogGetPosts',$rs);
+		
+		return $rs;
 	}
 	
@@ -371,8 +872,9 @@
 	@param	post_id				<b>integer</b>		Post ID
 	@param	dir					<b>integer</b>		Search direction
+	@param	restrict_to_category	<b>boolean</b>		Restrict to post with same category
 	@param	restrict_to_lang		<b>boolean</b>		Restrict to post with same lang
 	@return	record
 	*/
-	public function getNextPost($post, $dir, $restrict_to_lang=false)
+	public function getNextPost($post,$dir,$restrict_to_category=false, $restrict_to_lang=false)
 	{
 		$dt = $post->post_dt;
@@ -397,15 +899,19 @@
 		') ';
 		
+		if ($restrict_to_category) {
+			$params['sql'] .= $post->cat_id ? 'AND P.cat_id = '.(integer) $post->cat_id.' ' : 'AND P.cat_id IS NULL ';
+		}
+		
 		if ($restrict_to_lang) {
 			$params['sql'] .= $post->post_lang ? 'AND P.post_lang = \''. $this->con->escape($post->post_lang) .'\' ': 'AND P.post_lang IS NULL ';
 		}
 		
-		$posts = $this->getPosts($params);
-		
-		if (count($posts) == 0) {
+		$rs = $this->getPosts($params);
+		
+		if ($rs->isEmpty()) {
 			return null;
 		}
 		
-		return $posts;
+		return $rs;
 	}
 	
@@ -431,5 +937,10 @@
 		
 		if (!$this->core->auth->check('contentadmin',$this->id)) {
-			$strReq .= 'AND ((post_status = 1) ';
+			$strReq .= 'AND ((post_status = 1 ';
+			
+			if ($this->without_password) {
+				$strReq .= 'AND post_password IS NULL ';
+			}
+			$strReq .= ') ';
 			
 			if ($this->core->auth->userID()) {
@@ -471,4 +982,6 @@
 	- month: (integer) Get dates for given month
 	- day: (integer) Get dates for given day
+	- cat_id: (integer) Category ID filter
+	- cat_url: Category URL filter
 	- post_lang: lang of the posts
 	- next: Get date following match
@@ -497,4 +1010,11 @@
 		$cat_field = $catReq = $limit = '';
 		
+		if (isset($params['cat_id']) && $params['cat_id'] !== '') {
+			$catReq = 'AND P.cat_id = '.(integer) $params['cat_id'].' ';
+			$cat_field = ', C.cat_url ';
+		} elseif (isset($params['cat_url']) && $params['cat_url'] !== '') {
+			$catReq = "AND C.cat_url = '".$this->con->escape($params['cat_url'])."' ";
+			$cat_field = ', C.cat_url ';
+		}
 		if (!empty($params['post_lang'])) {
 			$catReq = 'AND P.post_lang = \''. $params['post_lang'].'\' ';
@@ -502,11 +1022,18 @@
 		
 		$strReq = 'SELECT DISTINCT('.$this->con->dateFormat('post_dt',$dt_f).') AS dt '.
+				$cat_field.
 				',COUNT(P.post_id) AS nb_post '.
-				'FROM '.$this->prefix.'post P '.
+				'FROM '.$this->prefix.'post P LEFT JOIN '.$this->prefix.'category C '.
+				'ON P.cat_id = C.cat_id '.
 				"WHERE P.blog_id = '".$this->con->escape($this->id)."' ".
 				$catReq;
 		
 		if (!$this->core->auth->check('contentadmin',$this->id)) {
-			$strReq .= 'AND ((post_status = 1) ';
+			$strReq .= 'AND ((post_status = 1 ';
+			
+			if ($this->without_password) {
+				$strReq .= 'AND post_password IS NULL ';
+			}
+			$strReq .= ') ';
 			
 			if ($this->core->auth->userID()) {
@@ -554,4 +1081,6 @@
 		}
 		
+		$strReq .= 'GROUP BY dt '.$cat_field;
+		
 		$order = 'desc';
 		if (!empty($params['order']) && preg_match('/^(desc|asc)$/i',$params['order'])) {
@@ -563,7 +1092,7 @@
 		$limit;
 		
-		$dates = $this->con->select($strReq);
-		$dates->extend('rsExtDates');
-		return $dates;
+		$rs = $this->con->select($strReq);
+		$rs->extend('rsExtDates');
+		return $rs;
 	}
 	
@@ -585,12 +1114,10 @@
 		{
 			# Get ID
-			$max = $this->con->select(
+			$rs = $this->con->select(
 				'SELECT MAX(post_id) '.
 				'FROM '.$this->prefix.'post ' 
 				);
 			
-			$max = $max->current();
-			
-			$cur->post_id = (integer) $max->f(0) + 1;
+			$cur->post_id = (integer) $rs->f(0) + 1;
 			$cur->blog_id = (string) $this->id;
 			$cur->post_creadt = date('Y-m-d H:i:s');
@@ -670,7 +1197,7 @@
 					"AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
 			
-			$posts = $this->con->select($strReq);
-			
-			if (count($posts) == 0) {
+			$rs = $this->con->select($strReq);
+			
+			if ($rs->isEmpty()) {
 				throw new Exception(__('You are not allowed to edit this entry'));
 			}
@@ -712,7 +1239,7 @@
 					"AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
 			
-			$posts = $this->con->select($strReq);
-			
-			if (count($posts) == 0) {
+			$rs = $this->con->select($strReq);
+			
+			if ($rs->isEmpty()) {
 				throw new Exception(__('You are not allowed to change this entry status'));
 			}
@@ -733,4 +1260,8 @@
 	public function updPostSelected($id,$selected)
 	{
+		if (!$this->core->auth->check('usage,contentadmin',$this->id)) {
+			throw new Exception(__('You are not allowed to change this entry category'));
+		}
+		
 		$id = (integer) $id;
 		$selected = (boolean) $selected;
@@ -745,7 +1276,7 @@
 					"AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
 			
-			$posts = $this->con->select($strReq);
-			
-			if (count($posts) == 0) {
+			$rs = $this->con->select($strReq);
+			
+			if ($rs->isEmpty()) {
 				throw new Exception(__('You are not allowed to mark this entry as selected'));
 			}
@@ -765,21 +1296,19 @@
 	
 	/**
-	Deletes a post.
+	Updates post category. <var>$cat_id</var> can be null.
 	
 	@param	id		<b>integer</b>		Post ID
-	*/
-	public function delPost($id)
-	{
-		if (!$this->core->auth->check('delete,contentadmin',$this->id)) {
-			throw new Exception(__('You are not allowed to delete entries'));
+	@param	cat_id	<b>integer</b>		Category ID
+	*/
+	public function updPostCategory($id,$cat_id)
+	{
+		if (!$this->core->auth->check('usage,contentadmin',$this->id)) {
+			throw new Exception(__('You are not allowed to change this entry category'));
 		}
 		
 		$id = (integer) $id;
-		
-		if (empty($id)) {
-			throw new Exception(__('No such entry ID'));
-		}
-		
-		#If user can only delete, we need to check the post's owner
+		$cat_id = (integer) $cat_id;
+		
+		# If user is only usage, we need to check the post's owner
 		if (!$this->core->auth->check('contentadmin',$this->id))
 		{
@@ -790,7 +1319,52 @@
 					"AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
 			
-			$posts = $this->con->select($strReq);
-			
-			if (count($posts) == 0) {
+			$rs = $this->con->select($strReq);
+			
+			if ($rs->isEmpty()) {
+				throw new Exception(__('You are not allowed to change this entry category'));
+			}
+		}
+		
+		$cur = $this->con->openCursor($this->prefix.'post');
+		
+		$cur->cat_id = ($cat_id ? $cat_id : null);
+		$cur->post_upddt = date('Y-m-d H:i:s');
+		
+		$cur->update(
+			'WHERE post_id = '.$id.' '.
+			"AND blog_id = '".$this->con->escape($this->id)."' "
+		);
+		$this->triggerBlog();
+	}
+	
+	/**
+	Deletes a post.
+	
+	@param	id		<b>integer</b>		Post ID
+	*/
+	public function delPost($id)
+	{
+		if (!$this->core->auth->check('delete,contentadmin',$this->id)) {
+			throw new Exception(__('You are not allowed to delete entries'));
+		}
+		
+		$id = (integer) $id;
+		
+		if (empty($id)) {
+			throw new Exception(__('No such entry ID'));
+		}
+		
+		#If user can only delete, we need to check the post's owner
+		if (!$this->core->auth->check('contentadmin',$this->id))
+		{
+			$strReq = 'SELECT post_id '.
+					'FROM '.$this->prefix.'post '.
+					'WHERE post_id = '.$id.' '.
+					"AND blog_id = '".$this->con->escape($this->id)."' ".
+					"AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
+			
+			$rs = $this->con->select($strReq);
+			
+			if ($rs->isEmpty()) {
 				throw new Exception(__('You are not allowed to delete this entry'));
 			}
@@ -816,24 +1390,24 @@
 				"AND blog_id = '".$this->con->escape($this->id)."' ";
 		
-		$posts = $this->con->select($strReq);
+		$rs = $this->con->select($strReq);
 		
 		$now = dt::toUTC(time());
 		$to_change = new ArrayObject();
 
-		if (count($posts) == 0) {
+		if ($rs->isEmpty()) {
 			return;
 		}
 		
-		foreach ($posts as $post)
+		while ($rs->fetch())
 		{
 			# Now timestamp with post timezone
-			$now_tz = $now + dt::getTimeOffset($post->post_tz,$now);
+			$now_tz = $now + dt::getTimeOffset($rs->post_tz,$now);
 			
 			# Post timestamp
-			$post_ts = strtotime($post->post_dt);
+			$post_ts = strtotime($rs->post_dt);
 			
 			# If now_tz >= post_ts, we publish the entry
 			if ($now_tz >= $post_ts) {
-				$to_change[] = (integer) $post->post_id;
+				$to_change[] = (integer) $rs->post_id;
 			}
 		}
@@ -880,4 +1454,73 @@
 	}
 	
+	private function getPostsCategoryFilter($arr,$field='cat_id')
+	{
+		$field = $field == 'cat_id' ? 'cat_id' : 'cat_url';
+		
+		$sub = array();
+		$not = array();
+		$queries = array();
+		
+		foreach ($arr as $v)
+		{
+			$v = trim($v);
+			$args = preg_split('/\s*[?]\s*/',$v,-1,PREG_SPLIT_NO_EMPTY);
+			$id = array_shift($args);
+			$args = array_flip($args);
+			
+			if (isset($args['not'])) { $not[$id] = 1; }
+			if (isset($args['sub'])) { $sub[$id] = 1; }
+			if ($field == 'cat_id') {
+				if (preg_match('/^null$/i',$id)) {
+					$queries[$id] = 'P.cat_id IS NULL';
+				}
+				else {
+					$queries[$id] = 'P.cat_id = '.(integer) $id;
+				}
+			} else {
+				$queries[$id] = "C.cat_url = '".$this->con->escape($id)."' ";
+			}
+		}
+		
+		if (!empty($sub)) {
+			$rs = $this->con->select(
+				'SELECT cat_id, cat_url, cat_lft, cat_rgt FROM '.$this->prefix.'category '.
+				"WHERE blog_id = '".$this->con->escape($this->id)."' ".
+				'AND '.$field.' '.$this->con->in(array_keys($sub))
+			);
+			
+			while ($rs->fetch()) {
+				$queries[$rs->f($field)] = '(C.cat_lft BETWEEN '.$rs->cat_lft.' AND '.$rs->cat_rgt.')';
+			}
+		}
+		
+		# Create queries
+		$sql = array(
+			0 => array(), # wanted categories
+			1 => array()  # excluded categories
+		);
+		
+		foreach ($queries as $id => $q) {
+			$sql[(integer) isset($not[$id])][] = $q;
+		}
+		
+		$sql[0] = implode(' OR ',$sql[0]);
+		$sql[1] = implode(' OR ',$sql[1]);
+		
+		if ($sql[0]) {
+			$sql[0] = '('.$sql[0].')';
+		} else {
+			unset($sql[0]);
+		}
+		
+		if ($sql[1]) {
+			$sql[1] = '(P.cat_id IS NULL OR NOT('.$sql[1].'))';
+		} else {
+			unset($sql[1]);
+		}
+		
+		return implode(' AND ',$sql);
+	}
+	
 	private function getPostCursor($cur,$post_id=null)
 	{
@@ -888,4 +1531,8 @@
 		if ($cur->post_content == '') {
 			throw new Exception(__('No entry content'));
+		}
+		
+		if ($cur->post_password === '') {
+			$cur->post_password = null;
 		}
 		
@@ -1023,7 +1670,7 @@
 				'ORDER BY post_url DESC';
 		
-		$urls = $this->con->select($strReq);
-		
-		if (count($urls) > 0)
+		$rs = $this->con->select($strReq);
+		
+		if (!$rs->isEmpty())
 		{
 			if ($this->con->driver() == 'mysql') {
@@ -1040,8 +1687,8 @@
 					'ORDER BY post_url DESC ';
 			
-			$urls = $this->con->select($strReq);
+			$rs = $this->con->select($strReq);
 			$a = array();
-			foreach ($urls as $u) {
-				$a[] = $u->post_url;
+			while ($rs->fetch()) {
+				$a[] = $rs->post_url;
 			}
 			
@@ -1067,4 +1714,376 @@
 	}
 	//@}
+	
+	/// @name Comments management methods
+	//@{
+	/**
+	Retrieves comments. <b>$params</b> is an array taking the following
+	optionnal parameters:
+	
+	- no_content: Don't retrieve comment content
+	- post_type: Get only entries with given type (default no type, array for many types) 
+	- post_id: (integer) Get comments belonging to given post_id
+	- cat_id: (integer or array) Get comments belonging to entries of given category ID
+	- comment_id: (integer) Get comment with given ID
+	- comment_status: (integer) Get comments with given comment_status
+	- comment_trackback: (integer) Get only comments (0) or trackbacks (1)
+	- comment_ip: (string) Get comments with given IP address
+	- post_url: Get entry with given post_url field
+	- user_id: (integer) Get entries belonging to given user ID
+	- q_author: Search comments by author
+	- sql: Append SQL string at the end of the query
+	- from: Append SQL string after "FROM" statement in query
+	- order: Order of results (default "ORDER BY comment_dt DES")
+	- limit: Limit parameter
+	- sql_only : return the sql request instead of results. Only ids are selected
+	
+	@param	params		<b>array</b>		Parameters
+	@param	count_only	<b>boolean</b>		Only counts results
+	@return	<b>record</b>	A record with some more capabilities
+	*/
+	public function getComments($params=array(),$count_only=false)
+	{
+		if ($count_only)
+		{
+			$strReq = 'SELECT count(comment_id) ';
+		}
+		elseif (!empty($params['sql_only'])) 
+		{
+			$strReq = 'SELECT P.post_id ';
+		}
+		else
+		{
+			if (!empty($params['no_content'])) {
+				$content_req = '';
+			} else {
+				$content_req = 'comment_content, ';
+			}
+			
+			if (!empty($params['columns']) && is_array($params['columns'])) {
+				$content_req .= implode(', ',$params['columns']).', ';
+			}
+			
+			$strReq =
+			'SELECT C.comment_id, comment_dt, comment_tz, comment_upddt, '.
+			'comment_author, comment_email, comment_site, '.
+			$content_req.' comment_trackback, comment_status, '.
+			'comment_spam_status, comment_spam_filter, comment_ip, '.
+			'P.post_title, P.post_url, P.post_id, P.post_password, P.post_type, '.
+			'P.post_dt, P.user_id, U.user_email, U.user_url ';
+		}
+		
+		$strReq .=
+		'FROM '.$this->prefix.'comment C '.
+		'INNER JOIN '.$this->prefix.'post P ON C.post_id = P.post_id '.
+		'INNER JOIN '.$this->prefix.'user U ON P.user_id = U.user_id ';
+		
+		if (!empty($params['from'])) {
+			$strReq .= $params['from'].' ';
+		}
+		
+		$strReq .=
+		"WHERE P.blog_id = '".$this->con->escape($this->id)."' ";
+		
+		if (!$this->core->auth->check('contentadmin',$this->id)) {
+			$strReq .= 'AND ((comment_status = 1 AND P.post_status = 1 ';
+			
+			if ($this->without_password) {
+				$strReq .= 'AND post_password IS NULL ';
+			}
+			$strReq .= ') ';
+			
+			if ($this->core->auth->userID()) {
+				$strReq .= "OR P.user_id = '".$this->con->escape($this->core->auth->userID())."')";
+			} else {
+				$strReq .= ') ';
+			}
+		}
+		
+		if (!empty($params['post_type']))
+		{
+			$strReq .= 'AND post_type '.$this->con->in($params['post_type']);
+		}
+		
+		if (isset($params['post_id']) && $params['post_id'] !== '') {
+			$strReq .= 'AND P.post_id = '.(integer) $params['post_id'].' ';
+		}
+		
+		if (isset($params['cat_id']) && $params['cat_id'] !== '') {
+			$strReq .= 'AND P.cat_id = '.(integer) $params['cat_id'].' ';
+		}
+		
+		if (isset($params['comment_id']) && $params['comment_id'] !== '') {
+			$strReq .= 'AND comment_id = '.(integer) $params['comment_id'].' ';
+		}
+		
+		if (isset($params['comment_status'])) {
+			$strReq .= 'AND comment_status = '.(integer) $params['comment_status'].' ';
+		}
+		
+		if (!empty($params['comment_status_not']))
+		{
+			$strReq .= 'AND comment_status <> '.(integer) $params['comment_status_not'].' ';
+		}
+		
+		if (isset($params['comment_trackback'])) {
+			$strReq .= 'AND comment_trackback = '.(integer) (boolean) $params['comment_trackback'].' ';
+		}
+		
+		if (isset($params['comment_ip'])) {
+			$strReq .= "AND comment_ip = '".$this->con->escape($params['comment_ip'])."' ";
+		}
+		
+		if (isset($params['q_author'])) {
+			$q_author = $this->con->escape(str_replace('*','%',strtolower($params['q_author'])));
+			$strReq .= "AND LOWER(comment_author) LIKE '".$q_author."' ";
+		}
+		
+		if (!empty($params['search']))
+		{
+			$words = text::splitWords($params['search']);
+			
+			if (!empty($words))
+			{
+				# --BEHAVIOR coreCommentSearch
+				if ($this->core->hasBehavior('coreCommentSearch')) {
+					$this->core->callBehavior('coreCommentSearch',$this->core,array(&$words,&$strReq,&$params));
+				}
+				
+				if ($words)
+				{
+					foreach ($words as $i => $w) {
+						$words[$i] = "comment_words LIKE '%".$this->con->escape($w)."%'";
+					}
+					$strReq .= 'AND '.implode(' AND ',$words).' ';
+				}
+			}
+		}
+		
+		if (!empty($params['sql'])) {
+			$strReq .= $params['sql'].' ';
+		}
+		
+		if (!$count_only)
+		{
+			if (!empty($params['order'])) {
+				$strReq .= 'ORDER BY '.$this->con->escape($params['order']).' ';
+			} else {
+				$strReq .= 'ORDER BY comment_dt DESC ';
+			}
+		}
+		
+		if (!$count_only && !empty($params['limit'])) {
+			$strReq .= $this->con->limit($params['limit']);
+		}
+
+		if (!empty($params['sql_only'])) {
+			return $strReq;
+		}
+		
+		$rs = $this->con->select($strReq);
+		$rs->core = $this->core;
+		$rs->extend('rsExtComment');
+		
+		# --BEHAVIOR-- coreBlogGetComments
+		$this->core->callBehavior('coreBlogGetComments',$rs);
+		
+		return $rs;
+	}
+	
+	/**
+	Creates a new comment. Takes a cursor as input and returns the new comment
+	ID.
+	
+	@param	cur		<b>cursor</b>		Comment cursor
+	@return	<b>integer</b>		New comment ID
+	*/
+	public function addComment($cur)
+	{
+		$this->con->writeLock($this->prefix.'comment');
+		try
+		{
+			# Get ID
+			$rs = $this->con->select(
+				'SELECT MAX(comment_id) '.
+				'FROM '.$this->prefix.'comment ' 
+			);
+			
+			$cur->comment_id = (integer) $rs->f(0) + 1;
+			$cur->comment_upddt = date('Y-m-d H:i:s');
+			
+			$offset = dt::getTimeOffset($this->settings->system->blog_timezone);
+			$cur->comment_dt = date('Y-m-d H:i:s',time() + $offset);
+			$cur->comment_tz = $this->settings->system->blog_timezone;
+			
+			$this->getCommentCursor($cur);
+			
+			if ($cur->comment_ip === null) {
+				$cur->comment_ip = http::realIP();
+			}
+			
+			# --BEHAVIOR-- coreBeforeCommentCreate
+			$this->core->callBehavior('coreBeforeCommentCreate',$this,$cur);
+			
+			$cur->insert();
+			$this->con->unlock();
+		}
+		catch (Exception $e)
+		{
+			$this->con->unlock();
+			throw $e;
+		}
+		
+		# --BEHAVIOR-- coreAfterCommentCreate
+		$this->core->callBehavior('coreAfterCommentCreate',$this,$cur);
+		
+		$this->triggerComment($cur->comment_id);
+		if ($cur->comment_status != -2) {
+			$this->triggerBlog();
+		}	
+		return $cur->comment_id;
+	}
+	
+	/**
+	Updates an existing comment.
+	
+	@param	id		<b>integer</b>		Comment ID
+	@param	cur		<b>cursor</b>		Comment cursor
+	*/
+	public function updComment($id,$cur)
+	{
+		if (!$this->core->auth->check('usage,contentadmin',$this->id)) {
+			throw new Exception(__('You are not allowed to update comments'));
+		}
+		
+		$id = (integer) $id;
+		
+		if (empty($id)) {
+			throw new Exception(__('No such comment ID'));
+		}
+		
+		$rs = $this->getComments(array('comment_id' => $id));
+		
+		if ($rs->isEmpty()) {
+			throw new Exception(__('No such comment ID'));
+		}
+		
+		#If user is only usage, we need to check the post's owner
+		if (!$this->core->auth->check('contentadmin',$this->id))
+		{
+			if ($rs->user_id != $this->core->auth->userID()) {
+				throw new Exception(__('You are not allowed to update this comment'));
+			}
+		}
+		
+		$this->getCommentCursor($cur);
+		
+		$cur->comment_upddt = date('Y-m-d H:i:s');
+		
+		if (!$this->core->auth->check('publish,contentadmin',$this->id)) {
+			$cur->unsetField('comment_status');
+		}
+		
+		# --BEHAVIOR-- coreBeforeCommentUpdate
+		$this->core->callBehavior('coreBeforeCommentUpdate',$this,$cur,$rs);
+		
+		$cur->update('WHERE comment_id = '.$id.' ');
+		
+		# --BEHAVIOR-- coreAfterCommentUpdate
+		$this->core->callBehavior('coreAfterCommentUpdate',$this,$cur,$rs);
+		
+		$this->triggerComment($id);
+		$this->triggerBlog();
+	}
+	
+	/**
+	Updates comment status.
+	
+	@param	id		<b>integer</b>		Comment ID
+	@param	status	<b>integer</b>		Comment status
+	*/
+	public function updCommentStatus($id,$status)
+	{
+		if (!$this->core->auth->check('publish,contentadmin',$this->id)) {
+			throw new Exception(__("You are not allowed to change this comment's status"));
+		}
+		
+		$cur = $this->con->openCursor($this->prefix.'comment');
+		$cur->comment_status = (integer) $status;
+		$this->updComment($id,$cur);
+	}
+	
+	/**
+	Delete a comment
+	
+	@param	id		<b>integer</b>		Comment ID
+	*/
+	public function delComment($id)
+	{
+		if (!$this->core->auth->check('delete,contentadmin',$this->id)) {
+			throw new Exception(__('You are not allowed to delete comments'));
+		}
+		
+		$id = (integer) $id;
+		
+		if (empty($id)) {
+			throw new Exception(__('No such comment ID'));
+		}
+		
+		#If user can only delete, we need to check the post's owner
+		if (!$this->core->auth->check('contentadmin',$this->id))
+		{
+			$strReq = 'SELECT P.post_id '.
+					'FROM '.$this->prefix.'post P, '.$this->prefix.'comment C '.
+					'WHERE P.post_id = C.post_id '.
+					"AND P.blog_id = '".$this->con->escape($this->id)."' ".
+					'AND comment_id = '.$id.' '.
+					"AND user_id = '".$this->con->escape($this->core->auth->userID())."' ";
+			
+			$rs = $this->con->select($strReq);
+			
+			if ($rs->isEmpty()) {
+				throw new Exception(__('You are not allowed to delete this comment'));
+			}
+		}
+		
+		$strReq = 'DELETE FROM '.$this->prefix.'comment '.
+				'WHERE comment_id = '.$id.' ';
+		
+		$this->triggerComment($id,true);
+		$this->con->execute($strReq);
+		$this->triggerBlog();
+	}
+	
+	private function getCommentCursor($cur)
+	{
+		if ($cur->comment_content !== null && $cur->comment_content == '') {
+			throw new Exception(__('You must provide a comment'));
+		}
+		
+		if ($cur->comment_author !== null && $cur->comment_author == '') {
+			throw new Exception(__('You must provide an author name'));
+		}
+		
+		if ($cur->comment_email != '' && !text::isEmail($cur->comment_email)) {
+			throw new Exception(__('Email address is not valid.'));
+		}
+		
+		if ($cur->comment_site !== null && $cur->comment_site != '') {
+			if (!preg_match('|^http(s?)://|',$cur->comment_site)) {
+				$cur->comment_site = 'http://'.$cur->comment_site;
+			}
+		}
+		
+		if ($cur->comment_status === null) {
+			$cur->comment_status = (integer) $this->settings->system->comments_pub;
+		}
+		
+		# Words list
+		if ($cur->comment_content !== null)
+		{
+			$cur->comment_words = implode(' ',text::splitWords($cur->comment_content));
+		}
+	}
+	//@}
 }
 ?>
Index: inc/core/class.dc.categories.php
===================================================================
--- inc/core/class.dc.categories.php	(revision 270)
+++ inc/core/class.dc.categories.php	(revision 270)
@@ -0,0 +1,483 @@
+<?php
+# -- BEGIN LICENSE BLOCK ---------------------------------------
+#
+# This file is part of Dotclear 2.
+#
+# Copyright (c) 2003-2011 Olivier Meunier & Association Dotclear
+# Licensed under the GPL version 2.0 license.
+# See LICENSE file or
+# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
+#
+# -- END LICENSE BLOCK -----------------------------------------
+if (!defined('DC_RC_PATH')) { return; }
+
+# nestedTree class is based on excellent work of Kuzma Feskov
+# (http://php.russofile.ru/ru/authors/sql/nestedsets01/)
+#
+# One day we'll move nestedTree to Clearbricks.
+
+class dcCategories extends nestedTree
+{
+	protected $f_left = 'cat_lft';
+	protected $f_right = 'cat_rgt';
+	protected $f_id = 'cat_id';
+	
+	protected $core;
+	protected $blog_id;
+	
+	public function __construct($core)
+	{
+		$this->core =& $core;
+		$this->con =& $core->con;
+		$this->blog_id = $core->blog->id;
+		$this->table = $core->prefix.'category';
+		$this->add_condition = array('blog_id' => "'".$this->con->escape($this->blog_id)."'");
+	}
+	
+	public function getChildren($start=0,$id=null,$sort='asc',$fields=array())
+	{
+		$fields = array_merge(array('cat_title','cat_url','cat_desc'),$fields);
+		return parent::getChildren($start,$id,$sort,$fields);
+	}
+	
+	public function getParents($id,$fields=array())
+	{
+		$fields = array_merge(array('cat_title','cat_url','cat_desc'),$fields);
+		return parent::getParents($id,$fields);
+	}
+	
+	public function getParent($id,$fields=array())
+	{
+		$fields = array_merge(array('cat_title','cat_url','cat_desc'),$fields);
+		return parent::getParent($id,$fields);
+	}
+}
+
+abstract class nestedTree
+{
+	protected $con;
+	
+	protected $table;
+	protected $f_left;
+	protected $f_right;
+	protected $f_id;
+	
+	protected $add_condition = array();
+	
+	protected $parents;
+	
+	public function __construct($con)
+	{
+		$this->con =& $con;
+	}
+	
+	public function getChildren($start=0,$id=null,$sort='asc',$fields=array())
+	{
+		$fields = count($fields) > 0 ? ', C2.'.implode(', C2.',$fields) : '';
+		
+		$sql = 'SELECT C2.'.$this->f_id.', C2.'.$this->f_left.', C2.'.$this->f_right.', COUNT(C1.'.$this->f_id.') AS level '
+		. $fields.' '	
+		. 'FROM '.$this->table.' AS C1, '.$this->table.' AS C2 %s '
+		. 'WHERE C2.'.$this->f_left.' BETWEEN C1.'.$this->f_left.' AND C1.'.$this->f_right.' '
+		. ' %s '
+		. $this->getCondition('AND','C2.')
+		. $this->getCondition('AND','C1.')
+		. 'GROUP BY C2.'.$this->f_id.', C2.'.$this->f_left.', C2.'.$this->f_right.' '.$fields.' '
+		. ' %s '
+		. 'ORDER BY C2.'.$this->f_left.' '.($sort == 'asc' ? 'ASC' : 'DESC').' ';
+		
+		$from = $where = '';
+		if ($start > 0) {
+			$from = ', '.$this->table.' AS C3';
+			$where = 'AND C3.'.$this->f_id.' = '.(integer) $start.' AND C1.'.$this->f_left.' >= C3.'.$this->f_left.' AND C1.'.$this->f_right.' <= C3.'.$this->f_right;
+			$where .= $this->getCondition('AND','C3.');
+		}
+		
+		$having = '';
+		if ($id !== null) {
+			$having = ' HAVING C2.'.$this->f_id.' = '.(integer) $id;
+		}
+		
+		$sql = sprintf($sql,$from,$where,$having);
+		
+		return $this->con->select($sql);
+	}
+	
+	public function getParents($id,$fields=array())
+	{
+		$fields = count($fields) > 0 ? ', C1.'.implode(', C1.',$fields) : '';
+		
+		return $this->con->select(
+			'SELECT C1.'.$this->f_id.' '.$fields.' '
+			. 'FROM '.$this->table.' C1, '.$this->table.' C2 '
+			. 'WHERE C2.'.$this->f_id.' = '.(integer) $id.' '
+			. 'AND C1.'.$this->f_left.' < C2.'.$this->f_left.' '
+			. 'AND C1.'.$this->f_right.' > C2.'.$this->f_right.' '
+			. $this->getCondition('AND','C2.')
+			. $this->getCondition('AND','C1.')
+			. 'ORDER BY C1.'.$this->f_left.' ASC '
+		);
+	}
+	
+	public function getParent($id,$fields=array())
+	{
+		$fields = count($fields) > 0 ? ', C1.'.implode(', C1.',$fields) : '';
+		
+		return $this->con->select(
+			'SELECT C1.'.$this->f_id.' '.$fields.' '
+			. 'FROM '.$this->table.' C1, '.$this->table.' C2 '
+			. 'WHERE C2.'.$this->f_id.' = '.(integer) $id.' '
+			. 'AND C1.'.$this->f_left.' < C2.'.$this->f_left.' '
+			. 'AND C1.'.$this->f_right.' > C2.'.$this->f_right.' '
+			. $this->getCondition('AND','C2.')
+			. $this->getCondition('AND','C1.')
+			. 'ORDER BY C1.'.$this->f_left.' DESC '
+			. $this->con->limit(1)
+		);
+	}
+	
+	/* ------------------------------------------------
+	 * Tree manipulations
+	 * ---------------------------------------------- */
+	public function addNode($data,$target=0)
+	{
+		if (!is_array($data) && !($data instanceof cursor)) {
+			throw new Exception('Invalid data block');
+		}
+		
+		if (is_array($data))
+		{
+			$D = $data;
+			$data = $this->con->openCursor($this->table);
+			foreach ($D as $k => $v) {
+				$data->{$k} = $v;
+			}
+			unset($D);
+		}
+		
+		# We want to put it at the end
+		$this->con->writeLock($this->table);
+		try
+		{
+			$rs = $this->con->select('SELECT MAX('.$this->f_id.') as n_id FROM '.$this->table);
+			$id = $rs->n_id;
+			
+			$rs = $this->con->select(
+				'SELECT MAX('.$this->f_right.') as n_r '.
+				'FROM '.$this->table.
+				$this->getCondition('WHERE')
+			);
+			$last = $rs->n_r == 0 ? 1 : $rs->n_r;
+			
+			$data->{$this->f_id} = $id+1;
+			$data->{$this->f_left} = $last+1;
+			$data->{$this->f_right} = $last+2;
+			
+			$data->insert();
+			$this->con->unlock();
+			try {
+				$this->setNodeParent($id+1,$target);
+				return $data->{$this->f_id};
+			} catch (Exception $e) {} # We don't mind error in this case
+		}
+		catch (Exception $e)
+		{
+			$this->con->unlock();
+			throw $e;
+		}
+	}
+	
+	public function deleteNode($node,$keep_children=true)
+	{
+		$node = (integer) $node;
+		
+		$rs = $this->getChildren(0,$node);
+		if ($rs->isEmpty()) {
+			throw new Exception('Node does not exist.');
+		}
+		$node_left = (integer) $rs->{$this->f_left};
+		$node_right = (integer) $rs->{$this->f_right};
+		
+		try
+		{
+			$this->con->begin();
+			
+			if ($keep_children)
+			{
+				$this->con->execute('DELETE FROM '.$this->table.' WHERE '.$this->f_id.' = '.$node);
+				
+				$sql = 'UPDATE '.$this->table.' SET '
+				. $this->f_right.' = CASE '
+				. 	'WHEN '.$this->f_right.' BETWEEN '.$node_left.' AND '.$node_right.' '
+				.		'THEN '.$this->f_right.' - 1 '
+				.	'WHEN '.$this->f_right.' > '.$node_right.' '
+				.		'THEN '.$this->f_right.' - 2 '
+				.	'ELSE '.$this->f_right.' '
+				.	'END, '
+				. $this->f_left.' = CASE '
+				.	'WHEN '.$this->f_left.' BETWEEN '.$node_left.' AND '.$node_right.' '
+				.		'THEN '.$this->f_left.' - 1 '
+				.	'WHEN '.$this->f_left.' > '.$node_right.' '
+				.		'THEN '.$this->f_left.' - 2 '
+				.	'ELSE '.$this->f_left.' '
+				.	'END '
+				. 'WHERE '.$this->f_right.' > '.$node_left
+				. $this->getCondition();
+				
+				$this->con->execute($sql);
+			}
+			else
+			{
+				$this->con->execute('DELETE FROM '.$this->table.' WHERE '.$this->f_left.' BETWEEN '.$node_left.' AND '.$node_right);
+				
+				$node_delta = $node_right - $node_left + 1;
+				$sql = 'UPDATE '.$this->table.' SET '
+				. $this->f_left.' = CASE '
+				.	'WHEN '.$this->f_left.' > '.$node_left.' '
+				.		'THEN '.$this->f_left.' - ('.$node_delta.') '
+				.	'ELSE '.$this->f_left.' '
+				.	'END, '
+				. $this->f_right.' = CASE '
+				.	'WHEN '.$this->f_right.' > '.$node_left.' '
+				.		'THEN '.$this->f_right.' - ('.$node_delta.') '
+				.	'ELSE '.$this->f_right.' '
+				.	'END '
+				. 'WHERE '.$this->f_right.' > '.$node_right
+				. $this->getCondition();
+			}
+			
+			$this->con->commit();
+		}
+		catch (Exception $e)
+		{
+			$this->con->rollback();
+			throw $e;
+		}
+	}
+	
+	public function resetOrder()
+	{
+		$rs = $this->con->select(
+			'SELECT '.$this->f_id.' '
+			.'FROM '.$this->table.' '
+			.$this->getCondition('WHERE')
+			.'ORDER BY '.$this->f_left.' ASC '
+		);
+		
+		$lft = 2;
+		$this->con->begin();
+		try
+		{
+			while ($rs->fetch()) {
+				$this->con->execute(
+					'UPDATE '.$this->table.' SET '
+					.$this->f_left.' = '.($lft++).', '
+					.$this->f_right.' = '.($lft++).' '
+					.'WHERE '.$this->f_id .' = '.(integer) $rs->{$this->f_id}.' '
+					.$this->getCondition()
+				);
+			}
+			$this->con->commit();
+		}
+		catch (Exception $e)
+		{
+			$this->con->rollback();
+			throw $e;
+		}
+	}
+	
+	public function setNodeParent($node,$target=0)
+	{
+		if ($node == $target) {
+			return;
+		}
+		$node = (integer) $node;
+		$target = (integer) $target;
+		
+		$rs = $this->getChildren(0,$node);
+		if ($rs->isEmpty()) {
+			throw new Exception('Node does not exist.');
+		}
+		$node_left = (integer) $rs->{$this->f_left};
+		$node_right = (integer) $rs->{$this->f_right};
+		$node_level = (integer) $rs->level;
+		
+		if ($target > 0)
+		{
+			$rs = $this->getChildren(0,$target);
+		}
+		else
+		{
+			$rs = $this->con->select(
+				'SELECT MIN('.$this->f_left.')-1 AS '.$this->f_left.', MAX('.$this->f_right.')+1 AS '.$this->f_right.', 0 AS level '.
+				'FROM '.$this->table.' '.
+				$this->getCondition('WHERE')
+			);
+		}
+		$target_left = (integer) $rs->{$this->f_left};
+		$target_right = (integer) $rs->{$this->f_right};
+		$target_level = (integer) $rs->level;
+		
+		if ($node_left == $target_left
+			|| ($target_left >= $node_left && $target_left <= $node_right)
+			|| ($node_level == $target_level+1 && $node_left > $target_left && $node_right < $target_right)
+		)
+		{
+			throw new Exception('Cannot move tree');
+		}
+		
+		if ($target_left < $node_left && $target_right > $node_right && $target_level < $node_level -1)
+		{
+			$sql = 'UPDATE '.$this->table.' SET '
+			. $this->f_right.' = CASE '
+			.	'WHEN '.$this->f_right.' BETWEEN '.($node_right+1).' AND '.($target_right-1).' '
+			.		'THEN '.$this->f_right.'-('.($node_right-$node_left+1).') '
+			. 	'WHEN '.$this->f_left.' BETWEEN '.$node_left.' AND '.$node_right.' '
+			.		'THEN '.$this->f_right.'+'.((($target_right-$node_right-$node_level+$target_level)/2)*2+$node_level-$target_level-1).' '
+			.	'ELSE '
+			.		$this->f_right.' '
+			.	'END, '
+			. $this->f_left.' = CASE '
+			.	'WHEN '.$this->f_left.' BETWEEN '.($node_right+1).' AND '.($target_right-1).' '
+			.		'THEN '.$this->f_left.'-('.($node_right-$node_left+1).') '
+			.	'WHEN '.$this->f_left.' BETWEEN '.$node_left.' AND '.$node_right.' '
+			.		'THEN '.$this->f_left.'+'.((($target_right-$node_right-$node_level+$target_level)/2)*2+$node_level-$target_level-1).' '
+			.	'ELSE '.$this->f_left.' '
+			.	'END '
+			. 'WHERE '.$this->f_left.' BETWEEN '.($target_left+1).' AND '.($target_right-1).'';
+		}
+		elseif ($target_left < $node_left)
+		{
+			$sql = 'UPDATE '.$this->table.' SET '
+			. $this->f_left.' = CASE '
+			.	'WHEN '.$this->f_left.' BETWEEN '.$target_right.' AND '.($node_left-1).' '
+			.		'THEN '.$this->f_left.'+'.($node_right-$node_left+1).' '
+			.	'WHEN '.$this->f_left.' BETWEEN '.$node_left.' AND '.$node_right.' '
+			.		'THEN '.$this->f_left.'-('.($node_left-$target_right).') '
+			.	'ELSE '.$this->f_left .' '
+			.	'END, '
+			. $this->f_right.' = CASE '
+			.	'WHEN '.$this->f_right.' BETWEEN '.$target_right.' AND '.$node_left.' '
+			.		'THEN '.$this->f_right.'+'.($node_right-$node_left+1).' '
+			.	'WHEN '.$this->f_right.' BETWEEN '.$node_left.' AND '.$node_right.' '
+			.		'THEN '.$this->f_right.'-('.($node_left-$target_right).') '
+			.	'ELSE '.$this->f_right.' '
+			.	'END '
+			. 'WHERE ('.$this->f_left.' BETWEEN '.$target_left.' AND '.$node_right. ' '
+			. 	'OR '.$this->f_right.' BETWEEN '.$target_left.' AND '.$node_right.')';
+		}
+		else
+		{
+			$sql = 'UPDATE '.$this->table.' SET '
+			. $this->f_left.' = CASE '
+			.	'WHEN '.$this->f_left.' BETWEEN '.$node_right.' AND '.$target_right.' '
+			.		'THEN '.$this->f_left.'-'.($node_right-$node_left+1).' '
+			.	'WHEN '.$this->f_left.' BETWEEN '.$node_left.' AND '.$node_right.' '
+			.		'THEN '.$this->f_left.'+'.($target_right-1-$node_right).' '
+			.	'ELSE '.$this->f_left.' '
+			.	'END, '
+			. $this->f_right.' = CASE '
+			.	'WHEN '.$this->f_right.' BETWEEN '.($node_right+1).' AND '.($target_right-1).' '
+			.		'THEN '.$this->f_right.'-'.($node_right-$node_left+1).' '
+			.	'WHEN '.$this->f_right.' BETWEEN '.$node_left.' AND '.$node_right.' '
+			.		'THEN '.$this->f_right.'+'.($target_right-1-$node_right).' '
+			.	'ELSE '.$this->f_right.' '
+			.	'END '
+			. 'WHERE ('.$this->f_left.' BETWEEN '.$node_left.' AND '.$target_right.' '
+			. 	'OR '.$this->f_right.' BETWEEN '.$node_left.' AND '.$target_right.')';
+		}
+		
+		$sql .= ' '.$this->getCondition();
+		
+		$this->con->execute($sql);
+	}
+	
+	public function setNodePosition($nodeA,$nodeB,$position='after')
+	{
+		$nodeA = (integer) $nodeA;
+		$nodeB = (integer) $nodeB;
+		
+		$rs = $this->getChildren(0,$nodeA);
+		if ($rs->isEmpty()) {
+			throw new Exception('Node does not exist.');
+		}
+		$A_left = $rs->{$this->f_left};
+		$A_right = $rs->{$this->f_right};
+		$A_level = $rs->level;
+		
+		$rs = $this->getChildren(0,$nodeB);
+		if ($rs->isEmpty()) {
+			throw new Exception('Node does not exist.');
+		}
+		$B_left = $rs->{$this->f_left};
+		$B_right = $rs->{$this->f_right};
+		$B_level = $rs->level;
+		
+		if ($A_level != $B_level) {
+			throw new Exception('Cannot change position');
+		}
+		
+		$rs = $this->getParents($nodeA);
+		$parentA = $rs->isEmpty() ? 0 : $rs->{$this->f_id};
+		$rs = $this->getParents($nodeB);
+		$parentB = $rs->isEmpty() ? 0 : $rs->{$this->f_id};
+		
+		if ($parentA != $parentB) {
+			throw new Exception('Cannot change position');
+		}
+		
+		if ($position == 'before')
+		{
+			if ($A_left > $B_left) {
+				$sql = 'UPDATE '.$this->table.' SET '
+				. $this->f_right.' = CASE WHEN '.$this->f_left.' BETWEEN '.$A_left.' AND '.$A_right.' THEN '.$this->f_right.' - ('.($A_left - $B_left).') '
+				. 'WHEN '.$this->f_left.' BETWEEN '.$B_left.' AND '.($A_left - 1).' THEN '.$this->f_right.' +  '.($A_right - $A_left + 1).' ELSE '.$this->f_right.' END, '
+				. $this->f_left.' = CASE WHEN '.$this->f_left.' BETWEEN '.$A_left.' AND '.$A_right.' THEN '.$this->f_left.' - ('.($A_left - $B_left).') '
+				. 'WHEN '.$this->f_left.' BETWEEN '.$B_left.' AND '.($A_left - 1).' THEN '.$this->f_left.' + '.($A_right - $A_left + 1).' ELSE '.$this->f_left.' END '
+				. 'WHERE '.$this->f_left.' BETWEEN '.$B_left.' AND '.$A_right;
+			} else {
+				$sql = 'UPDATE '.$this->table.' SET '
+				. $this->f_right.' = CASE WHEN '.$this->f_left.' BETWEEN '.$A_left.' AND '.$A_right.' THEN '.$this->f_right.' + '.(($B_left - $A_left) - ($A_right - $A_left + 1)).' '
+				. 'WHEN '.$this->f_left.' BETWEEN '.($A_right + 1).' AND '.($B_left - 1).' THEN '.$this->f_right.' - ('.(($A_right - $A_left + 1)).') ELSE '.$this->f_right.' END, '
+				. $this->f_left.' = CASE WHEN '.$this->f_left.' BETWEEN '.$A_left.' AND '.$A_right.' THEN '.$this->f_left.' + '.(($B_left - $A_left) - ($A_right - $A_left + 1)).' '
+				. 'WHEN '.$this->f_left.' BETWEEN '.($A_right + 1).' AND '.($B_left - 1).' THEN '.$this->f_left.' - ('.($A_right - $A_left + 1).') ELSE '.$this->f_left.' END '
+				. 'WHERE '.$this->f_left.' BETWEEN '.$A_left.' AND '.($B_left - 1);
+			}
+		}
+		else
+		{
+			if ($A_left > $B_left) {
+				$sql = 'UPDATE '.$this->table.' SET '
+				. $this->f_right.' = CASE WHEN '.$this->f_left.' BETWEEN '.$A_left.' AND '.$A_right.' THEN '.$this->f_right.' - ('.($A_left - $B_left - ($B_right - $B_left + 1)).') '
+				. 'WHEN '.$this->f_left.' BETWEEN '.($B_right + 1).' AND '.($A_left - 1).' THEN '.$this->f_right.' +  '.($A_right - $A_left + 1).' ELSE '.$this->f_right.' END, '
+				. $this->f_left.' = CASE WHEN '.$this->f_left.' BETWEEN '.$A_left.' AND '.$A_right.' THEN '.$this->f_left.' - ('.($A_left - $B_left - ($B_right - $B_left + 1)).') '
+				. 'WHEN '.$this->f_left.' BETWEEN '.($B_right + 1).' AND '.($A_left - 1).' THEN '.$this->f_left.' + '.($A_right - $A_left + 1).' ELSE '.$this->f_left.' END '
+				. 'WHERE '.$this->f_left.' BETWEEN '.($B_right + 1).' AND '.$A_right;
+			} else {
+				$sql = 'UPDATE '.$this->table.' SET '
+				. $this->f_right.' = CASE WHEN '.$this->f_left.' BETWEEN '.$A_left.' AND '.$A_right.' THEN '.$this->f_right.' + '.($B_right - $A_right).' '
+				. 'WHEN '.$this->f_left.' BETWEEN '.($A_right + 1).' AND '.$B_right.' THEN '.$this->f_right.' - ('.(($A_right - $A_left + 1)).') ELSE '.$this->f_right.' END, '
+				. $this->f_left.' = CASE WHEN '.$this->f_left.' BETWEEN '.$A_left.' AND '.$A_right.' THEN '.$this->f_left.' + '.($B_right - $A_right).' '
+				. 'WHEN '.$this->f_left.' BETWEEN '.($A_right + 1).' AND '.$B_right.' THEN '.$this->f_left.' - ('.($A_right - $A_left + 1).') ELSE '.$this->f_left.' END '
+				. 'WHERE '.$this->f_left.' BETWEEN '.$A_left.' AND '.$B_right;
+			}
+		}
+		
+		$sql .= $this->getCondition();
+		$this->con->execute($sql);
+	}
+	
+	protected function getCondition($start='AND',$prefix='')
+	{
+		if (empty($this->add_condition)) {
+			return '';
+		}
+		
+		$w = array();
+		foreach ($this->add_condition as $c => $n) {
+			$w[] = $prefix.$c.' = '.$n;
+		}
+		return ' '.$start.' '.implode(' AND ',$w).' ';
+	}
+}
+?>
Index: inc/core/class.dc.core.php
===================================================================
--- inc/core/class.dc.core.php	(revision 873)
+++ inc/core/class.dc.core.php	(revision 706)
@@ -35,4 +35,6 @@
 	public $wiki2xhtml;	///< <b>wiki2xhtml</b>		wiki2xhtml object
 	public $plugins;	///< <b>dcModules</b>		dcModules object
+	public $media;		///< <b>dcMedia</b>			dcMedia object
+	public $postmedia;	///< <b>dcPostMedia</b>		dcPostMedia object
 	public $rest;		///< <b>dcRestServer</b>	dcRestServer object
 	public $log;		///< <b>dcLog</b>			dcLog object
@@ -371,8 +373,8 @@
 		{
 			$strReq = 'SELECT module, version FROM '.$this->prefix.'version';
-			$modules = $this->con->select($strReq);
+			$rs = $this->con->select($strReq);
 			
-			foreach ($modules as $m) {
-				$this->versions[$m->module] = $m->version;
+			while ($rs->fetch()) {
+				$this->versions[$rs->module] = $rs->version;
 			}
 		}
@@ -506,7 +508,7 @@
 		}
 		
-		$users = $this->con->select($strReq);
-		$users->extend('rsExtUser');
-		return $users;
+		$rs = $this->con->select($strReq);
+		$rs->extend('rsExtUser');
+		return $rs;
 	}
 	
@@ -569,11 +571,11 @@
 		
 		# Updating all user's blogs
-		$blogs = $this->con->select(
+		$rs = $this->con->select(
 			'SELECT DISTINCT(blog_id) FROM '.$this->prefix.'post '.
 			"WHERE user_id = '".$this->con->escape($id)."' "
 			);
 		
-		foreach ($blogs as $blog) {
-			$b = new dcBlog($this,$blog->blog_id);
+		while ($rs->fetch()) {
+			$b = new dcBlog($this,$rs->blog_id);
 			$b->triggerBlog();
 			unset($b);
@@ -598,7 +600,7 @@
 		}
 		
-		$user = $this->getUser($id);
-		
-		if ($user->nb_post > 0) {
+		$rs = $this->getUser($id);
+		
+		if ($rs->nb_post > 0) {
 			return;
 		}
@@ -624,7 +626,7 @@
 				"WHERE user_id = '".$this->con->escape($id)."' ";
 		
-		$users = $this->con->select($strReq);
-		
-		return (count($users) > 0);
+		$rs = $this->con->select($strReq);
+		
+		return !$rs->isEmpty();
 	}
 	
@@ -649,14 +651,14 @@
 				"WHERE user_id = '".$this->con->escape($id)."' ";
 		
-		$blogs = $this->con->select($strReq);
+		$rs = $this->con->select($strReq);
 		
 		$res = array();
 		
-		foreach ($blogs as $blog)
+		while ($rs->fetch())
 		{
-			$res[$blog->blog_id] = array(
-				'name' => $blog->blog_name,
-				'url' => $blog->blog_url,
-				'p' => $this->auth->parsePermissions($blog->permissions)
+			$res[$rs->blog_id] = array(
+				'name' => $rs->blog_name,
+				'url' => $rs->blog_url,
+				'p' => $this->auth->parsePermissions($rs->permissions)
 			);
 		}
@@ -829,16 +831,16 @@
 		}
 		
-		$users = $this->con->select($strReq);
+		$rs = $this->con->select($strReq);
 		
 		$res = array();
 		
-		foreach ($users as $u)
+		while ($rs->fetch())
 		{
-			$res[$u->user_id] = array(
-				'name' => $u->user_name,
-				'firstname' => $u->user_firstname,
-				'displayname' => $u->user_displayname,
-				'super' => (boolean) $u->user_super,
-				'p' => $this->auth->parsePermissions($u->permissions)
+			$res[$rs->user_id] = array(
+				'name' => $rs->user_name,
+				'firstname' => $rs->user_firstname,
+				'displayname' => $rs->user_displayname,
+				'super' => (boolean) $rs->user_super,
+				'p' => $this->auth->parsePermissions($rs->permissions)
 			);
 		}
@@ -1025,7 +1027,7 @@
 				"WHERE blog_id = '".$this->con->escape($id)."' ";
 		
-		$blogs = $this->con->select($strReq);
-		
-		return (count($blogs) > 0);
+		$rs = $this->con->select($strReq);
+		
+		return !$rs->isEmpty();
 	}
 	
@@ -1139,4 +1141,84 @@
 	}
 	
+	/**
+	Inits <var>wiki2xhtml</var> property for simple blog comment (basic syntax).
+	*/
+	public function initWikiSimpleComment()
+	{
+		$this->initWiki();
+		
+		$this->wiki2xhtml->setOpts(array(
+			'active_title' => 0,
+			'active_setext_title' => 0,
+			'active_hr' => 0,
+			'active_lists' => 0,
+			'active_quote' => 0,
+			'active_pre' => 0,
+			'active_empty' => 0,
+			'active_auto_br' => 1,
+			'active_auto_urls' => 1,
+			'active_urls' => 0,
+			'active_auto_img' => 0,
+			'active_img' => 0,
+			'active_anchor' => 0,
+			'active_em' => 0,
+			'active_strong' => 0,
+			'active_br' => 0,
+			'active_q' => 0,
+			'active_code' => 0,
+			'active_acronym' => 0,
+			'active_ins' => 0,
+			'active_del' => 0,
+			'active_footnotes' => 0,
+			'active_wikiwords' => 0,
+			'active_macros' => 0,
+			'parse_pre' => 0,
+			'active_fr_syntax' => 0
+		));
+		
+		# --BEHAVIOR-- coreInitWikiSimpleComment
+		$this->callBehavior('coreInitWikiSimpleComment',$this->wiki2xhtml);
+	}
+	
+	/**
+	Inits <var>wiki2xhtml</var> property for blog comment.
+	*/
+	public function initWikiComment()
+	{
+		$this->initWiki();
+		
+		$this->wiki2xhtml->setOpts(array(
+			'active_title' => 0,
+			'active_setext_title' => 0,
+			'active_hr' => 0,
+			'active_lists' => 1,
+			'active_quote' => 0,
+			'active_pre' => 1,
+			'active_empty' => 0,
+			'active_auto_br' => 1,
+			'active_auto_urls' => 1,
+			'active_urls' => 1,
+			'active_auto_img' => 0,
+			'active_img' => 0,
+			'active_anchor' => 0,
+			'active_em' => 1,
+			'active_strong' => 1,
+			'active_br' => 1,
+			'active_q' => 1,
+			'active_code' => 1,
+			'active_acronym' => 1,
+			'active_ins' => 1,
+			'active_del' => 1,
+			'active_footnotes' => 0,
+			'active_wikiwords' => 0,
+			'active_macros' => 0,
+			'parse_pre' => 0,
+			'active_fr_syntax' => 0
+		));
+		
+		# --BEHAVIOR-- coreInitWikiComment
+		$this->callBehavior('coreInitWikiComment',$this->wiki2xhtml);
+	}
+	
 	public function wikiPostLink($url,$content)
 	{
@@ -1187,6 +1269,16 @@
 		{
 			$defaults = array(
+				array('allow_comments','boolean',true,
+				'Allow comments on blog'),
+				array('allow_trackbacks','boolean',true,
+				'Allow trackbacks on blog'),
 				array('blog_timezone','string','Europe/London',
 				'Blog timezone'),
+				array('comments_nofollow','boolean',true,
+				'Add rel="nofollow" to comments URLs'),
+				array('comments_pub','boolean',true,
+				'Publish comments immediately'),
+				array('comments_ttl','integer',0,
+				'Number of days to keep comments open (0 means no ttl)'),
 				array('copyright_notice','string','','Copyright notice (simple text)'),
 				array('date_format','string','%A, %B %e %Y',
@@ -1200,8 +1292,20 @@
 				array('lang','string','en',
 				'Default blog language'),
+				array('media_exclusion','string','/\.php$/i',
+				'File name exclusion pattern in media manager. (PCRE value)'),
+				array('media_img_m_size','integer',448,
+				'Image medium size in media manager'),
+				array('media_img_s_size','integer',240,
+				'Image small size in media manager'),
+				array('media_img_t_size','integer',100,
+				'Image thumbnail size in media manager'),
+				array('media_img_title_pattern','string','Title ;; Date(%b %Y) ;; separator(, )',
+				'Pattern to set image title when you insert it in a post'),
 				array('nb_post_per_page','integer',20,
 				'Number of entries on home page and category pages'),
 				array('nb_post_per_feed','integer',20,
 				'Number of entries on feeds'),
+				array('nb_comment_per_feed','integer',20,
+				'Number of comments on feeds'),
 				array('post_url_format','string','{y}/{m}/{d}/{t}',
 				'Post URL format. {y}: year, {m}: month, {d}: day, {id}: post id, {t}: entry title'),
@@ -1226,8 +1330,14 @@
 				array('tpl_use_cache','boolean',true,
 				'Use template caching'),
+				array('trackbacks_pub','boolean',true,
+				'Publish trackbacks immediately'),
+				array('trackbacks_ttl','integer',0,
+				'Number of days to keep trackbacks open (0 means no ttl)'),
 				array('url_scan','string','query_string',
 				'URL handle mode (path_info or query_string)'),
 				array('use_smilies','boolean',false,
 				'Show smilies on entries and comments'),
+				array('wiki_comments','boolean',false,
+				'Allow commenters to use a subset of wiki syntax')
 			);
 		}
@@ -1253,7 +1363,6 @@
 		$strReq = 'SELECT COUNT(post_id) '.
 				'FROM '.$this->prefix.'post';
-		$count = $this->con->select($strReq);
-		$count = $count->current();
-		$count = $count->f(0);
+		$rs = $this->con->select($strReq);
+		$count = $rs->f(0);
 		
 		$strReq = 'SELECT post_id, post_title, post_excerpt_xhtml, post_content_xhtml '.
@@ -1264,15 +1373,15 @@
 		}
 		
-		$posts = $this->con->select($strReq,true);
+		$rs = $this->con->select($strReq,true);
 		
 		$cur = $this->con->openCursor($this->prefix.'post');
 		
-		foreach ($posts as $post)
+		while ($rs->fetch())
 		{
-			$words = $post->post_title.' '.	$post->post_excerpt_xhtml.' '.
-			$post->post_content_xhtml;
+			$words = $rs->post_title.' '.	$rs->post_excerpt_xhtml.' '.
+			$rs->post_content_xhtml;
 			
 			$cur->post_words = implode(' ',text::splitWords($words));
-			$cur->update('WHERE post_id = '.(integer) $post->post_id);
+			$cur->update('WHERE post_id = '.(integer) $rs->post_id);
 			$cur->clean();
 		}
@@ -1282,4 +1391,65 @@
 		}
 		return $start+$limit;
+	}
+	
+	/**
+	Recreates comments search engine index.
+	
+	@param	start	<b>integer</b>		Start comment index
+	@param	limit	<b>integer</b>		Number of comments to index
+	
+	@return	<b>integer</b>		<var>$start</var> and <var>$limit</var> sum
+	*/
+	public function indexAllComments($start=null,$limit=null)
+	{
+		$strReq = 'SELECT COUNT(comment_id) '.
+				'FROM '.$this->prefix.'comment';
+		$rs = $this->con->select($strReq);
+		$count = $rs->f(0);
+		
+		$strReq = 'SELECT comment_id, comment_content '.
+				'FROM '.$this->prefix.'comment ';
+		
+		if ($start !== null && $limit !== null) {
+			$strReq .= $this->con->limit($start,$limit);
+		}
+		
+		$rs = $this->con->select($strReq);
+		
+		$cur = $this->con->openCursor($this->prefix.'comment');
+		
+		while ($rs->fetch())
+		{
+			$cur->comment_words = implode(' ',text::splitWords($rs->comment_content));
+			$cur->update('WHERE comment_id = '.(integer) $rs->comment_id);
+			$cur->clean();
+		}
+		
+		if ($start+$limit > $count) {
+			return null;
+		}
+		return $start+$limit;
+	}
+	
+	/**
+	Reinits nb_comment and nb_trackback in post table.
+	*/
+	public function countAllComments()
+	{
+	
+		$updCommentReq = 'UPDATE '.$this->prefix.'post P '.
+			'SET nb_comment = ('.
+				'SELECT COUNT(C.comment_id) from '.$this->prefix.'comment C '.
+				'WHERE C.post_id = P.post_id AND C.comment_trackback <> 1 '.
+				'AND C.comment_status = 1 '.
+			')';
+		$updTrackbackReq = 'UPDATE '.$this->prefix.'post P '.
+			'SET nb_trackback = ('.
+				'SELECT COUNT(C.comment_id) from '.$this->prefix.'comment C '.
+				'WHERE C.post_id = P.post_id AND C.comment_trackback = 1 '.
+				'AND C.comment_status = 1 '.
+			')';
+		$this->con->execute($updCommentReq);
+		$this->con->execute($updTrackbackReq);
 	}
 	
Index: inc/core/class.dc.media.php
===================================================================
--- inc/core/class.dc.media.php	(revision 909)
+++ inc/core/class.dc.media.php	(revision 909)
@@ -0,0 +1,1094 @@
+<?php
+# -- BEGIN LICENSE BLOCK ---------------------------------------
+#
+# This file is part of Dotclear 2.
+#
+# Copyright (c) 2003-2011 Olivier Meunier & Association Dotclear
+# Licensed under the GPL version 2.0 license.
+# See LICENSE file or
+# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
+#
+# -- END LICENSE BLOCK -----------------------------------------
+if (!defined('DC_RC_PATH')) { return; }
+
+/**
+@ingroup DC_CORE
+@brief Dotclear media manage
+
+This class handles Dotclear media items.
+*/
+class dcMedia extends filemanager
+{
+	protected $core;		///< <b>dcCore</b> dcCore instance
+	protected $con;		///< <b>connection</b> Database connection
+	protected $table;		///< <b>string</b> Media table name
+	protected $type;		///< <b>string</b> Media type filter
+	protected $postmedia;
+	protected $file_sort = 'name-asc';
+	
+	protected $file_handler = array();	///< <b>array</b> Array of callbacks
+	
+	public $thumb_tp = '%s/.%s_%s.jpg';	///< <b>string</b> Thumbnail file pattern
+	
+	/**
+	<b>array</b> Tubmnail sizes:
+	- m: medium image
+	- s: small image
+	- t: thumbnail image
+	- sq: square image
+	*/
+	public $thumb_sizes = array(	
+		'm' => array(448,'ratio','medium'),
+		's' => array(240,'ratio','small'),
+		't' => array(100,'ratio','thumbnail'),
+		'sq' => array(48,'crop','square')
+	);
+	
+	public $icon_img = 'images/media/%s.png';	///< <b>string</b> Icon file pattern
+	
+	/**
+	Object constructor.
+	
+	@param	core		<b>dcCore</b>		dcCore instance
+	@param	type		<b>string</b>		Media type filter
+	*/
+	public function __construct($core,$type='')
+	{
+		$this->core =& $core;
+		$this->con =& $core->con;
+		$this->postmedia = new dcPostMedia($core);
+		
+		if ($this->core->blog == null) {
+			throw new Exception(__('No blog defined.'));
+		}
+		
+		$this->table = $this->core->prefix.'media';
+		$root = $this->core->blog->public_path;
+		
+		if (preg_match('#^http(s)?://#',$this->core->blog->settings->system->public_url)) {
+			$root_url = rawurldecode($this->core->blog->settings->system->public_url);
+		} else {
+			$root_url = rawurldecode($this->core->blog->host.path::clean($this->core->blog->settings->system->public_url));
+		}
+		
+		if (!is_dir($root)) {
+			throw new Exception(sprintf(__('Directory %s does not exist.'),$root));
+		}
+		
+		$this->type = $type;
+		
+		parent::__construct($root,$root_url);
+		$this->chdir('');
+		
+		$this->path = $this->core->blog->settings->system->public_path;
+		
+		$this->addExclusion(DC_RC_PATH);
+		$this->addExclusion(dirname(__FILE__).'/../');
+		
+		$this->exclude_pattern = $core->blog->settings->system->media_exclusion;
+		
+		# Event handlers
+		$this->addFileHandler('image/jpeg','create',array($this,'imageThumbCreate'));
+		$this->addFileHandler('image/png','create',array($this,'imageThumbCreate'));
+		$this->addFileHandler('image/gif','create',array($this,'imageThumbCreate'));
+		
+		$this->addFileHandler('image/png','update',array($this,'imageThumbUpdate'));
+		$this->addFileHandler('image/jpeg','update',array($this,'imageThumbUpdate'));
+		$this->addFileHandler('image/gif','update',array($this,'imageThumbUpdate'));
+		
+		$this->addFileHandler('image/png','remove',array($this,'imageThumbRemove'));
+		$this->addFileHandler('image/jpeg','remove',array($this,'imageThumbRemove'));
+		$this->addFileHandler('image/gif','remove',array($this,'imageThumbRemove'));
+		
+		$this->addFileHandler('image/jpeg','create',array($this,'imageMetaCreate'));
+		
+		$this->addFileHandler('image/jpeg','recreate',array($this,'imageThumbCreate'));
+		$this->addFileHandler('image/png','recreate',array($this,'imageThumbCreate'));
+		$this->addFileHandler('image/gif','recreate',array($this,'imageThumbCreate'));
+		
+		$this->addFileHandler('image/jpeg','recreate',array($this,'imageThumbCreate'));
+		$this->addFileHandler('image/png','recreate',array($this,'imageThumbCreate'));
+		$this->addFileHandler('image/gif','recreate',array($this,'imageThumbCreate'));
+		
+		# Thumbnails sizes
+		$this->thumb_sizes['m'][0] = abs($core->blog->settings->system->media_img_m_size);
+		$this->thumb_sizes['s'][0] = abs($core->blog->settings->system->media_img_s_size);
+		$this->thumb_sizes['t'][0] = abs($core->blog->settings->system->media_img_t_size);
+		
+		# Thumbnails sizes names
+		$this->thumb_sizes['m'][2] = __($this->thumb_sizes['m'][2]);
+		$this->thumb_sizes['s'][2] = __($this->thumb_sizes['s'][2]);
+		$this->thumb_sizes['t'][2] = __($this->thumb_sizes['t'][2]);
+		$this->thumb_sizes['sq'][2] = __($this->thumb_sizes['sq'][2]);
+		
+		# --BEHAVIOR-- coreMediaConstruct
+		$this->core->callBehavior('coreMediaConstruct',$this);	
+	}
+	
+	/**
+	Changes working directory.
+	
+	@param	dir		<b>string</b>		Directory name.
+	*/
+	public function chdir($dir)
+	{
+		parent::chdir($dir);
+		$this->relpwd = preg_replace('/^'.preg_quote($this->root,'/').'\/?/','',$this->pwd);
+	}
+	
+	/**
+	Adds a new file handler for a given media type and event.
+	
+	Available events are:
+	- create: file creation
+	- update: file update
+	- remove: file deletion
+	
+	@param	type		<b>string</b>		Media type
+	@param	event	<b>string</b>		Event
+	@param	function	<b>callback</b>
+	*/
+	public function addFileHandler($type,$event,$function)
+	{
+		if (is_callable($function)) {
+			$this->file_handler[$type][$event][] = $function;
+		}
+	}
+	
+	protected function callFileHandler($type,$event)
+	{
+		if (!empty($this->file_handler[$type][$event]))
+		{
+			$args = func_get_args();
+			array_shift($args);
+			array_shift($args);
+			
+			foreach ($this->file_handler[$type][$event] as $f)
+			{
+				call_user_func_array($f,$args);
+			}
+		}
+	}
+	
+	/**
+	Returns HTML breadCrumb for media manager navigation.
+	
+	@param	href		<b>string</b>		URL pattern
+	@param	last		<b>string</b>		Last item pattern
+	@return	<b>string</b> HTML code
+	*/
+	public function breadCrumb($href,$last='')
+	{
+		$res = '';
+		if ($this->relpwd && $this->relpwd != '.') {
+			$pwd = '';
+			$arr = explode('/',$this->relpwd);
+			$count = count($arr);
+			foreach ($arr as $v) {
+				if (($last != '') && (0 === --$count)) {
+					$res .= sprintf($last,$v);
+				} else {
+					$pwd .= rawurlencode($v).'/';
+					$res .= '<a href="'.sprintf($href,$pwd).'">'.$v.'</a> / ';
+				}
+			}
+		}
+		return $res;
+		
+	}
+	
+	protected function fileRecord($rs)
+	{
+		if ($rs->isEmpty()) { return null; }
+		
+		if (!$this->isFileExclude($this->root.'/'.$rs->media_file) && is_file($this->root.'/'.$rs->media_file))
+		{
+			$f = new fileItem($this->root.'/'.$rs->media_file,$this->root,$this->root_url);
+			
+			if ($this->type && $f->type_prefix != $this->type) {
+				return null;
+			}
+			
+			$meta = @simplexml_load_string($rs->media_meta);
+			
+			$f->editable = true;
+			$f->media_id = $rs->media_id;
+			$f->media_title = $rs->media_title;
+			$f->media_meta =  $meta instanceof SimpleXMLElement ? $meta : simplexml_load_string('<meta></meta>');
+			$f->media_user = $rs->user_id;
+			$f->media_priv = (boolean) $rs->media_private;
+			$f->media_dt = strtotime($rs->media_dt);
+			$f->media_dtstr = dt::str('%Y-%m-%d %H:%M',$f->media_dt);
+			
+			$f->media_image = false;
+			
+			if (!$this->core->auth->check('media_admin',$this->core->blog->id)
+			&& $this->core->auth->userID() != $f->media_user) {
+				$f->del = false;
+				$f->editable = false;
+			}
+			
+			$type_prefix = explode('/',$f->type);
+			$type_prefix = $type_prefix[0];
+			
+			switch ($type_prefix) {
+				case 'image':
+					$f->media_image = true;
+					$f->media_icon = 'image';
+					break;
+				case 'audio':
+					$f->media_icon = 'audio';
+					break;
+				case 'text':
+					$f->media_icon = 'text';
+					break;
+				case 'video':
+					$f->media_icon = 'video';
+					break;
+				default:
+					$f->media_icon = 'blank';
+			}
+			switch ($f->type) {
+				case 'application/msword':
+				case 'application/vnd.oasis.opendocument.text':
+				case 'application/vnd.sun.xml.writer':
+				case 'application/pdf':
+				case 'application/postscript':
+					$f->media_icon = 'document';
+					break;
+				case 'application/msexcel':
+				case 'application/vnd.oasis.opendocument.spreadsheet':
+				case 'application/vnd.sun.xml.calc':
+					$f->media_icon = 'spreadsheet';
+					break;
+				case 'application/mspowerpoint':
+				case 'application/vnd.oasis.opendocument.presentation':
+				case 'application/vnd.sun.xml.impress':
+					$f->media_icon = 'presentation';
+					break;
+				case 'application/x-debian-package':
+				case 'application/x-bzip':
+				case 'application/x-gzip':
+				case 'application/x-java-archive':
+				case 'application/rar':
+				case 'application/x-redhat-package-manager':
+				case 'application/x-tar':
+				case 'application/x-gtar':
+				case 'application/zip':
+					$f->media_icon = 'package';
+					break;
+				case 'application/octet-stream':
+					$f->media_icon = 'executable';
+					break;
+				case 'application/x-shockwave-flash':
+					$f->media_icon = 'video';
+					break;
+				case 'application/ogg':
+					$f->media_icon = 'audio';
+					break;
+				case 'text/html':
+					$f->media_icon = 'html';
+					break;
+			}
+			
+			$f->media_type = $f->media_icon;
+			$f->media_icon = sprintf($this->icon_img,$f->media_icon);
+			
+			# Thumbnails
+			$f->media_thumb = array();
+			$p = path::info($f->relname);
+			$thumb = sprintf($this->thumb_tp,$this->root.'/'.$p['dirname'],$p['base'],'%s');
+			$thumb_url = sprintf($this->thumb_tp,$this->root_url.$p['dirname'],$p['base'],'%s');
+			
+			# Cleaner URLs
+			$thumb_url = preg_replace('#\./#','/',$thumb_url);
+			$thumb_url = preg_replace('#(?<!:)/+#','/',$thumb_url);
+			
+			foreach ($this->thumb_sizes as $suffix => $s) {
+				if (file_exists(sprintf($thumb,$suffix))) {
+					$f->media_thumb[$suffix] = sprintf($thumb_url,$suffix);
+				}
+			}
+			
+			if (isset($f->media_thumb['sq']) && $f->media_type == 'image') {
+				$f->media_icon = $f->media_thumb['sq'];
+			}
+			
+			return $f;
+		}
+		
+		return null;
+	}
+	
+	
+	public function setFileSort($type='name')
+	{
+		if (in_array($type,array('name-asc','name-desc','date-asc','date-desc'))) {
+			$this->file_sort = $type;
+		}
+	}
+	
+	protected function sortFileHandler($a,$b)
+	{
+		switch ($this->file_sort)
+		{
+			case 'date-asc':
+				if ($a->media_dt == $b->media_dt) {
+					return 0;
+				}
+				return ($a->media_dt < $b->media_dt) ? -1 : 1;
+			case 'date-desc':
+				if ($a->media_dt == $b->media_dt) {
+					return 0;
+				}
+				return ($a->media_dt > $b->media_dt) ? -1 : 1;
+			case 'name-desc':
+				return strcasecmp($b->basename,$a->basename);
+			case 'name-asc':
+			default:
+				return strcasecmp($a->basename,$b->basename);
+		}
+		
+	}
+	
+	/**
+	Gets current working directory content. 
+	
+	@param	type		<b>string</b>		Media type filter
+	*/
+	public function getDir($type=null)
+	{
+		if ($type) {
+			$this->type = $type;
+		}
+		
+		$media_dir = $this->relpwd ? $this->relpwd : '.';
+		
+		$strReq =
+		'SELECT media_file, media_id, media_path, media_title, media_meta, media_dt, '.
+		'media_creadt, media_upddt, media_private, user_id '.
+		'FROM '.$this->table.' '.
+		"WHERE media_path = '".$this->path."' ".
+		"AND media_dir = '".$this->con->escape($media_dir)."' ";
+		
+		if (!$this->core->auth->check('media_admin',$this->core->blog->id))
+		{
+			$strReq .= 'AND (media_private <> 1 ';
+			
+			if ($this->core->auth->userID()) {
+				$strReq .= "OR user_id = '".$this->con->escape($this->core->auth->userID())."'";
+			}
+			$strReq .= ') ';
+		}
+		
+		$rs = $this->con->select($strReq);
+		
+		parent::getDir();
+		
+		$f_res = array();
+		$p_dir = $this->dir;
+		
+		# If type is set, remove items from p_dir
+		if ($this->type)
+		{
+			foreach ($p_dir['files'] as $k => $f) {
+				if ($f->type_prefix != $this->type) {
+					unset($p_dir['files'][$k]);
+				}
+			}
+		}
+		
+		$f_reg = array();
+		
+		while ($rs->fetch())
+		{
+			# File in subdirectory, forget about it!
+			if (dirname($rs->media_file) != '.' && dirname($rs->media_file) != $this->relpwd) {
+				continue;
+			}
+			
+			if ($this->inFiles($rs->media_file))
+			{
+				$f = $this->fileRecord($rs);
+				if ($f !== null) {
+					if (isset($f_reg[$rs->media_file]))
+					{
+						# That media is duplicated in the database, 
+						# time to do a bit of house cleaning.
+						$this->con->execute(
+							'DELETE FROM '.$this->table.' '.
+							"WHERE media_id = ".$this->fileRecord($rs)->media_id
+						);
+					} else {
+						$f_res[] = $this->fileRecord($rs);
+						$f_reg[$rs->media_file] = 1;
+					}
+				}
+			}
+			elseif (!empty($p_dir['files']) && $this->relpwd == '')
+			{
+				# Physical file does not exist remove it from DB
+				# Because we don't want to erase everything on
+				# dotclear upgrade, do it only if there are files
+				# in directory and directory is root
+				$this->con->execute(
+					'DELETE FROM '.$this->table.' '.
+					"WHERE media_path = '".$this->con->escape($this->path)."' ".
+					"AND media_file = '".$this->con->escape($rs->media_file)."' "
+				);
+				$this->callFileHandler(files::getMimeType($rs->media_file),'remove',$this->pwd.'/'.$rs->media_file);
+			}
+		}
+		
+		$this->dir['files'] = $f_res;
+		foreach ($this->dir['dirs'] as $k => $v) {
+			$v->media_icon = sprintf($this->icon_img,'folder');
+		}
+		
+		# Check files that don't exist in database and create them
+		if ($this->core->auth->check('media,media_admin',$this->core->blog->id))
+		{
+			foreach ($p_dir['files'] as $f)
+			{
+				if (!isset($f_reg[$f->relname])) {
+					if (($id = $this->createFile($f->basename,null,false,null,false)) !== false) {
+						$this->dir['files'][] = $this->getFile($id);
+					}
+				}
+			}
+		}
+		usort($this->dir['files'],array($this,'sortFileHandler'));
+	}
+	
+	/**
+	Gets file by its id. Returns a filteItem object.
+	
+	@param	id		<b>integer</b>		File ID
+	@return	<b>fileItem</b>
+	*/
+	public function getFile($id)
+	{
+		$strReq =
+		'SELECT media_id, media_path, media_title, '.
+		'media_file, media_meta, media_dt, media_creadt, '.
+		'media_upddt, media_private, user_id '.
+		'FROM '.$this->table.' '.
+		"WHERE media_path = '".$this->path."' ".
+		'AND media_id = '.(integer) $id.' ';
+		
+		if (!$this->core->auth->check('media_admin',$this->core->blog->id))
+		{
+			$strReq .= 'AND (media_private <> 1 ';
+			
+			if ($this->core->auth->userID()) {
+				$strReq .= "OR user_id = '".$this->con->escape($this->core->auth->userID())."'";
+			}
+			$strReq .= ') ';
+		}
+		
+		$rs = $this->con->select($strReq);
+		return $this->fileRecord($rs);
+	}
+	
+	/**
+	Returns media items attached to a blog post. Result is an array containing
+	fileItems objects.
+	
+	@param	post_id	<b>integer</b>		Post ID
+	@param	media_id	<b>integer</b>		Optionnal media ID
+	@return	<b>array</b> Array of fileItems
+	*/
+	public function getPostMedia($post_id,$media_id=null)
+	{
+		$params = array(
+			'post_id' => $post_id,
+			'media_path' => $this->path
+		);
+		if ($media_id) {
+			$params['media_id'] = (integer) $media_id;
+		}
+		$rs = $this->postmedia->getPostMedia($params);
+		
+		$res = array();
+		
+		while ($rs->fetch()) {
+			$f = $this->fileRecord($rs);
+			if ($f !== null) {
+				$res[] = $f;
+			}
+		}
+		
+		return $res;
+	}
+	
+	/**
+	@deprecated since version 2.4
+	@see dcPostMedia::addPostMedia
+	*/
+	public function addPostMedia($post_id,$media_id)
+	{
+		$this->postmedia->addPostMedia($post_id,$media_id);
+	}
+	
+	/**
+	@deprecated since version 2.4
+	@see dcPostMedia::removePostMedia
+	*/
+	public function removePostMedia($post_id,$media_id)
+	{
+		$this->postmedia->removePostMedia($post_id,$media_id,"attachment");
+	}
+	
+	/**
+	Rebuilds database items collection. Optional <var>$pwd</var> parameter is
+	the path where to start rebuild.
+	
+	@param	pwd		<b>string</b>		Directory to rebuild
+	*/
+	public function rebuild($pwd='')
+	{
+		if (!$this->core->auth->isSuperAdmin()) {
+			throw new Exception(__('You are not a super administrator.'));
+		}
+		
+		$this->chdir($pwd);
+		parent::getDir();
+		
+		$dir = $this->dir;
+		
+		foreach ($dir['dirs'] as $d) {
+			if (!$d->parent) {
+				$this->rebuild($d->relname,false);
+			}
+		}
+		
+		foreach ($dir['files'] as $f) {
+			$this->chdir(dirname($f->relname));
+			$this->createFile($f->basename);
+		}
+		
+		$this->rebuildDB($pwd);
+	}
+	
+	protected function rebuildDB($pwd)
+	{
+		$media_dir = $pwd ? $pwd : '.';
+		
+		$strReq =
+		'SELECT media_file, media_id '.
+		'FROM '.$this->table.' '.
+		"WHERE media_path = '".$this->path."' ".
+		"AND media_dir = '".$this->con->escape($media_dir)."' ";
+		
+		$rs = $this->con->select($strReq);
+		
+		$delReq = 'DELETE FROM '.$this->table.' '.
+				'WHERE media_id IN (%s) ';
+		$del_ids = array();
+		
+		while ($rs->fetch())
+		{
+			if (!is_file($this->root.'/'.$rs->media_file)) {
+				$del_ids[] = (integer) $rs->media_id;
+			}
+		}
+		
+		if (!empty($del_ids)) {
+			$this->con->execute(sprintf($delReq,implode(',',$del_ids)));
+		}
+	}
+	
+	public function makeDir($d)
+	{
+		$d = files::tidyFileName($d);
+		parent::makeDir($d);
+	}
+	
+	/**
+	Creates or updates a file in database. Returns new media ID or false if
+	file does not exist.
+	
+	@param	name		<b>string</b>		File name (relative to working directory)
+	@param	title	<b>string</b>		File title
+	@param	private	<b>boolean</b>		File is private
+	@param	dt		<b>string</b>		File date
+	@return	<b>integer</b> New media ID
+	*/
+	public function createFile($name,$title=null,$private=false,$dt=null,$force=true)
+	{
+		if (!$this->core->auth->check('media,media_admin',$this->core->blog->id)) {
+			throw new Exception(__('Permission denied.'));
+		}
+		
+		$file = $this->pwd.'/'.$name;
+		if (!file_exists($file)) {
+			return false;
+		}
+		
+		$media_file = $this->relpwd ? path::clean($this->relpwd.'/'.$name) : path::clean($name);
+		$media_type = files::getMimeType($name);
+		
+		$cur = $this->con->openCursor($this->table);
+		
+		$strReq = 'SELECT media_id '.
+				'FROM '.$this->table.' '.
+				"WHERE media_path = '".$this->con->escape($this->path)."' ".
+				"AND media_file = '".$this->con->escape($media_file)."' ";
+		
+		$rs = $this->con->select($strReq);
+		
+		if ($rs->isEmpty())
+		{
+			$this->con->writeLock($this->table);
+			try
+			{
+				$rs = $this->con->select('SELECT MAX(media_id) FROM '.$this->table);
+				$media_id = (integer) $rs->f(0) + 1;
+				
+				$cur->media_id = $media_id;
+				$cur->user_id = (string) $this->core->auth->userID();
+				$cur->media_path = (string) $this->path;
+				$cur->media_file = (string) $media_file;
+				$cur->media_dir = (string) dirname($media_file);
+				$cur->media_creadt = date('Y-m-d H:i:s');
+				$cur->media_upddt = date('Y-m-d H:i:s');
+				
+				$cur->media_title = !$title ? (string) $name : (string) $title;
+				$cur->media_private = (integer) (boolean) $private;
+				
+				if ($dt) {
+					$cur->media_dt = (string) $dt;
+				} else {
+					$cur->media_dt = strftime('%Y-%m-%d %H:%M:%S',filemtime($file));
+				}
+				
+				try {
+					$cur->insert();
+				} catch (Exception $e) {
+					@unlink($name);
+					throw $e;
+				}
+				$this->con->unlock();
+			}
+			catch (Exception $e)
+			{
+				$this->con->unlock();
+				throw $e;
+			}
+		}
+		else
+		{
+			$media_id = (integer) $rs->media_id;
+			
+			$cur->media_upddt = date('Y-m-d H:i:s');
+			
+			$cur->update('WHERE media_id = '.$media_id);
+		}
+		
+		$this->callFileHandler($media_type,'create',$cur,$name,$media_id,$force);
+		
+		return $media_id;
+	}
+	
+	/**
+	Updates a file in database.
+	
+	@param	file		<b>fileItem</b>	Current fileItem object
+	@param	newFile	<b>fileItem</b>	New fileItem object
+	*/
+	public function updateFile($file,$newFile)
+	{
+		if (!$this->core->auth->check('media,media_admin',$this->core->blog->id)) {
+			throw new Exception(__('Permission denied.'));
+		}
+		
+		$id = (integer) $file->media_id;
+		
+		if (!$id) {
+			throw new Exception('No file ID');
+		}
+		
+		if (!$this->core->auth->check('media_admin',$this->core->blog->id)
+		&& $this->core->auth->userID() != $file->media_user) {
+			throw new Exception(__('You are not the file owner.'));
+		}
+		
+		$cur = $this->con->openCursor($this->table);
+		
+		# We need to tidy newFile basename. If dir isn't empty, concat to basename
+		$newFile->relname = files::tidyFileName($newFile->basename);
+		if ($newFile->dir) {
+			$newFile->relname = $newFile->dir.'/'.$newFile->relname;
+		}
+		
+		if ($file->relname != $newFile->relname) {
+			$newFile->file = $this->root.'/'.$newFile->relname;
+			
+			if ($this->isFileExclude($newFile->relname)) {
+				throw new Exception(__('This file is not allowed.'));
+			}
+			
+			if (file_exists($newFile->file)) {
+				throw new Exception(__('New file already exists.'));
+			}
+			
+			$this->moveFile($file->relname,$newFile->relname);
+			
+			$cur->media_file = (string) $newFile->relname;
+			$cur->media_dir = (string) dirname($newFile->relname);
+		}
+		
+		$cur->media_title = (string) $newFile->media_title;
+		$cur->media_dt = (string) $newFile->media_dtstr;
+		$cur->media_upddt = date('Y-m-d H:i:s');
+		$cur->media_private = (integer) $newFile->media_priv;
+		
+		$cur->update('WHERE media_id = '.$id);
+		
+		$this->callFileHandler($file->type,'update',$file,$newFile);
+	}
+	
+	/**
+	Uploads a file.
+	
+	@param	tmp		<b>string</b>		Full path of temporary uploaded file
+	@param	name		<b>string</b>		File name (relative to working directory)
+	@param	title	<b>string</b>		File title
+	@param	private	<b>boolean</b>		File is private
+	*/
+	public function uploadFile($tmp,$name,$title=null,$private=false,$overwrite=false)
+	{
+		if (!$this->core->auth->check('media,media_admin',$this->core->blog->id)) {
+			throw new Exception(__('Permission denied.'));
+		}
+		
+		$name = files::tidyFileName($name);
+		
+		parent::uploadFile($tmp,$name,$overwrite);
+		
+		return $this->createFile($name,$title,$private);
+	}
+	
+	/**
+	Creates a file from binary content.
+	
+	@param	name		<b>string</b>		File name (relative to working directory)
+	@param	bits		<b>string</b>		Binary file content
+	*/
+	public function uploadBits($name,$bits)
+	{
+		if (!$this->core->auth->check('media,media_admin',$this->core->blog->id)) {
+			throw new Exception(__('Permission denied.'));
+		}
+		
+		$name = files::tidyFileName($name);
+		
+		parent::uploadBits($name,$bits);
+		
+		return $this->createFile($name,null,null);
+	}
+	
+	/**
+	Removes a file.
+	
+	@param	f		<b>fileItem</b>	fileItem object
+	*/
+	public function removeFile($f)
+	{
+		if (!$this->core->auth->check('media,media_admin',$this->core->blog->id)) {
+			throw new Exception(__('Permission denied.'));
+		}
+		
+		$media_file = $this->relpwd ? path::clean($this->relpwd.'/'.$f) : path::clean($f);
+		
+		$strReq = 'DELETE FROM '.$this->table.' '.
+				"WHERE media_path = '".$this->con->escape($this->path)."' ".
+				"AND media_file = '".$this->con->escape($media_file)."' ";
+		
+		if (!$this->core->auth->check('media_admin',$this->core->blog->id))
+		{
+			$strReq .= "AND user_id = '".$this->con->escape($this->core->auth->userID())."'";
+		}
+		
+		$this->con->execute($strReq);
+		
+		if ($this->con->changes() == 0) {
+			throw new Exception(__('File does not exist in the database.'));
+		}
+		
+		parent::removeFile($f);
+		
+		$this->callFileHandler(files::getMimeType($media_file),'remove',$f);
+	}
+	
+	/**
+	Extract zip file in current location
+	
+	@param	f		<b>fileRecord</b>	fileRecord object
+	*/
+	public function inflateZipFile($f,$create_dir=true)
+	{
+		$zip = new fileUnzip($f->file);
+		$zip->setExcludePattern($this->exclude_pattern);
+		$zip->getList(false,'#(^|/)(__MACOSX|\.svn|\.DS_Store|\.directory|Thumbs\.db)(/|$)#');
+		
+		if ($create_dir)
+		{
+			$zip_root_dir = $zip->getRootDir();
+			if ($zip_root_dir != false) {
+				$destination = $zip_root_dir;
+				$target = $f->dir;
+			} else {
+				$destination = preg_replace('/\.([^.]+)$/','',$f->basename);
+				$target = $f->dir.'/'.$destination;
+			}
+			
+			if (is_dir($f->dir.'/'.$destination)) {
+				throw new Exception(sprintf(__('Extract destination directory %s already exists.'),dirname($f->relname).'/'.$destination)); 
+			}
+		}
+		else
+		{
+			$target = $f->dir;
+			$destination = '';
+		}
+		
+		$zip->unzipAll($target);
+		$zip->close();
+		return dirname($f->relname).'/'.$destination;
+	}
+	
+	/**
+	Returns zip file content
+	
+	@param	f		<b>fileRecord</b>	fileRecord object
+	@return <b>array</b>
+	*/
+	public function getZipContent($f)
+	{
+		$zip = new fileUnzip($f->file);
+		$list = $zip->getList(false,'#(^|/)(__MACOSX|\.svn|\.DS_Store|\.directory|Thumbs\.db)(/|$)#');
+		$zip->close();
+		return $list;
+	}
+
+	/**
+	Calls file handlers registered for recreate event
+	
+	@param	f	<b>fileItem</b>	fileItem object
+	*/
+	public function mediaFireRecreateEvent($f)
+	{
+		$media_type = files::getMimeType($f->basename);
+		$this->callFileHandler($media_type,'recreate',null,$f->basename); // Args list to be completed as necessary (Franck)
+	}
+	
+	/* Image handlers
+	------------------------------------------------------- */
+	public function imageThumbCreate($cur,$f,$force=true)
+	{
+		$file = $this->pwd.'/'.$f;
+		
+		if (!file_exists($file)) {
+			return false;
+		}
+		
+		$p = path::info($file);
+		$thumb = sprintf($this->thumb_tp,$p['dirname'],$p['base'],'%s');
+		
+		try
+		{
+			$img = new imageTools();
+			$img->loadImage($file);
+			
+			$w = $img->getW();
+			$h = $img->getH();
+			
+			if ($force) $this->imageThumbRemove($f);
+			
+			foreach ($this->thumb_sizes as $suffix => $s) {
+				$thumb_file = sprintf($thumb,$suffix);
+				if (!file_exists($thumb_file) && $s[0] > 0 &&
+					($suffix == 'sq' || $w > $s[0] || $h > $s[0]))
+				{
+					$rate = ($s[0] < 100 ? 95 : ($s[0] < 600 ? 90 : 85));
+					$img->resize($s[0],$s[0],$s[1]);
+					$img->output('jpeg',$thumb_file,$rate);
+				}
+			}
+			$img->close();
+		}
+		catch (Exception $e)
+		{
+			if ($cur === null) { # Called only if cursor is null (public call)
+				throw $e;
+			}
+		}
+	}
+	
+	protected function imageThumbUpdate($file,$newFile)
+	{
+		if ($file->relname != $newFile->relname)
+		{
+			$p = path::info($file->relname);
+			$thumb_old = sprintf($this->thumb_tp,$p['dirname'],$p['base'],'%s');
+			
+			$p = path::info($newFile->relname);
+			$thumb_new = sprintf($this->thumb_tp,$p['dirname'],$p['base'],'%s');
+			
+			foreach ($this->thumb_sizes as $suffix => $s) {
+				try {
+					parent::moveFile(sprintf($thumb_old,$suffix),sprintf($thumb_new,$suffix));
+				} catch (Exception $e) {}
+			}
+		}
+	}
+	
+	protected function imageThumbRemove($f)
+	{
+		$p = path::info($f);
+		$thumb = sprintf($this->thumb_tp,'',$p['base'],'%s');
+		
+		foreach ($this->thumb_sizes as $suffix => $s) {
+			try {
+				parent::removeFile(sprintf($thumb,$suffix));
+			} catch (Exception $e) {}
+		}
+	}
+	
+	protected function imageMetaCreate($cur,$f,$id)
+	{
+		$file = $this->pwd.'/'.$f;
+		
+		if (!file_exists($file)) {
+			return false;
+		}
+		
+		$xml = new xmlTag('meta');
+		$meta = imageMeta::readMeta($file);
+		$xml->insertNode($meta);
+		
+		$c = $this->core->con->openCursor($this->table);
+		$c->media_meta = $xml->toXML();
+		
+		if ($cur->media_title !== null && $cur->media_title == basename($cur->media_file))
+		{
+			if ($meta['Title']) {
+				$c->media_title = $meta['Title'];
+			}
+		}
+		
+		if ($meta['DateTimeOriginal'] && $cur->media_dt === '')
+		{
+			# We set picture time to user timezone
+			$media_ts = strtotime($meta['DateTimeOriginal']);
+			if ($media_ts !== false) {
+				$o = dt::getTimeOffset($this->core->auth->getInfo('user_tz'),$media_ts);
+				$c->media_dt = dt::str('%Y-%m-%d %H:%M:%S',$media_ts+$o);
+			}
+		}
+		
+		$c->update('WHERE media_id = '.$id);
+	}
+	
+	/**
+	Returns HTML code for MP3 player
+	
+	@param	url		<b>string</b>		MP3 URL to play
+	@param	player	<b>string</b>		Player URL
+	@param	args		<b>array</b>		Player parameters
+	@return	<b>string</b>
+	*/
+	public static function mp3player($url,$player=null,$args=null)
+	{
+		if (!$player) {
+			$player = 'player_mp3.swf';
+		}
+		
+		if (!is_array($args))
+		{
+			$args = array(
+				'showvolume' => 1,
+				'loadingcolor' => 'ff9900',
+				'bgcolor1' => 'eeeeee',
+				'bgcolor2' => 'cccccc',
+				'buttoncolor' => '0066cc',
+				'buttonovercolor' => 'ff9900',
+				'slidercolor1' => 'cccccc',
+				'slidercolor2' => '999999',
+				'sliderovercolor' => '0066cc'
+			);
+		}
+		
+		$args['mp3'] = $url;
+		
+		if (empty($args['width'])) {
+			$args['width'] = 200;
+		}
+		if (empty($args['height'])) {
+			$args['height'] = 20;
+		}
+		
+		$vars = array();
+		foreach ($args as $k => $v) {
+			$vars[] = $k.'='.$v;
+		}
+		
+		return
+		'<object type="application/x-shockwave-flash" '.
+		'data="'.$player.'" '.
+		'width="'.$args['width'].'" height="'.$args['height'].'">'.
+		'<param name="movie" value="'.$player.'" />'.
+		'<param name="wmode" value="transparent" />'.
+		'<param name="FlashVars" value="'.implode('&amp;',$vars).'" />'.
+		__('Embedded Audio Player').
+		'</object>';
+	}
+	
+	public static function flvplayer($url,$player=null,$args=null)
+	{
+		if (!$player) {
+			$player = 'player_flv.swf';
+		}
+		
+		if (!is_array($args))
+		{
+			$args = array(
+				'margin' => 1,
+				'showvolume' => 1,
+				'showtime' => 1,
+				'showfullscreen' => 1,
+				'buttonovercolor' => 'ff9900',
+				'slidercolor1' => 'cccccc',
+				'slidercolor2' => '999999',
+				'sliderovercolor' => '0066cc'
+			);
+		}
+		
+		$args['flv'] = $url;
+		
+		if (empty($args['width'])) {
+			$args['width'] = 400;
+		}
+		if (empty($args['height'])) {
+			$args['height'] = 300;
+		}
+		
+		$vars = array();
+		foreach ($args as $k => $v) {
+			$vars[] = $k.'='.$v;
+		}
+		
+		return
+		'<object type="application/x-shockwave-flash" '.
+		'data="'.$player.'" '.
+		'width="'.$args['width'].'" height="'.$args['height'].'">'.
+		'<param name="movie" value="'.$player.'" />'.
+		'<param name="wmode" value="transparent" />'.
+		'<param name="allowFullScreen" value="true" />'.
+		'<param name="FlashVars" value="'.implode('&amp;',$vars).'" />'.
+		__('Embedded Video Player').
+		'</object>';
+	}
+}
+?>
Index: inc/core/class.dc.meta.php
===================================================================
--- inc/core/class.dc.meta.php	(revision 877)
+++ inc/core/class.dc.meta.php	(revision 270)
@@ -198,9 +198,9 @@
 				'WHERE post_id = '.$post_id.' ';
 		
-		$rsmeta = $this->con->select($strReq);
+		$rs = $this->con->select($strReq);
 		
 		$meta = array();
-		foreach ($rsmeta as $r) {
-			$meta[$r->meta_type][] = $r->meta_id;
+		while ($rs->fetch()) {
+			$meta[$rs->meta_type][] = $rs->meta_id;
 		}
 		
@@ -244,4 +244,33 @@
 		
 		return $this->core->blog->getPosts($params,$count_only);
+	}
+	
+	/**
+	Retrieves comments to posts corresponding to given meta criteria.
+	<b>$params</b> is an array taking the following optional parameters:
+	- meta_id : get comments to posts having meta id 
+	- meta_type : get comments to posts having meta type
+	
+	@param	params	<b>array</b>	Parameters
+	@param	count_only	<b>boolean</b>		Only counts results
+	
+	@return	<b>record</b>	the resulting comments record
+	*/
+	public function getCommentsByMeta($params=array(),$count_only=false)
+	{
+		if (!isset($params['meta_id'])) {
+			return null;
+		}
+		
+		$params['from'] = ', '.$this->table.' META ';
+		$params['sql'] = 'AND META.post_id = P.post_id ';
+		$params['sql'] .= "AND META.meta_id = '".$this->con->escape($params['meta_id'])."' ";
+		
+		if (!empty($params['meta_type'])) {
+			$params['sql'] .= "AND META.meta_type = '".$this->con->escape($params['meta_type'])."' ";
+			unset($params['meta_type']);
+		}
+		
+		return $this->core->blog->getComments($params,$count_only);
 	}
 	
@@ -271,6 +300,6 @@
 		if ($meta_id != null)
 			$params['post_id'] = $post_id;
-		$meta = $this->getMetadata($params, false);
-		return $this->computeMetaStats($meta);
+		$rs = $this->getMetadata($params, false);
+		return $this->computeMetaStats($rs);
 	}
 	
@@ -317,5 +346,10 @@
 		
 		if (!$this->core->auth->check('contentadmin',$this->core->blog->id)) {
-			$strReq .= 'AND ((post_status = 1) ';
+			$strReq .= 'AND ((post_status = 1 ';
+			
+			if ($this->core->blog->without_password) {
+				$strReq .= 'AND post_password IS NULL ';
+			}
+			$strReq .= ') ';
 			
 			if ($this->core->auth->userID()) {
@@ -340,6 +374,6 @@
 		}
 		
-		$meta = $this->con->select($strReq);
-		return $meta;
+		$rs = $this->con->select($strReq);
+		return $rs;
 	}
 	
@@ -352,32 +386,32 @@
 	@return	<b>record</b>	the enriched recordset
 	*/
-	public function computeMetaStats($meta) {
-		$meta_static = $meta->toStatic();
+	public function computeMetaStats($rs) {
+		$rs_static = $rs->toStatic();
 		
 		$max = array();
-		foreach ($meta_static as $m)
+		while ($rs_static->fetch())
 		{
-			$type = $m->meta_type;
+			$type = $rs_static->meta_type;
 			if (!isset($max[$type])) {
-				$max[$type] = $m->count;
+				$max[$type] = $rs_static->count;
 			} else {
-				if ($m->count > $max[$type]) {
-					$max[$type] = $m->count;
+				if ($rs_static->count > $max[$type]) {
+					$max[$type] = $rs_static->count;
 				}
 			}
 		}
 		
-		foreach ($meta_static as $m)
+		while ($rs_static->fetch())
 		{
-			$m->set('meta_id_lower',mb_strtolower($m->meta_id));
-			
-			$count = $m->count;
-			$percent = ((integer) $m->count) * 100 / $max[$m->meta_type];
-			
-			$m->set('percent',(integer) round($percent));
-			$m->set('roundpercent',round($percent/10)*10);
-		}
-		
-		return $meta_static;
+			$rs_static->set('meta_id_lower',mb_strtolower($rs_static->meta_id));
+			
+			$count = $rs_static->count;
+			$percent = ((integer) $rs_static->count) * 100 / $max[$rs_static->meta_type];
+			
+			$rs_static->set('percent',(integer) round($percent));
+			$rs_static->set('roundpercent',round($percent/10)*10);
+		}
+		
+		return $rs_static;
 	}
 	
@@ -482,9 +516,9 @@
 		$to_update = $to_remove = array();
 		
-		$meta = $this->con->select(sprintf($getReq,$this->con->escape($meta_id),
+		$rs = $this->con->select(sprintf($getReq,$this->con->escape($meta_id),
 							$this->con->escape($type)));
 		
-		foreach ($meta as $m) {
-			$to_update[] = $m->post_id;
+		while ($rs->fetch()) {
+			$to_update[] = $rs->post_id;
 		}
 		
@@ -493,9 +527,9 @@
 		}
 		
-		$meta = $this->con->select(sprintf($getReq,$new_meta_id,$type));
-		foreach ($meta as $m) {
-			if (in_array($m->post_id,$to_update)) {
-				$to_remove[] = $m->post_id;
-				unset($to_update[array_search($m->post_id,$to_update)]);
+		$rs = $this->con->select(sprintf($getReq,$new_meta_id,$type));
+		while ($rs->fetch()) {
+			if (in_array($rs->post_id,$to_update)) {
+				$to_remove[] = $rs->post_id;
+				unset($to_update[array_search($rs->post_id,$to_update)]);
 			}
 		}
@@ -553,11 +587,11 @@
 		}
 		
-		$posts = $this->con->select($strReq);
-		
-		if (count($posts) == 0) return array();
+		$rs = $this->con->select($strReq);
+		
+		if ($rs->isEmpty()) return array();
 		
 		$ids = array();
-		foreach ($posts as $p) {
-			$ids[] = $p->post_id;
+		while ($rs->fetch()) {
+			$ids[] = $rs->post_id;
 		}
 		
Index: inc/core/class.dc.postmedia.php
===================================================================
--- inc/core/class.dc.postmedia.php	(revision 407)
+++ inc/core/class.dc.postmedia.php	(revision 407)
@@ -0,0 +1,172 @@
+<?php
+# -- BEGIN LICENSE BLOCK ---------------------------------------
+#
+# This file is part of Dotclear 2.
+#
+# Copyright (c) 2003-2011 Olivier Meunier & Association Dotclear
+# Licensed under the GPL version 2.0 license.
+# See LICENSE file or
+# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
+#
+# -- END LICENSE BLOCK -----------------------------------------
+if (!defined('DC_RC_PATH')) { return; }
+
+class dcPostMedia
+{
+	protected $core;		///< <b>dcCore</b> dcCore instance
+	protected $con;		///< <b>connection</b> Database connection
+	protected $table;		///< <b>string</b> Post-Media table name
+	
+	/**
+	Object constructor.
+	
+	@param	core		<b>dcCore</b>		dcCore instance
+	@param	type		<b>string</b>		Media type filter
+	*/
+	public function __construct($core,$type='')
+	{
+		$this->core =& $core;
+		$this->con =& $core->con;
+		$this->table = $this->core->prefix.'post_media';
+	}
+	
+	/**
+	Returns media items attached to a blog post. Result is an array containing
+	fileItems objects.
+	
+	@param	post_id	<b>integer</b>		Post ID
+	@param	media_id	<b>integer</b>		Optionnal media ID
+	@return	<b>array</b> Array of fileItems
+	*/
+	public function getPostMedia($params=array())
+	{
+		$strReq =
+		'SELECT M.media_file, M.media_id, M.media_path, M.media_title, M.media_meta, M.media_dt, '.
+		'M.media_creadt, M.media_upddt, M.media_private, M.user_id, PM.post_id ';
+		
+		if (!empty($params['columns']) && is_array($params['columns'])) {
+			$strReq .= implode(', ',$params['columns']).', ';
+		}
+		
+		$strReq .=
+		'FROM '.$this->core->prefix.'media M '.
+		'INNER JOIN '.$this->table.' PM ON (M.media_id = PM.media_id) ';
+		
+		if (!empty($params['from'])) {
+			$strReq .= $params['from'].' ';
+		}
+		
+		$where='';
+		if (isset($params['post_id'])) {
+			$where[]="PM.post_id ".$this->con->in($params['post_id']);
+		}
+		if (isset($params['media_id'])) {
+			$where[]="M.media_id ".$this->con->in($params['media_id']);
+		}
+		if (isset($params['media_path'])) {
+			$where[]="M.media_path ".$this->con->in($params['media_path']);
+		}
+		if (isset($params['link_type'])) {
+			$where[]="PM.link_type ".$this->con->in($params['link_type']);
+		} else {
+			$where[]="PM.link_type='attachment'";
+		}
+
+		$strReq .= 'WHERE '.join('AND ',$where).' ';
+
+		if (isset($params['sql'])) {
+			$strReq .= $params['sql'];
+		}
+	//echo $strReq; exit;
+		$rs = $this->con->select($strReq);
+		
+		return $rs;
+	}
+
+	/**
+	Attaches a media to a post.
+	
+	@param	post_id	<b>integer</b>		Post ID
+	@param	media_id	<b>integer</b>		Optionnal media ID
+	*/
+	public function addPostMedia($post_id,$media_id,$link_type='attachment')
+	{
+		$post_id = (integer) $post_id;
+		$media_id = (integer) $media_id;
+		
+		$f = $this->getPostMedia(array('post_id'=>$post_id,'media_id'=>$media_id,'link_type'=>$link_type));
+		
+		if (!$f->isEmpty()) {
+			return;
+		}
+		
+		$cur = $this->con->openCursor($this->table);
+		$cur->post_id = $post_id;
+		$cur->media_id = $media_id;
+		$cur->link_type = $link_type;
+		
+		$cur->insert();
+		$this->core->blog->triggerBlog();
+	}
+	
+	/**
+	Detaches a media from a post.
+	
+	@param	post_id	<b>integer</b>		Post ID
+	@param	media_id	<b>integer</b>		Optionnal media ID
+	*/
+	public function removePostMedia($post_id,$media_id,$link_type=null)
+	{
+		$post_id = (integer) $post_id;
+		$media_id = (integer) $media_id;
+		
+		$strReq = 'DELETE FROM '.$this->table.' '.
+				'WHERE post_id = '.$post_id.' '.
+				'AND media_id = '.$media_id.' ';
+		if ($link_type != null) {
+			$strReq .= "AND link_type = '".$this->con->escape($link_type)."'";
+		}
+		$this->con->execute($strReq);
+		$this->core->blog->triggerBlog();
+	}
+	
+	/**
+	Returns media items attached to a blog post. Result is an array containing
+	fileItems objects.
+	
+	@param	post_id	<b>integer</b>		Post ID
+	@param	media_id	<b>integer</b>		Optionnal media ID
+	@return	<b>array</b> Array of fileItems
+	*/
+	public function getLegacyPostMedia($post_id,$media_id=null)
+	{
+		$post_id = (integer) $post_id;
+		
+		$strReq =
+		'SELECT media_file, M.media_id, media_path, media_title, media_meta, media_dt, '.
+		'media_creadt, media_upddt, media_private, user_id '.
+		'FROM '.$this->table.' M '.
+		'INNER JOIN '.$this->table_ref.' PM ON (M.media_id = PM.media_id) '.
+		"WHERE media_path = '".$this->path."' ".
+		'AND post_id = '.$post_id.' ';
+		
+		if ($media_id) {
+			$strReq .= 'AND M.media_id = '.(integer) $media_id.' ';
+		}
+		
+		$rs = $this->con->select($strReq);
+		
+		$res = array();
+		
+		while ($rs->fetch()) {
+			$f = $this->fileRecord($rs);
+			if ($f !== null) {
+				$res[] = $f;
+			}
+		}
+		
+		return $res;
+	}
+	
+}
+?>
Index: inc/core/class.dc.rs.extensions.php
===================================================================
--- inc/core/class.dc.rs.extensions.php	(revision 852)
+++ inc/core/class.dc.rs.extensions.php	(revision 776)
@@ -117,4 +117,55 @@
 	
 	/**
+	Returns whether comments are enabled on post.
+	
+	@param	rs	Invisible parameter
+	@return	<b>boolean</b>
+	*/
+	public static function commentsActive($rs)
+	{
+		return
+		$rs->core->blog->settings->system->allow_comments
+		&& $rs->post_open_comment
+		&& ($rs->core->blog->settings->system->comments_ttl == 0 ||
+		time()-($rs->core->blog->settings->system->comments_ttl*86400) < $rs->getTS());
+	}
+	
+	/**
+	Returns whether trackbacks are enabled on post.
+	
+	@param	rs	Invisible parameter
+	@return	<b>boolean</b>
+	*/
+	public static function trackbacksActive($rs)
+	{
+		return
+		$rs->core->blog->settings->system->allow_trackbacks
+		&& $rs->post_open_tb
+		&& ($rs->core->blog->settings->system->trackbacks_ttl == 0 ||
+		time()-($rs->core->blog->settings->system->trackbacks_ttl*86400) < $rs->getTS());
+	}
+	
+	/**
+	Returns whether post has at least one comment.
+	
+	@param	rs	Invisible parameter
+	@return	<b>boolean</b>
+	*/
+	public static function hasComments($rs)
+	{
+		return $rs->nb_comment > 0;
+	}
+	
+	/**
+	Returns whether post has at least one trackbacks.
+	
+	@return	<b>boolean</b>
+	*/
+	public static function hasTrackbacks($rs)
+	{
+		return $rs->nb_trackback > 0;
+	}
+	
+	/**
 	Returns full post URL.
 	
@@ -127,4 +178,15 @@
 				$rs->post_type,html::sanitizeURL($rs->post_url)
 			);
+	}
+	
+	/**
+	Returns full post category URL.
+	
+	@param	rs	Invisible parameter
+	@return	<b>string</b>
+	*/
+	public static function getCategoryURL($rs)
+	{
+		return $rs->core->blog->url.$rs->core->url->getURLFor('category',html::sanitizeURL($rs->cat_url));
 	}
 	
@@ -302,4 +364,38 @@
 	
 	/**
+	Returns trackback RDF information block in HTML comment.
+	
+	@param	rs	Invisible parameter
+	@return	<b>string</b>
+	*/
+	public static function getTrackbackData($rs)
+	{
+		return
+		"<![CDATA[>\n".
+		"<!--[\n".
+		'<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"'."\n".
+		'  xmlns:dc="http://purl.org/dc/elements/1.1/"'."\n".
+		'  xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">'."\n".
+		"<rdf:Description\n".
+		'  rdf:about="'.$rs->getURL().'"'."\n".
+		'  dc:identifier="'.$rs->getURL().'"'."\n".
+		'  dc:title="'.htmlspecialchars($rs->post_title,ENT_COMPAT,'UTF-8').'"'."\n".
+		'  trackback:ping="'.$rs->getTrackbackLink().'" />'."\n".
+		"</rdf:RDF>\n".
+		"<!]]><!---->\n";
+	}
+	
+	/**
+	Returns post trackback full URL.
+	
+	@param	rs	Invisible parameter
+	@return	<b>string</b>
+	*/
+	public static function getTrackbackLink($rs)
+	{
+		return $rs->core->blog->url.$rs->core->url->getURLFor('trackback',$rs->post_id);
+	}
+	
+	/**
 	Returns post content. If <var>$absolute_urls</var> is true, appends full
 	blog URL to each relative post URLs.
@@ -335,4 +431,289 @@
 	}
 	
+	/**
+	Returns post media count using a subquery.
+	
+	@param	rs	Invisible parameter
+	@return	<b>integer</b>
+	*/
+	public static function countMedia($rs)
+	{
+		if (isset($rs->_nb_media[$rs->index()]))
+		{
+			return $rs->_nb_media[$rs->index()];
+		}
+		else
+		{
+			$strReq =
+			'SELECT count(media_id) '.
+			'FROM '.$rs->core->prefix.'post_media '.
+			'WHERE post_id = '.(integer) $rs->post_id.' ';
+			
+			$res = (integer) $rs->core->con->select($strReq)->f(0);
+			$rs->_nb_media[$rs->index()] = $res;
+			return $res;
+		}
+	}
+}
+
+/**
+@ingroup DC_CORE
+@brief Dotclear comment record helpers.
+
+This class adds new methods to database comment results.
+You can call them on every record comming from dcBlog::getComments and similar
+methods.
+
+@warning You should not give the first argument (usualy $rs) of every described
+function.
+*/
+class rsExtComment
+{
+	/**
+	Returns comment date with <var>$format</var> as formatting pattern. If
+	format is empty, uses <var>date_format</var> blog setting.
+	
+	@param	rs	Invisible parameter
+	@param	format	<b>string</b>		Date format pattern
+	@param	type	<b>string</b>		(dt|upddt) defaults to comment_dt
+	@return	<b>string</b>
+	*/
+	public static function getDate($rs,$format,$type='')
+	{
+		if (!$format) {
+			$format = $rs->core->blog->settings->system->date_format;
+		}
+		
+		if ($type == 'upddt') {
+			return dt::dt2str($format,$rs->comment_upddt,$rs->comment_tz);
+		} else {
+			return dt::dt2str($format,$rs->comment_dt);
+		}
+	}
+	
+	/**
+	Returns comment time with <var>$format</var> as formatting pattern. If
+	format is empty, uses <var>time_format</var> blog setting.
+	
+	@param	rs	Invisible parameter
+	@param	format	<b>string</b>		Date format pattern
+	@param	type	<b>string</b>		(dt|upddt) defaults to comment_dt
+	@return	<b>string</b>
+	*/
+	public static function getTime($rs,$format,$type='')
+	{
+		if (!$format) {
+			$format = $rs->core->blog->settings->system->time_format;
+		}
+		
+		if ($type == 'upddt') {
+			return dt::dt2str($format,$rs->comment_updt,$rs->comment_tz);
+		} else {
+			return dt::dt2str($format,$rs->comment_dt);
+		}
+	}
+	
+	/**
+	Returns comment timestamp.
+	
+	@param	rs	Invisible parameter
+	@param	type	<b>string</b>		(dt|upddt) defaults to comment_dt
+	@return	<b>integer</b>
+	*/
+	public static function getTS($rs,$type='')
+	{
+		if ($type == 'upddt') {
+			return strtotime($rs->comment_upddt);
+		} else {
+			return strtotime($rs->comment_dt);
+		}
+	}
+	
+	/**
+	Returns comment date formating according to the ISO 8601 standard.
+	
+	@param	rs	Invisible parameter
+	@param	type	<b>string</b>		(dt|upddt) defaults to comment_dt
+	@return	<b>string</b>
+	*/
+	public static function getISO8601Date($rs,$type='')
+	{
+		if ($type == 'upddt') {
+			return dt::iso8601($rs->getTS($type)+dt::getTimeOffset($rs->comment_tz),$rs->comment_tz);
+		} else {
+			return dt::iso8601($rs->getTS(),$rs->comment_tz);
+		}
+	}
+	
+	/**
+	Returns comment date formating according to RFC 822.
+	
+	@param	rs	Invisible parameter
+	@param	type	<b>string</b>		(dt|upddt) defaults to comment_dt
+	@return	<b>string</b>
+	*/
+	public static function getRFC822Date($rs,$type='')
+	{
+		if ($type == 'upddt') {
+			return dt::rfc822($rs->getTS($type)+dt::getTimeOffset($rs->comment_tz),$rs->comment_tz);
+		} else {
+			return dt::rfc822($rs->getTS(),$rs->comment_tz);
+		}
+	}
+	
+	/**
+	Returns comment content. If <var>$absolute_urls</var> is true, appends full
+	blog URL to each relative post URLs.
+	
+	@param	rs	Invisible parameter
+	@param	absolute_urls	<b>boolean</b>		With absolute URLs
+	@return	<b>string</b>
+	*/
+	public static function getContent($rs,$absolute_urls=false)
+	{
+		$res = $rs->comment_content;
+		
+		if ($rs->core->blog->settings->system->comments_nofollow) {
+			$res = preg_replace_callback('#<a(.*?href=".*?".*?)>#ms',array('self','noFollowURL'),$res);
+		}
+		
+		if ($absolute_urls) {
+			$res = html::absoluteURLs($res,$rs->getPostURL());
+		}
+		
+		return $res;
+	}
+	
+	private static function noFollowURL($m)
+	{
+		if (preg_match('/rel="nofollow"/',$m[1])) {
+			return $m[0];
+		}
+		
+		return '<a'.$m[1].' rel="nofollow">';
+	}
+	
+	/**
+	Returns comment author link to his website if he specified one.
+	
+	@param	rs	Invisible parameter
+	@return	<b>string</b>
+	*/
+	public static function getAuthorURL($rs)
+	{
+		if (trim($rs->comment_site)) {
+			return trim($rs->comment_site);
+		}
+	}
+	
+	/**
+	Returns comment post full URL.
+	
+	@param	rs	Invisible parameter
+	@return	<b>string</b>
+	*/
+	public static function getPostURL($rs)
+	{
+		return $rs->core->blog->url.$rs->core->getPostPublicURL(
+				$rs->post_type,html::sanitizeURL($rs->post_url)
+			);
+	}
+	
+	/**
+	Returns comment author name in a link to his website if he specified one.
+	
+	@param	rs	Invisible parameter
+	@return	<b>string</b>
+	*/
+	public static function getAuthorLink($rs)
+	{
+		$res = '%1$s';
+		$url = $rs->getAuthorURL();
+		if ($url) {
+			$res = '<a href="%2$s"%3$s>%1$s</a>';
+		}
+		
+		$nofollow = '';
+		if ($rs->core->blog->settings->system->comments_nofollow) {
+			$nofollow = ' rel="nofollow"';
+		}
+		
+		return sprintf($res,html::escapeHTML($rs->comment_author),html::escapeHTML($url),$nofollow);
+	}
+	
+	/**
+	Returns comment author e-mail address. If <var>$encoded</var> is true,
+	"@" sign is replaced by "%40" and "." by "%2e".
+	
+	@param	rs	Invisible parameter
+	@param	encoded	<b>boolean</b>		Encode address.
+	@return	<b>string</b>
+	*/
+	public static function getEmail($rs,$encoded=true)
+	{
+		if ($encoded) {
+			return strtr($rs->comment_email,array('@'=>'%40','.'=>'%2e'));
+		}
+		return $rs->comment_email;
+	}
+	
+	/**
+	Returns trackback site title if comment is a trackback.
+	
+	@param	rs	Invisible parameter
+	@return	<b>string</b>
+	*/
+	public static function getTrackbackTitle($rs)
+	{
+		if ($rs->comment_trackback == 1 &&
+		preg_match('|<p><strong>(.*?)</strong></p>|msU',$rs->comment_content,
+		$match)) {
+			return html::decodeEntities($match[1]);
+		}
+	}
+	
+	/**
+	Returns trackback content if comment is a trackback.
+	
+	@param	rs	Invisible parameter
+	@return	<b>string</b>
+	*/
+	public static function getTrackbackContent($rs)
+	{
+		if ($rs->comment_trackback == 1) {
+			return preg_replace('|<p><strong>.*?</strong></p>|msU','',
+			$rs->comment_content);
+		}
+	}
+	
+	/**
+	Returns comment feed unique ID.
+	
+	@param	rs	Invisible parameter
+	@return	<b>string</b>
+	*/
+	public static function getFeedID($rs)
+	{
+		return 'urn:md5:'.md5($rs->core->blog->uid.$rs->comment_id);
+		
+		$url = parse_url($rs->core->blog->url);
+		$date_part = date('Y-m-d',strtotime($rs->comment_dt));
+		
+		return 'tag:'.$url['host'].','.$date_part.':'.$rs->comment_id;
+	}
+	
+	/**
+	Returns whether comment is from the post author.
+	
+	@param	rs	Invisible parameter
+	@return	<b>boolean</b>
+	*/
+	public static function isMe($rs)
+	{
+		return
+		$rs->comment_email && $rs->comment_site &&
+		$rs->comment_email == $rs->user_email &&
+		$rs->comment_site == $rs->user_url;
+	}
 }
 
Index: inc/core/class.dc.trackback.php
===================================================================
--- inc/core/class.dc.trackback.php	(revision 270)
+++ inc/core/class.dc.trackback.php	(revision 270)
@@ -0,0 +1,404 @@
+<?php
+# -- BEGIN LICENSE BLOCK ---------------------------------------
+#
+# This file is part of Dotclear 2.
+#
+# Copyright (c) 2003-2011 Olivier Meunier & Association Dotclear
+# Licensed under the GPL version 2.0 license.
+# See LICENSE file or
+# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
+#
+# -- END LICENSE BLOCK -----------------------------------------
+if (!defined('DC_RC_PATH')) { return; }
+
+/**
+@ingroup DC_CORE
+@brief Trackbacks sender and server
+
+Sends and receives trackbacks. Also handles trackbacks auto discovery.
+*/
+class dcTrackback
+{
+	public $core;		///< <b>dcCore</b> dcCore instance
+	public $table;		///< <b>string</b> done pings table name
+	
+	/**
+	Object constructor
+	
+	@param	core		<b>dcCore</b>		dcCore instance
+	*/
+	public function __construct($core)
+	{
+		$this->core =& $core;
+		$this->con =& $this->core->con;
+		$this->table = $this->core->prefix.'ping';
+	}
+	
+	/// @name Send trackbacks
+	//@{
+	/**
+	Get all pings sent for a given post.
+	
+	@param	post_id	<b>integer</b>		Post ID
+	@return	<b>record</b>
+	*/
+	public function getPostPings($post_id)
+	{
+		$strReq = 'SELECT ping_url, ping_dt '.
+				'FROM '.$this->table.' '.
+				'WHERE post_id = '.(integer) $post_id;
+		
+		return $this->con->select($strReq);
+	}
+	
+	/**
+	Sends a ping to given <var>$url</var>.
+	
+	@param	url			<b>string</b>		URL to ping
+	@param	post_id		<b>integer</b>		Post ID
+	@param	post_title	<b>string</b>		Post title
+	@param	post_excerpt	<b>string</b>		Post excerpt
+	@param	post_url		<b>string</b>		Post URL
+	*/
+	public function ping($url,$post_id,$post_title,$post_excerpt,$post_url)
+	{
+		if ($this->core->blog === null) {
+			return false;
+		}
+		
+		$post_id = (integer) $post_id;
+		
+		# Check for previously done trackback
+		$strReq = 'SELECT post_id, ping_url FROM '.$this->table.' '.
+				'WHERE post_id = '.$post_id.' '.
+				"AND ping_url = '".$this->con->escape($url)."' ";
+		
+		$rs = $this->con->select($strReq);
+		
+		if (!$rs->isEmpty()) {
+			throw new Exception(sprintf(__('%s has still been pinged'),$url));
+		}
+		
+		$data = array(
+			'title' => $post_title,
+			'excerpt' => $post_excerpt,
+			'url' => $post_url,
+			'blog_name' => trim(html::escapeHTML(html::clean($this->core->blog->name)))
+			//,'__debug' => false
+		);
+		
+		# Ping
+		try
+		{
+			$http = self::initHttp($url,$path);
+			$http->post($path,$data,'UTF-8');
+			$res = $http->getContent();
+		}
+		catch (Exception $e)
+		{
+			throw new Exception(__('Unable to ping URL'));
+		}
+		
+		$pattern =
+		'|<response>.*<error>(.*)</error>(.*)'.
+		'(<message>(.*)</message>(.*))?'.
+		'</response>|msU';
+		
+		if (!preg_match($pattern,$res,$match))
+		{
+			throw new Exception(sprintf(__('%s is not a ping URL'),$url));
+		}
+		
+		$ping_error = trim($match[1]);
+		$ping_msg = (!empty($match[4])) ? $match[4] : '';
+		
+		if ($ping_error != '0') {
+			throw new Exception(sprintf(__('%s, ping error:'),$url).' '.$ping_msg);
+		} else {
+			# Notify ping result in database
+			$cur = $this->con->openCursor($this->table);
+			$cur->post_id = $post_id;
+			$cur->ping_url = $url;
+			$cur->ping_dt = date('Y-m-d H:i:s');
+			
+			$cur->insert();
+		}
+	}
+	//@}
+	
+	/// @name Receive trackbacks
+	//@{
+	/**
+	Receives a trackback and insert it as a comment of given post.
+	
+	@param	post_id		<b>integer</b>		Post ID
+	*/
+	public function receive($post_id)
+	{
+		header('Content-Type: text/xml; charset=UTF-8');
+		if (empty($_POST)) {
+			http::head(405,'Method Not Allowed');
+			echo
+			'<?xml version="1.0" encoding="utf-8"?>'."\n".
+			"<response>\n".
+			"  <error>1</error>\n".
+			"  <message>POST request needed</message>\n".
+			"</response>";
+			return;
+		}
+		
+		$post_id = (integer) $post_id;
+		
+		$title = !empty($_POST['title']) ? $_POST['title'] : '';
+		$excerpt = !empty($_POST['excerpt']) ? $_POST['excerpt'] : '';
+		$url = !empty($_POST['url']) ? $_POST['url'] : '';
+		$blog_name = !empty($_POST['blog_name']) ? $_POST['blog_name'] : '';
+		$charset = '';
+		$comment = '';
+		
+		$err = false;
+		$msg = '';
+		
+		if ($this->core->blog === null)
+		{
+			$err = true;
+			$msg = 'No blog.';
+		}
+		elseif ($url == '')
+		{
+			$err = true;
+			$msg = 'URL parameter is required.';
+		}
+		elseif ($blog_name == '') {
+			$err = true;
+			$msg = 'Blog name is required.';
+		}
+		
+		if (!$err)
+		{
+			$post = $this->core->blog->getPosts(array('post_id'=>$post_id,'post_type'=>''));
+			
+			if ($post->isEmpty())
+			{
+				$err = true;
+				$msg = 'No such post.';
+			}
+			elseif (!$post->trackbacksActive())
+			{
+				$err = true;
+				$msg = 'Trackbacks are not allowed for this post or weblog.';
+			}
+		}
+		
+		if (!$err)
+		{
+			$charset = self::getCharsetFromRequest();
+			
+			if (!$charset) {
+				$charset = mb_detect_encoding($title.' '.$excerpt.' '.$blog_name,
+				'UTF-8,ISO-8859-1,ISO-8859-2,ISO-8859-3,'.
+				'ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,'.
+				'ISO-8859-9,ISO-8859-10,ISO-8859-13,ISO-8859-14,ISO-8859-15');
+			}
+			
+			if (strtolower($charset) != 'utf-8') {
+				$title = iconv($charset,'UTF-8',$title);
+				$excerpt = iconv($charset,'UTF-8',$excerpt);
+				$blog_name = iconv($charset,'UTF-8',$blog_name);
+			}
+			
+			$title = trim(html::clean($title));
+			$title = html::decodeEntities($title);
+			$title = html::escapeHTML($title);
+			$title = text::cutString($title,60);
+			
+			$excerpt = trim(html::clean($excerpt));
+			$excerpt = html::decodeEntities($excerpt);
+			$excerpt = preg_replace('/\s+/ms',' ',$excerpt);
+			$excerpt = text::cutString($excerpt,252); 
+			$excerpt = html::escapeHTML($excerpt).'...';
+			
+			$blog_name = trim(html::clean($blog_name));
+			$blog_name = html::decodeEntities($blog_name);
+			$blog_name = html::escapeHTML($blog_name);
+			$blog_name = text::cutString($blog_name,60);
+			
+			$url = trim(html::clean($url));
+			
+			if (!$blog_name) {
+				$blog_name = 'Anonymous blog';
+			}
+			
+			$comment =
+			"<!-- TB -->\n".
+			'<p><strong>'.($title ? $title : $blog_name)."</strong></p>\n".
+			'<p>'.$excerpt.'</p>';
+			
+			$cur = $this->core->con->openCursor($this->core->prefix.'comment');
+			$cur->comment_author = (string) $blog_name;
+			$cur->comment_site = (string) $url;
+			$cur->comment_content = (string) $comment;
+			$cur->post_id = $post_id;
+			$cur->comment_trackback = 1;
+			$cur->comment_status = $this->core->blog->settings->system->trackbacks_pub ? 1 : -1;
+			$cur->comment_ip = http::realIP();
+			
+			try
+			{
+				# --BEHAVIOR-- publicBeforeTrackbackCreate
+				$this->core->callBehavior('publicBeforeTrackbackCreate',$cur);
+				if ($cur->post_id) {
+					$comment_id = $this->core->blog->addComment($cur);
+					
+					# --BEHAVIOR-- publicAfterTrackbackCreate
+					$this->core->callBehavior('publicAfterTrackbackCreate',$cur,$comment_id);
+				}
+			}
+			catch (Exception $e)
+			{
+				$err = 1;
+				$msg = 'Something went wrong : '.$e->getMessage();
+			}
+		}
+		
+		
+		$debug_trace =
+		"  <debug>\n".
+		'    <title>'.$title."</title>\n".
+		'    <excerpt>'.$excerpt."</excerpt>\n".
+		'    <url>'.$url."</url>\n".
+		'    <blog_name>'.$blog_name."</blog_name>\n".
+		'    <charset>'.$charset."</charset>\n".
+		'    <comment>'.$comment."</comment>\n".
+		"  </debug>\n";
+		
+		$resp =
+		'<?xml version="1.0" encoding="utf-8"?>'."\n".
+		"<response>\n".
+		'  <error>'.(integer) $err."</error>\n";
+		
+		if ($msg) {
+			$resp .= '  <message>'.$msg."</message>\n";
+		}
+		
+		if (!empty($_POST['__debug'])) {
+			$resp .= $debug_trace;
+		}
+		
+		echo	$resp."</response>";
+	}
+	//@}
+	
+	private static function initHttp($url,&$path)
+	{
+		$client = netHttp::initClient($url,$path);
+		$client->setTimeout(5);
+		$client->setUserAgent('Dotclear - http://www.dotclear.org/');
+		$client->useGzip(false);
+		$client->setPersistReferers(false);
+		
+		return $client;
+	}
+	
+	private static function getCharsetFromRequest()
+	{
+		if (isset($_SERVER['CONTENT_TYPE']))
+		{
+			if (preg_match('|charset=([a-zA-Z0-9-]+)|',$_SERVER['CONTENT_TYPE'],$m)) {
+				return $m[1];
+			}
+		}
+		
+		return null;
+	}
+	
+	/// @name Trackbacks auto discovery
+	//@{
+	/**
+	Returns an array containing all discovered trackbacks URLs in
+	<var>$text</var>.
+	
+	@param	text		<b>string</b>		Input text
+	@return	<b>array</b>
+	*/
+	public function discover($text)
+	{
+		$res = array();
+		
+		foreach ($this->getTextLinks($text) as $link)
+		{
+			if (($url = $this->getPingURL($link)) !== null) {
+				$res[] = $url;
+			}
+		}
+		
+		return $res;
+	}
+	//@}
+	
+	private function getTextLinks($text)
+	{
+		$res = array();
+		
+		# href attribute on "a" tags
+		if (preg_match_all('/<a ([^>]+)>/ms', $text, $match, PREG_SET_ORDER))
+		{
+			for ($i = 0; $i<count($match); $i++)
+			{
+				if (preg_match('/href="(http:\/\/[^"]+)"/ms', $match[$i][1], $matches)) {
+					$res[$matches[1]] = 1;
+				}
+			}
+		}
+		unset($match);
+		
+		# cite attributes on "blockquote" and "q" tags
+		if (preg_match_all('/<(blockquote|q) ([^>]+)>/ms', $text, $match, PREG_SET_ORDER))
+		{
+			for ($i = 0; $i<count($match); $i++)
+			{
+				if (preg_match('/cite="(http:\/\/[^"]+)"/ms', $match[$i][2], $matches)) {
+					$res[$matches[1]] = 1;
+				}
+			}
+		}
+		
+		return array_keys($res);
+	}
+	
+	private function getPingURL($url)
+	{
+		try
+		{
+			$http = self::initHttp($url,$path);
+			$http->get($path);
+			$page_content = $http->getContent();
+		}
+		catch (Exception $e)
+		{
+			return false;
+		}
+		
+		$pattern_rdf =
+		'/<rdf:RDF.*?>.*?'.
+		'<rdf:Description\s+(.*?)\/>'.
+		'.*?<\/rdf:RDF>'.
+		'/msi';
+		
+		preg_match_all($pattern_rdf,$page_content,$rdf_all,PREG_SET_ORDER);
+		
+		for ($i=0; $i<count($rdf_all); $i++)
+		{
+			$rdf = $rdf_all[$i][1];
+			
+			if (preg_match('/dc:identifier="'.preg_quote($url,'/').'"/msi',$rdf)) {
+				if (preg_match('/trackback:ping="(.*?)"/msi',$rdf,$tb_link)) {
+					return $tb_link[1];
+				}
+			}
+		}
+		
+		return null;
+	}
+}
+?>
Index: inc/core/class.dc.xmlrpc.php
===================================================================
--- inc/core/class.dc.xmlrpc.php	(revision 877)
+++ inc/core/class.dc.xmlrpc.php	(revision 776)
@@ -75,4 +75,12 @@
 			'List of most recent posts in the system');
 		
+		$this->addCallback('metaWeblog.getCategories',array($this,'mw_getCategories'),
+			array('array','string','string','string'),
+			'List of all categories defined in the weblog');
+		
+		$this->addCallback('metaWeblog.newMediaObject',array($this,'mw_newMediaObject'),
+			array('struct','string','string','string','struct'),
+			'Upload a file on the web server');
+		
 		# MovableType methods
 		$this->addCallback('mt.getRecentPostTitles',array($this,'mt_getRecentPostTitles'),
@@ -80,4 +88,16 @@
 			'List of most recent posts in the system');
 		
+		$this->addCallback('mt.getCategoryList',array($this,'mt_getCategoryList'),
+			array('array','string','string','string'),
+			'List of all categories defined in the weblog');
+		
+		$this->addCallback('mt.getPostCategories',array($this,'mt_getPostCategories'),
+			array('array','string','string','string'),
+			'List of all categories to which the post is assigned');
+		
+		$this->addCallback('mt.setPostCategories',array($this,'mt_setPostCategories'),
+			array('boolean','string','string','string','array'),
+			'Sets the categories for a post');
+		
 		$this->addCallback('mt.publishPost',array($this,'mt_publishPost'),
 			array('boolean','string','string','string'),
@@ -123,8 +143,24 @@
 			'Get an array of users for the blog.');
 		
+		$this->addCallback('wp.getCategories',array($this,'wp_getCategories'),
+			array('array','integer','string','string'),
+			'Get an array of available categories on a blog.');
+		
 		$this->addCallback('wp.getTags',array($this,'wp_getTags'),
 			array('array','integer','string','string'),
 			'Get list of all tags for the blog.');
 		
+		$this->addCallback('wp.newCategory',array($this,'wp_newCategory'),
+			array('integer','integer','string','string','struct'),
+			'Create a new category.');
+		
+		$this->addCallback('wp.deleteCategory',array($this,'wp_deleteCategory'),
+			array('boolean','integer','string','string','integer'),
+			'Delete a category with a given ID.');
+		
+		$this->addCallback('wp.suggestCategories',array($this,'wp_suggestCategories'),
+			array('array','integer','string','string','string','integer'),
+			'Get an array of categories that start with a given string.');
+		
 		$this->addCallback('wp.uploadFile',array($this,'wp_uploadFile'),
 			array('struct','integer','string','string','struct'),
@@ -151,4 +187,31 @@
 			'Update blog options');
 		
+		$this->addCallback('wp.getComment',array($this,'wp_getComment'),
+			array('struct','integer','string','string','integer'),
+			"Gets a comment, given it's comment ID.");
+		
+		$this->addCallback('wp.getCommentCount',array($this,'wp_getCommentCount'),
+			array('array','integer','string','string','integer'),
+			'Retrieve comment count.');
+		
+		$this->addCallback('wp.getComments',array($this,'wp_getComments'),
+			array('array','integer','string','string','struct'),
+			'Gets a set of comments for a given post.');
+		
+		$this->addCallback('wp.deleteComment',array($this,'wp_deleteComment'),
+			array('boolean','integer','string','string','integer'),
+			'Delete a comment with given ID.');
+		
+		$this->addCallback('wp.editComment',array($this,'wp_editComment'),
+			array('boolean','integer','string','string','integer','struct'),
+			'Edit a comment with given ID.');
+		
+		$this->addCallback('wp.newComment',array($this,'wp_newComment'),
+			array('integer','integer','string','string','integer','struct'),
+			'Create a new comment for a given post ID.');
+		
+		$this->addCallback('wp.getCommentStatusList',array($this,'wp_getCommentStatusList'),
+			array('array','integer','string','string'),
+			'Retrieve all of the comment statuses.');
 	}
 	
@@ -242,14 +305,21 @@
 		$this->setUser($user,$pwd);
 		$this->setBlog();
-		$posts = $this->core->blog->getPosts(array(
+		$rs = $this->core->blog->getPosts(array(
 			'post_id' => (integer) $post_id,
 			'post_type' => $post_type
 		));
 		
-		if (count($posts) == 0) {
+		if ($rs->isEmpty()) {
 			throw new Exception('This entry does not exist');
 		}
 		
-		return $posts;
+		return $rs;
+	}
+	
+	private function getCatID($cat_url)
+	{
+		$rs = $this->core->blog->getCategories(array('cat_url' => $cat_url));
+		
+		return $rs->isEmpty() ? null : $rs->cat_id;
 	}
 	
@@ -265,4 +335,6 @@
 		$description = !empty($struct['description']) ? $struct['description'] : null;
 		$dateCreated = !empty($struct['dateCreated']) ? $struct['dateCreated'] : null;
+		$open_comment = isset($struct['mt_allow_comments']) ? $struct['mt_allow_comments'] : 1;
+		$open_tb = isset($struct['mt_allow_pings']) ? $struct['mt_allow_pings'] : 1;
 		
 		if ($description !== null) {
@@ -290,4 +362,6 @@
 		$cur->post_content_xhtml = $content_xhtml;
 		$cur->post_excerpt_xhtml = $excerpt_xhtml;
+		$cur->post_open_comment = (integer) ($open_comment == 1);
+		$cur->post_open_tb = (integer) ($open_tb == 1);
 		$cur->post_status = (integer) $publish;
 		$cur->post_format = 'xhtml';
@@ -301,6 +375,19 @@
 		}
 		
+		# Categories in an array
+		if (isset($struct['categories']) && is_array($struct['categories']))
+		{
+			$categories = $struct['categories'];
+			$cat_id = !empty($categories[0]) ? $categories[0] : null;
+			
+			$cur->cat_id = $this->getCatID($cat_id);
+		}
+		
 		if (isset($struct['wp_slug'])) {
 			$cur->post_url = $struct['wp_slug'];
+		}
+		
+		if (isset($struct['wp_password'])) {
+			$cur->post_password = $struct['wp_password'];
 		}
 		
@@ -353,4 +440,6 @@
 		$description = (!empty($struct['description'])) ? $struct['description'] : null;
 		$dateCreated = !empty($struct['dateCreated']) ? $struct['dateCreated'] : null;
+		$open_comment = (isset($struct['mt_allow_comments'])) ? $struct['mt_allow_comments'] : 1;
+		$open_tb = (isset($struct['mt_allow_pings'])) ? $struct['mt_allow_pings'] : 1;
 		
 		if ($description !== null) {
@@ -377,4 +466,6 @@
 		$cur->post_content_xhtml = $content_xhtml;
 		$cur->post_excerpt_xhtml = $excerpt_xhtml;
+		$cur->post_open_comment = (integer) ($open_comment == 1);
+		$cur->post_open_tb = (integer) ($open_tb == 1);
 		$cur->post_status = (integer) $publish;
 		$cur->post_format = 'xhtml';
@@ -392,6 +483,19 @@
 		}
 		
+		# Categories in an array
+		if (isset($struct['categories']) && is_array($struct['categories']))
+		{
+			$categories = $struct['categories'];
+			$cat_id = !empty($categories[0]) ? $categories[0] : null;
+			
+			$cur->cat_id = $this->getCatID($cat_id);
+		}
+		
 		if (isset($struct['wp_slug'])) {
 			$cur->post_url = $struct['wp_slug'];
+		}
+		
+		if (isset($struct['wp_password'])) {
+			$cur->post_password = $struct['wp_password'];
 		}
 		
@@ -435,4 +539,8 @@
 		$res['userid'] = $post->user_id;
 		$res['postid'] = $post->post_id;
+		
+		if ($post->cat_id) {
+			$res['categories'] = array($post->cat_url);
+		}
 		
 		if ($type == 'blogger') {
@@ -449,4 +557,6 @@
 			$res['mt_excerpt'] = $post->post_excerpt_xhtml;
 			$res['mt_text_more'] = '';
+			$res['mt_allow_comments'] = (integer) $post->post_open_comment;
+			$res['mt_allow_pings'] = (integer) $post->post_open_tb;
 			$res['mt_convert_breaks'] = '';
 			$res['mt_keywords'] = '';
@@ -486,25 +596,31 @@
 		
 		$res = array();
-		foreach ($posts as $p)
+		while ($posts->fetch())
 		{
 			$tres = array();
 			
 			$tres['dateCreated'] = new xmlrpcDate($posts->getTS());
-			$tres['userid'] = $p->user_id;
-			$tres['postid'] = $p->post_id;
+			$tres['userid'] = $posts->user_id;
+			$tres['postid'] = $posts->post_id;
+			
+			if ($posts->cat_id) {
+				$tres['categories'] = array($posts->cat_url);
+			}
 			
 			if ($type == 'blogger') {
-				$tres['content'] = $p->post_content_xhtml;
+				$tres['content'] = $posts->post_content_xhtml;
 			}
 			
 			if ($type == 'mt' || $type == 'mw') {
-				$tres['title'] = $p->post_title;
+				$tres['title'] = $posts->post_title;
 			}
 			
 			if ($type == 'mw') {
-				$tres['description'] = $p->post_content_xhtml;
-				$tres['link'] = $tres['permaLink'] = $p->getURL();
-				$tres['mt_excerpt'] = $p->post_excerpt_xhtml;
+				$tres['description'] = $posts->post_content_xhtml;
+				$tres['link'] = $tres['permaLink'] = $posts->getURL();
+				$tres['mt_excerpt'] = $posts->post_excerpt_xhtml;
 				$tres['mt_text_more'] = '';
+				$tres['mt_allow_comments'] = (integer) $posts->post_open_comment;
+				$tres['mt_allow_pings'] = (integer) $posts->post_open_tb;
 				$tres['mt_convert_breaks'] = '';
 				$tres['mt_keywords'] = '';
@@ -546,4 +662,94 @@
 	}
 	
+	private function getCategories($blog_id,$user,$pwd)
+	{
+		$this->setUser($user,$pwd);
+		$this->setBlog();
+		$rs = $this->core->blog->getCategories();
+		
+		$res = array();
+		
+		$l = $rs->level;
+		$stack = array('',$rs->cat_url);
+		
+		while ($rs->fetch())
+		{
+			$d = $rs->level - $l;
+			if ($d == 0) {
+				array_pop($stack);
+				$parent = end($stack);
+			} elseif ($d > 0) {
+				$parent = end($stack);
+			} elseif ($d < 0) {
+				$D = abs($d);
+				for ($i=0; $i<=$D; $i++) {
+					array_pop($stack);
+				}
+				$parent = end($stack);
+			}
+			
+			$res[] = array(
+				'categoryId' => $rs->cat_url,
+				'parentId' => $parent,
+				'description' => $rs->cat_title,
+				'categoryName' => $rs->cat_url,
+				'htmlUrl' => $this->core->blog->url.
+					$this->core->url->getURLFor('category',$rs->cat_url),
+				'rssUrl' => $this->core->blog->url.
+					$this->core->url->getURLFor('feed','category/'.$rs->cat_url.'/rss2')
+			);
+			
+			$stack[] = $rs->cat_url;
+			$l = $rs->level;
+		}
+		
+		return $res;
+	}
+	
+	private function getPostCategories($post_id,$user,$pwd)
+	{
+		$post_id = (integer) $post_id;
+		
+		$post = $this->getPostRS($post_id,$user,$pwd);
+		
+		return array(
+			array(
+			'categoryName' => $post->cat_url,
+			'categoryId' => (string) $post->cat_url,
+			'isPrimary' => true
+			)
+		);
+	}
+	
+	private function setPostCategories($post_id,$user,$pwd,$categories)
+	{
+		$post_id = (integer) $post_id;
+		
+		$post = $this->getPostRS($post_id,$user,$pwd);
+		
+		$cat_id = (!empty($categories[0]['categoryId'])) ? $categories[0]['categoryId'] : null;
+		
+		foreach($categories as $v)
+		{
+			if (isset($v['isPrimary']) && $v['isPrimary']) {
+				$cat_id = $v['categoryId'];
+				break;
+			}
+		}
+		
+		# w.bloggar sends -1 for no category.
+		if ($cat_id == -1) {
+			$cat_id = null;
+		}
+		
+		if ($cat_id) {
+			$cat_id = $this->getCatID($cat_id);
+		}
+		
+		$this->core->blog->updPostCategory($post_id,(integer) $cat_id);
+		
+		return true;
+	}
+	
 	private function publishPost($post_id,$user,$pwd)
 	{
@@ -561,4 +767,49 @@
 		
 		return true;
+	}
+	
+	private function newMediaObject($blog_id,$user,$pwd,$file)
+	{
+		if (empty($file['name'])) {
+			throw new Exception('No file name');
+		}
+		
+		if (empty($file['bits'])) {
+			throw new Exception('No file content');
+		}
+		
+		$file_name = $file['name'];
+		$file_bits = $file['bits'];
+		
+		$this->setUser($user,$pwd);
+		$this->setBlog();
+		
+		$media = new dcMedia($this->core);
+		
+		$dir_name = path::clean(dirname($file_name));
+		$file_name = basename($file_name);
+		
+		$dir_name = preg_replace('!^/!','',$dir_name);
+		if ($dir_name != '')
+		{
+			$dir = explode('/',$dir_name);
+			$cwd = './';
+			foreach ($dir as $v)
+			{
+				$v = files::tidyFileName($v);
+				$cwd .= $v.'/';
+				$media->makeDir($v);
+				$media->chdir($cwd);
+			}
+		}
+		
+		$media_id = $media->uploadBits($file_name,$file_bits);
+		
+		$f = $media->getFile($media_id);
+		return array(
+			'file' => $file_name,
+			'url' => $f->file_url,
+			'type' => files::getMimeType($file_name)
+		);
 	}
 	
@@ -581,4 +832,19 @@
 	}
 	
+	private function translateWpCommentstatus($s)
+	{
+		$status = array(
+			'hold' => -1,
+			'approve' => 0,
+			'spam' => -2
+		);
+		
+		if (is_int($s)) {
+			$status = array_flip($status);
+			return isset($status[$s]) ? $status[$s] : $status[0];
+		} else {
+			return isset($status[$s]) ? $status[$s] : $status['approve'];
+		}
+	}
 	
 	private function translateWpOptions($options=array())
@@ -706,25 +972,29 @@
 		
 		$res = array();
-		foreach ($posts as $post)
+		while ($posts->fetch())
 		{
 			$tres = array(
-				"dateCreated"			=> new xmlrpcDate($post->getTS()),
-				"userid"				=> $post->user_id,
-				"page_id"				=> $post->post_id,
-				"page_status"			=> $this->translateWpStatus((integer) $post->post_status),
-				"description"			=> $post->post_content_xhtml,
-				"title"				=> $post->post_title,
-				"link"				=> $post->getURL(),
-				"permaLink"			=> $post->getURL(),
-				"excerpt"				=> $post->post_excerpt_xhtml,
+				"dateCreated"			=> new xmlrpcDate($posts->getTS()),
+				"userid"				=> $posts->user_id,
+				"page_id"				=> $posts->post_id,
+				"page_status"			=> $this->translateWpStatus((integer) $posts->post_status),
+				"description"			=> $posts->post_content_xhtml,
+				"title"				=> $posts->post_title,
+				"link"				=> $posts->getURL(),
+				"permaLink"			=> $posts->getURL(),
+				"categories"			=> array(),
+				"excerpt"				=> $posts->post_excerpt_xhtml,
 				"text_more"			=> '',
-				"wp_slug"				=> $post->post_url,
-				"wp_author"			=> $post->getAuthorCN(),
+				"mt_allow_comments"		=> (integer) $posts->post_open_comment,
+				"mt_allow_pings"		=> (integer) $posts->post_open_tb,
+				"wp_slug"				=> $posts->post_url,
+				"wp_password"			=> $posts->post_password,
+				"wp_author"			=> $posts->getAuthorCN(),
 				"wp_page_parent_id"		=> 0,
 				"wp_page_parent_title"	=> '',
-				"wp_page_order"		=> $post->post_position,
-				"wp_author_id"			=> $post->user_id,
-				"wp_author_display_name"	=> $post->getAuthorCN(),
-				"date_created_gmt"		=> new xmlrpcDate(dt::iso8601($post->getTS(),$post->post_tz)),
+				"wp_page_order"		=> $posts->post_position,
+				"wp_author_id"			=> $posts->user_id,
+				"wp_author_display_name"	=> $posts->getAuthorCN(),
+				"date_created_gmt"		=> new xmlrpcDate(dt::iso8601($posts->getTS(),$posts->post_tz)),
 				"custom_fields"		=> array(),
 				"wp_page_template"		=> 'default'
@@ -781,8 +1051,8 @@
 		$this->setBlog();
 		
-		$perms = $this->core->getBlogPermissions($this->core->blog->id);
+		$rs = $this->core->getBlogPermissions($this->core->blog->id);
 		$res = array();
 		
-		foreach($perms as $k => $v)
+		foreach($rs as $k => $v)
 		{
 			$res[] = array(
@@ -808,16 +1078,238 @@
 		$f_url = $this->core->blog->url.
 			$this->core->url->getURLFor('tag_feed','%s');
-		foreach ($tags as $tag)
+		while ($tags->fetch())
 		{
 			$res[] = array(
-				'tag_id'		=> $tag->meta_id,
-				'name'		=> $tag->meta_id,
-				'count'		=> $tag->count,
-				'slug'		=> $tag->meta_id,
-				'html_url'	=> sprintf($url,$tag->meta_id),
-				'rss_url'		=> sprintf($f_url,$tag->meta_id)
+				'tag_id'		=> $tags->meta_id,
+				'name'		=> $tags->meta_id,
+				'count'		=> $tags->count,
+				'slug'		=> $tags->meta_id,
+				'html_url'	=> sprintf($url,$tags->meta_id),
+				'rss_url'		=> sprintf($f_url,$tags->meta_id)
 			);
 		}
 		return $res;
+	}
+	
+	private function newCategory($user,$pwd,$struct)
+	{
+		$this->setUser($user,$pwd);
+		$this->setBlog();
+		
+		if (empty($struct['name'])) {
+			throw new Exception('You mus give a category name.');
+		}
+		
+		$cur = $this->core->con->openCursor($this->core->prefix.'category');
+		$cur->cat_title = $struct['name'];
+		
+		if (!empty($struct['slug'])) {
+			$cur->cat_url = $struct['slug'];
+		}
+		if (!empty($struct['category_description'])) {
+			$cur->cat_desc = $struct['category_description'];
+			if (html::clean($cur->cat_desc) == $cur->cat_desc) {
+				$cur->cat_desc = '<p>'.$cur->cat_desc.'</p>';
+			}
+		}
+		
+		$parent = !empty($struct['category_parent']) ? (integer) $struct['category_parent'] : 0;
+		
+		$id = $this->core->blog->addCategory($cur,$parent);
+		$rs = $this->core->blog->getCategory($id);
+		return $rs->cat_url;
+	}
+	
+	private function deleteCategory($user,$pwd,$cat_id)
+	{
+		$this->setUser($user,$pwd);
+		$this->setBlog();
+		
+		$c = $this->core->blog->getCategories(array('cat_url' => $cat_id));
+		if ($c->isEmpty()) {
+			throw new Exception(__('This category does not exist.'));
+		}
+		$cat_id = $c->cat_id;
+		unset($c);
+		
+		$this->core->blog->delCategory((integer) $cat_id);
+		return true;
+	}
+	
+	private function searchCategories($user,$pwd,$category,$limit)
+	{
+		$this->setUser($user,$pwd);
+		$this->setBlog();
+		
+		$strReq = 'SELECT cat_id, cat_title, cat_url '.
+				'FROM '.$this->core->prefix.'category '.
+				"WHERE blog_id = '".$this->core->con->escape($this->core->blog->id)."' ".
+				"AND LOWER(cat_title) LIKE LOWER('%".$this->core->con->escape($category)."%') ".
+				($limit > 0 ? $this->core->con->limit($limit) : '');
+		
+		$rs = $this->core->con->select($strReq);
+		
+		$res = array();
+		while ($rs->fetch())
+		{
+			$res[] = array(
+				'category_id' => $rs->cat_url,
+				'category_name' => $rs->cat_url
+			);
+		}
+		return $res;
+	}
+	
+	private function countComments($user,$pwd,$post_id)
+	{
+		$this->setUser($user,$pwd);
+		$this->setBlog();
+		
+		$res = array(
+			'approved' => 0,
+			'awaiting_moderation' => 0,
+			'spam' => 0,
+			'total' => 0
+		);
+		$rs = $this->core->blog->getComments(array('post_id' => $post_id));
+		
+		while ($rs->fetch()) {
+			$res['total']++;
+			if ($rs->comment_status == 1) {
+				$res['approved']++;
+			} elseif ($rs->comment_status == -2) {
+				$res['spam']++;
+			} else {
+				$res['awaiting_moderation']++;
+			}
+		}
+		return $res;
+	}
+	
+	private function getComments($user,$pwd,$struct,$id=null)
+	{
+		$this->setUser($user,$pwd);
+		$this->setBlog();
+		
+		$params = array();
+		
+		if (!empty($struct['status'])) {
+			$params['comment_status'] = $this->translateWpCommentstatus($struct['status']);
+		}
+		
+		if (!empty($struct['post_id'])) {
+			$params['post_id'] = (integer) $struct['post_id'];
+		}
+		
+		if (isset($id)) {
+			$params['comment_id'] = $id;
+		}
+		
+		$offset = !empty($struct['offset']) ? (integer) $struct['offset'] : 0;
+		$limit = !empty($struct['number']) ? (integer) $struct['number'] : 10;
+		$params['limit'] = array($offset,$limit);
+		
+		$rs = $this->core->blog->getComments($params);
+		$res = array();
+		while ($rs->fetch())
+		{
+			$res[] = array(
+				'date_created_gmt'		=> new xmlrpcDate($rs->getTS()),
+				'user_id'				=> $rs->user_id,
+				'comment_id'			=> $rs->comment_id,
+				'parent'				=> 0,
+				'status'				=> $this->translateWpCommentstatus((integer) $rs->comment_status),
+				'content'				=> $rs->comment_content,
+				'link'				=> $rs->getPostURL().'#c'.$rs->comment_id,
+				'post_id'				=> $rs->post_id,
+				'post_title'			=> $rs->post_title,
+				'author'				=> $rs->comment_author,
+				'author_url'			=> $rs->comment_site,
+				'author_email'			=> $rs->comment_email,
+				'author_ip'			=> $rs->comment_ip
+			);
+		}
+		return $res;
+	}
+	
+	private function addComment($user,$pwd,$post_id,$struct)
+	{
+		$this->setUser($user,$pwd);
+		$this->setBlog();
+		
+		if (empty($struct['content'])) {
+			throw new Exception('Sorry, you cannot post an empty comment',401);
+		}
+		
+		if (is_numeric($post_id)) {
+			$p['post_id'] = $post_id;
+		} else {
+			$p['post_url'] = $post_id;
+		}
+		$rs = $this->core->blog->getPosts($p);
+		if ($rs->isEmpty()) {
+			throw new Exception('Sorry, no such post.',404);
+		}
+		
+		$cur = $this->core->con->openCursor($this->core->prefix.'comment');
+		
+		$cur->comment_author = $this->core->auth->getInfo('user_cn');
+		$cur->comment_email = $this->core->auth->getInfo('user_email');
+		$cur->comment_site = $this->core->auth->getInfo('user_url');
+		
+		$cur->comment_content = $struct['content'];
+		$cur->post_id = (integer) $post_id;
+		
+		$id = $this->core->blog->addComment($cur);
+		return $id;
+	}
+	
+	private function updComment($user,$pwd,$comment_id,$struct)
+	{
+		$this->setUser($user,$pwd);
+		$this->setBlog();
+		
+		$cur = $this->core->con->openCursor($this->core->prefix.'comment');
+		
+		if (isset($struct['status'])) {
+			$cur->comment_status = $this->translateWpCommentstatus($struct['status']);
+		}
+		
+		if (isset($struct['date_created_gmt'])) {
+			if ($struct['date_created_gmt'] instanceof xmlrpcDate) {
+				$cur->comment_dt = date('Y-m-d H:i:00',$struct['date_created_gmt']->getTimestamp());
+			} elseif (is_string($struct['date_created_gmt']) && @strtotime($struct['date_created_gmt'])) {
+				$cur->comment_dt = date('Y-m-d H:i:00',strtotime($struct['date_created_gmt']));
+			}
+			$cur->comment_dt = $struct['date_created_gmt'];
+		}
+		
+		if (isset($struct['content'])) {
+			$cur->comment_content = $struct['content'];
+		}
+		
+		if (isset($struct['author'])) {
+			$cur->comment_author = $struct['author'];
+		}
+		
+		if (isset($struct['author_url'])) {
+			$cur->comment_site = $struct['author_url'];
+		}
+		
+		if (isset($struct['author_email'])) {
+			$cur->comment_email = $struct['author_email'];
+		}
+		
+		$this->core->blog->updComment($comment_id,$cur);
+		return true;
+	}
+	
+	private function delComment($user,$pwd,$comment_id)
+	{
+		$this->setUser($user,$pwd);
+		$this->setBlog();
+		
+		$this->core->blog->delComment($comment_id);
+		return true;
 	}
 	
@@ -882,4 +1374,14 @@
 	}
 	
+	public function mw_getCategories($blogid,$username,$password)
+	{
+		return $this->getCategories($blogid,$username,$password);
+	}
+	
+	public function mw_newMediaObject($blogid,$username,$password,$file)
+	{
+		return $this->newMediaObject($blogid,$username,$password,$file);
+	}
+	
 	/* MovableType methods
 	--------------------------------------------------- */
@@ -887,4 +1389,19 @@
 	{
 		return $this->getRecentPosts($blogid,$username,$password,$numberOfPosts,'mt');
+	}
+	
+	public function mt_getCategoryList($blogid,$username,$password)
+	{
+		return $this->getCategories($blogid,$username,$password);
+	}
+	
+	public function mt_getPostCategories($postid,$username,$password)
+	{
+		return $this->getPostCategories($postid,$username,$password);
+	}
+	
+	public function mt_setPostCategories($postid,$username,$password,$categories)
+	{
+		return $this->setPostCategories($postid,$username,$password,$categories);
 	}
 	
@@ -958,7 +1475,32 @@
 	}
 	
+	public function wp_getCategories($blogid,$username,$password)
+	{
+		return $this->getCategories($blogid,$username,$password);
+	}
+	
 	public function wp_getTags($blogid,$username,$password)
 	{
 		return $this->getTags($username,$password);
+	}
+	
+	public function wp_newCategory($blogid,$username,$password,$content)
+	{
+		return $this->newCategory($username,$password,$content);
+	}
+	
+	public function wp_deleteCategory($blogid,$username,$password,$categoryid)
+	{
+		return $this->deleteCategory($username,$password,$categoryid);
+	}
+	
+	public function wp_suggestCategories($blogid,$username,$password,$category,$max_results=0)
+	{
+		return $this->searchCategories($username,$password,$category,$max_results);
+	}
+	
+	public function wp_uploadFile($blogid,$username,$password,$file)
+	{
+		return $this->newMediaObject($blogid,$username,$password,$file);
 	}
 	
@@ -1040,4 +1582,51 @@
 	}
 	
+	public function wp_getComment($blogid,$username,$password,$commentid)
+	{
+		$res = $this->getComments($username,$password,array(),$commentid);
+		
+		if (empty($res)) {
+			throw new Exception('Sorry, no such comment',404);
+		}
+		
+		return $res[0];
+	}
+	
+	public function wp_getCommentCount($blogid,$username,$password,$postid)
+	{
+		return $this->countComments($username,$password,$postid);
+	}
+	
+	public function wp_getComments($blogid,$username,$password,$struct)
+	{
+		return $this->getComments($username,$password,$struct);
+	}
+	
+	public function wp_deleteComment($blogid,$username,$password,$commentid)
+	{
+		return $this->delComment($username,$password,$commentid);
+	}
+	
+	public function wp_editComment($blogid,$username,$password,$commentid,$content)
+	{
+		return $this->updComment($username,$password,$commentid,$content);
+	}
+	
+	public function wp_newComment($blogid,$username,$password,$postid,$content)
+	{
+		return $this->addComment($username,$password,$postid,$content);
+	}
+	
+	public function wp_getCommentStatusList($blogid,$username,$password)
+	{
+		$this->setUser($username,$password);
+		$this->setBlog();
+		
+		return array(
+			'hold' => 'Unapproved',
+			'approve' => 'Approved',
+			'spam' => 'Spam'
+		);
+	}
 }
 ?>
