[pLog-svn] r2423 - in plog/trunk: . class/action class/action/admin class/bayesian class/cache class/dao class/dao/customfields class/dao/userdata class/data class/database class/database/pdb class/database/pdb/drivers class/gallery/dao class/gallery/resizers class/locale class/logger class/logger/layout class/net/http class/net/http/session class/plugin class/summary/action class/template/templatesets class/view class/view/admin config templates/admin

oscar at devel.plogworld.net oscar at devel.plogworld.net
Sat Aug 27 19:09:08 GMT 2005


Author: oscar
Date: 2005-08-27 19:09:07 +0000 (Sat, 27 Aug 2005)
New Revision: 2423

Added:
   plog/trunk/class/gallery/resizers/gallerythumbnailgenerator.class.php
Modified:
   plog/trunk/class/action/addcommentaction.class.php
   plog/trunk/class/action/addtrackbackaction.class.php
   plog/trunk/class/action/admin/adminaddpostaction.class.php
   plog/trunk/class/action/admin/adminaddresourcealbumaction.class.php
   plog/trunk/class/action/admin/admindeleteblogaction.class.php
   plog/trunk/class/action/admin/admindeletecommentaction.class.php
   plog/trunk/class/action/admin/admindeletelinkcategoryaction.class.php
   plog/trunk/class/action/admin/admineditlinkcategoryaction.class.php
   plog/trunk/class/action/admin/adminnewarticlecategoryaction.class.php
   plog/trunk/class/action/admin/adminnewresourceaction.class.php
   plog/trunk/class/action/admin/adminpostmanagementcommonaction.class.php
   plog/trunk/class/action/admin/adminresourcesaction.class.php
   plog/trunk/class/action/admin/adminupdateblogsettingsaction.class.php
   plog/trunk/class/action/admin/adminupdateeditblogaction.class.php
   plog/trunk/class/action/admin/adminupdatelinkcategoryaction.class.php
   plog/trunk/class/action/blogaction.class.php
   plog/trunk/class/action/commentaction.class.php
   plog/trunk/class/action/defaultaction.class.php
   plog/trunk/class/action/resourceserveraction.class.php
   plog/trunk/class/action/viewarticleaction.class.php
   plog/trunk/class/action/viewresourceaction.class.php
   plog/trunk/class/bayesian/bayesianfilterutils.class.php
   plog/trunk/class/cache/bloginfomanager.class.php
   plog/trunk/class/cache/cachemanager.class.php
   plog/trunk/class/dao/article.class.php
   plog/trunk/class/dao/articlecategories.class.php
   plog/trunk/class/dao/articlecategory.class.php
   plog/trunk/class/dao/articlecomments.class.php
   plog/trunk/class/dao/articlenotifications.class.php
   plog/trunk/class/dao/articles.class.php
   plog/trunk/class/dao/blogarticles.class.php
   plog/trunk/class/dao/blogcategories.class.php
   plog/trunk/class/dao/blogcategory.class.php
   plog/trunk/class/dao/bloginfo.class.php
   plog/trunk/class/dao/blogs.class.php
   plog/trunk/class/dao/commentscommon.class.php
   plog/trunk/class/dao/customfields/customfield.class.php
   plog/trunk/class/dao/customfields/customfieldcheckboxvalue.class.php
   plog/trunk/class/dao/customfields/customfielddatevalue.class.php
   plog/trunk/class/dao/customfields/customfields.class.php
   plog/trunk/class/dao/customfields/customfieldsvalues.class.php
   plog/trunk/class/dao/customfields/customfieldvalue.class.php
   plog/trunk/class/dao/customfields/customfieldvaluefactory.class.php
   plog/trunk/class/dao/model.class.php
   plog/trunk/class/dao/mylink.class.php
   plog/trunk/class/dao/mylinks.class.php
   plog/trunk/class/dao/mylinkscategories.class.php
   plog/trunk/class/dao/mylinkscategory.class.php
   plog/trunk/class/dao/trackback.class.php
   plog/trunk/class/dao/trackbacks.class.php
   plog/trunk/class/dao/usercomment.class.php
   plog/trunk/class/dao/userdata/baseuserdataprovider.class.php
   plog/trunk/class/dao/userdata/ploguserdataprovider.class.php
   plog/trunk/class/dao/userinfo.class.php
   plog/trunk/class/data/timestamp.class.php
   plog/trunk/class/database/db.class.php
   plog/trunk/class/database/dbobject.class.php
   plog/trunk/class/database/pdb/drivers/pdbdriverbase.class.php
   plog/trunk/class/database/pdb/pdb.class.php
   plog/trunk/class/gallery/dao/galleryalbum.class.php
   plog/trunk/class/gallery/dao/galleryalbums.class.php
   plog/trunk/class/gallery/dao/galleryresource.class.php
   plog/trunk/class/gallery/dao/galleryresourcequotas.class.php
   plog/trunk/class/gallery/dao/galleryresources.class.php
   plog/trunk/class/locale/locales.class.php
   plog/trunk/class/logger/LogUtil.php
   plog/trunk/class/logger/layout/patternlayout.class.php
   plog/trunk/class/net/http/httpvars.class.php
   plog/trunk/class/net/http/session/sessionmanager.class.php
   plog/trunk/class/plugin/pluginbase.class.php
   plog/trunk/class/summary/action/activeaccountaction.class.php
   plog/trunk/class/template/templatesets/templatesets.class.php
   plog/trunk/class/template/templatesets/templatesetstorage.class.php
   plog/trunk/class/view/admin/adminarticlecategorieslistview.class.php
   plog/trunk/class/view/admin/adminblogcategorieslistview.class.php
   plog/trunk/class/view/admin/adminblogsettingsview.class.php
   plog/trunk/class/view/admin/admineditpostview.class.php
   plog/trunk/class/view/admin/adminnewpostview.class.php
   plog/trunk/class/view/admin/adminresourceslistview.class.php
   plog/trunk/class/view/blogview.class.php
   plog/trunk/config/config.properties.php
   plog/trunk/config/logging.properties.php
   plog/trunk/index.php
   plog/trunk/templates/admin/blogcategories.template
   plog/trunk/templates/admin/dashboard.template
   plog/trunk/templates/admin/editlinks.template
   plog/trunk/templates/admin/resources.template
   plog/trunk/wizard.php
Log:
merged plog-1.1-daochanges with the trunk, no more branches from now... it's time to try to push this forward together (though some things might not be working very well yet ;))

*PLEASE* remember to re-run the wizard before trying to run with the new code.


Modified: plog/trunk/class/action/addcommentaction.class.php
===================================================================
--- plog/trunk/class/action/addcommentaction.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/action/addcommentaction.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -162,28 +162,26 @@
         	// we have already checked all the data, so we are sure that everything's in place
             $comments = new ArticleComments();
 			
-			$comment = new UserComment( $this->_articleId, $this->_parentId, $this->_commentTopic, $this->_commentText,
-			                            null, $this->_userName, $this->_userEmail, $this->_userUrl,
+			$comment = new UserComment( $this->_articleId, 
+			                            $this->_blogInfo->getId(),
+			                            $this->_parentId, 
+			                            $this->_commentTopic, 
+			                            $this->_commentText,
+			                            null, 
+			                            $this->_userName, 
+			                            $this->_userEmail, 
+			                            $this->_userUrl,
 									    $clientIp );			
 
-            // check if there is already a comment with the same text, topic and made from the same
-            // IP already in the database because if so, then we will not add the comment that
-            // the user is trying to add (a reload button mistake, perhaps?)
-            if( !$comments->getIdenticalComment( $this->_commentTopic, $this->_commentText,
-                                                 $this->_articleId, $this->_parentId,
-                                                 $this->_userName, $this->_userEmail,
-                                                 $this->_userUrl, $clientIp )) {
-												 
-				// fire an event
-				$this->notifyEvent( EVENT_PRE_COMMENT_ADD, Array( "comment" => &$comment ));
-												 
-				if( !$comments->addComment( $comment )) {
-                	// show an error message if problems
-                    $this->_view = new ErrorView( $this->_blogInfo );
-                    $this->_view->setValue( "message", "error_adding_comment" );
-                    $this->setCommonData();
-                    return false;
-                }
+			// fire an event
+			$this->notifyEvent( EVENT_PRE_COMMENT_ADD, Array( "comment" => &$comment ));
+											 
+			if( !$comments->addComment( $comment )) {
+               	// show an error message if problems
+                $this->_view = new ErrorView( $this->_blogInfo );
+                $this->_view->setValue( "message", "error_adding_comment" );
+                $this->setCommonData();
+                return false;
             }
 			
             // finally, check if there was any user who wanted to be notified of new comments

Modified: plog/trunk/class/action/addtrackbackaction.class.php
===================================================================
--- plog/trunk/class/action/addtrackbackaction.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/action/addtrackbackaction.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -115,7 +115,14 @@
 			// create teh trackback object
 			$now = new Timestamp();
 			$ip = Client::getIp();
-			$trackback = new Trackback( $url, $title, $articleId, $excerpt, $blogName, $now->getTimestamp(), $ip );
+			$trackback = new Trackback( $url, 
+			                            $title, 
+			                            $articleId, 
+			                            $this->_blogInfo->getId(),
+			                            $excerpt, 
+			                            $blogName, 
+			                            $now->getTimestamp(), 
+			                            $ip );
 
 			// this code probably needs some explanation... 
 			// Basically, if the bayesian filter is configured to save spam to the database marked as spam,

Modified: plog/trunk/class/action/admin/adminaddpostaction.class.php
===================================================================
--- plog/trunk/class/action/admin/adminaddpostaction.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/action/admin/adminaddpostaction.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -58,6 +58,7 @@
 			
 			$articles = new Articles();
 			$article->setFields( $this->_getArticleCustomFields());			
+			print_r($article->_customFields);
 			
 			// notifiy about this event
 			$this->notifyEvent( EVENT_PRE_POST_ADD, Array( "article" => &$article ));				
@@ -100,8 +101,15 @@
             // the post to the database
 			$postText = Textfilter::xhtmlize($this->_postText).POST_EXTENDED_TEXT_MODIFIER.Textfilter::xhtmlize($this->_postExtendedText);
 			
-			$article  = new Article( $this->_postTopic, $postText, $this->_postCategories,
-									 $this->_userInfo->getId(), $this->_blogInfo->getId(), $this->_postStatus, 0, Array(), $this->_postSlug );
+			$article  = new Article( $this->_postTopic, 
+			                         $postText, 
+			                         $this->_postCategories,
+									 $this->_userInfo->getId(), 
+									 $this->_blogInfo->getId(), 
+									 $this->_postStatus, 
+									 0, 
+									 Array(), 
+									 $this->_postSlug );
 			// set also the date before it's too late
 			$article->setDateObject( $this->_postTimestamp );
 			$article->setCommentsEnabled( $this->_commentsEnabled );
@@ -183,4 +191,4 @@
             return true;
         }
     }
-?>
+?>
\ No newline at end of file

Modified: plog/trunk/class/action/admin/adminaddresourcealbumaction.class.php
===================================================================
--- plog/trunk/class/action/admin/adminaddresourcealbumaction.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/action/admin/adminaddresourcealbumaction.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -7,6 +7,7 @@
     include_once( PLOG_CLASS_PATH."class/data/validator/integervalidator.class.php" );
     include_once( PLOG_CLASS_PATH."class/gallery/dao/galleryalbums.class.php" );
 	include_once( PLOG_CLASS_PATH."class/template/cachecontrol.class.php" );
+	include_once( PLOG_CLASS_PATH."class/data/timestamp.class.php" );
 
     /**
      * \ingroup Action
@@ -47,7 +48,7 @@
             $this->_parentId = $this->_request->getValue( "parentId" );			
 			
 			// create the album
-        	$albums = new GalleryAlbums();			
+        	$albums = new GalleryAlbums();
 			$t = new Timestamp();
 			$album = new GalleryAlbum( $this->_blogInfo->getId(), $this->_albumName, 
 			                           $this->_albumDescription, 

Modified: plog/trunk/class/action/admin/admindeleteblogaction.class.php
===================================================================
--- plog/trunk/class/action/admin/admindeleteblogaction.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/action/admin/admindeleteblogaction.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -44,6 +44,8 @@
 
         	$this->_disableBlogs();
         }
+        
+        function disableBlog( $blogIn
 
 		/**
 		 * @private
@@ -72,7 +74,9 @@
 						$errorMessage .= $this->_locale->pr("error_blog_is_default_blog", $blogInfo->getBlog())."<br />";
 					}
 					else {
-						if( $blogs->disableBlog( $blogId )) {
+					   // disable the blog
+					    $blogInfo->setStatus( BLOG_STATUS_DISABLED );
+						if( $blogs->updateBlog( $blogInfo )) {
 							$totalOk++;						
 							if( $totalOk < 2 )
 								$successMessage = $this->_locale->pr("blog_deleted_ok", $blogInfo->getBlog());

Modified: plog/trunk/class/action/admin/admindeletecommentaction.class.php
===================================================================
--- plog/trunk/class/action/admin/admindeletecommentaction.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/action/admin/admindeletecommentaction.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -88,7 +88,6 @@
 			// loop through the comments and remove them
             foreach( $this->_commentIds as $commentId ) {
             	// fetch the comment
-                //$comment = $comments->getPostComment( $this->_articleId, $commentId );
 				$comment = $comments->getComment( $commentId );
 				
 				if( !$comment ) {
@@ -101,11 +100,11 @@
 					// check if the comment really belongs to this blog...
 					$article = $comment->getArticle();
 					if( $article->getBlogId() != $this->_blogInfo->getId()) {
-						// if not, then we shouldn't be allowed to remove anything!
+						// if not, then we shouldn't be allowed to remove anything!						
 						$errorMessage .= $this->_locale->pr("error_deleting_comment", $comment->getTopic())."<br/>";
 					}
 					else {
-						if( !$comments->deletePostComment( $article->getId(), $commentId ))
+						if( !$comments->deleteComment( $commentId ))
 							$errorMessage .= $this->_locale->pr("error_deleting_comment", $comment->getTopic())."<br/>";
 						else {
 							$totalOk++;

Modified: plog/trunk/class/action/admin/admindeletelinkcategoryaction.class.php
===================================================================
--- plog/trunk/class/action/admin/admindeletelinkcategoryaction.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/action/admin/admindeletelinkcategoryaction.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -66,7 +66,6 @@
             	// fetch the category
                 $linkCategory = $categories->getMyLinksCategory( $categoryId, $this->_blogInfo->getId());
                 if( $linkCategory ) {
-            		//if( $categories->getNumMyLinksCategory( $categoryId ) > 0 ) {
 					if( $linkCategory->getNumLinks() > 0 ) {
                 		$errorMessage .= $this->_locale->pr("error_links_in_link_category",$linkCategory->getName())."<br/>";
                 	}

Modified: plog/trunk/class/action/admin/admineditlinkcategoryaction.class.php
===================================================================
--- plog/trunk/class/action/admin/admineditlinkcategoryaction.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/action/admin/admineditlinkcategoryaction.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -4,6 +4,7 @@
     include_once( PLOG_CLASS_PATH."class/view/admin/admintemplatedview.class.php" );
 	include_once( PLOG_CLASS_PATH."class/view/admin/adminlinkcategorieslistview.class.php" );
     include_once( PLOG_CLASS_PATH."class/dao/mylinkscategories.class.php" );
+    include_once( PLOG_CLASS_PATH."class/data/validator/integervalidator.class.php" );
 
     /**
      * \ingroup Action

Modified: plog/trunk/class/action/admin/adminnewarticlecategoryaction.class.php
===================================================================
--- plog/trunk/class/action/admin/adminnewarticlecategoryaction.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/action/admin/adminnewarticlecategoryaction.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -36,7 +36,7 @@
             $categories = new ArticleCategories();
 			$blogSettings = $this->_blogInfo->getSettings();
 			$categoriesOrder = $blogSettings->getValue( "categories_order" );
-            $blogCategories = $categories->getBlogCategoriesAdmin( $this->_blogInfo->getId(), false, $categoriesOrder );
+            $blogCategories = $categories->getBlogCategories( $this->_blogInfo->getId(), false, $categoriesOrder );
             $this->_view->setValue( "categories", $blogCategories );
 			// this field should be true by default
 			$this->_view->setValue( "categoryInMainPage", true );

Modified: plog/trunk/class/action/admin/adminnewresourceaction.class.php
===================================================================
--- plog/trunk/class/action/admin/adminnewresourceaction.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/action/admin/adminnewresourceaction.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -45,8 +45,9 @@
         function perform()
         {
             // check that we have at least one album where to put our pictures
-            $albums = new GalleryAlbums();			
-            if( $albums->getNumUserAlbums( $this->_blogInfo->getId()) == 0 ) {
+            $albums = new GalleryAlbums();
+            $blogAlbums = $albums->getNestedAlbumList( $this->_blogInfo->getId());            
+            if( count( $blogAlbums ) == 0 ) {
             	$this->_view = new AdminNewAlbumView( $this->_blogInfo );
                 $this->_view->setErrorMessage( $this->_locale->tr("error_must_create_album_first"));
                 $this->setCommonData();

Modified: plog/trunk/class/action/admin/adminpostmanagementcommonaction.class.php
===================================================================
--- plog/trunk/class/action/admin/adminpostmanagementcommonaction.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/action/admin/adminpostmanagementcommonaction.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -97,8 +97,8 @@
             if( !$this->_config->getValue( "xmlrpc_ping_enabled", false ))
             	return "";
 
-            $blogs = new Blogs();
-            $resultArray = $blogs->updateNotify( $this->_blogInfo );
+            $notifications = new ArticleNotifications();
+            $resultArray = $notifications->updateNotify( $this->_blogInfo );
 			
 			// check to prevent throwing an error if the list is empty
 			if( $resultArray == "" || empty( $resultArray ))

Modified: plog/trunk/class/action/admin/adminresourcesaction.class.php
===================================================================
--- plog/trunk/class/action/admin/adminresourcesaction.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/action/admin/adminresourcesaction.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -4,6 +4,7 @@
 	include_once( PLOG_CLASS_PATH."class/view/admin/adminresourceslistview.class.php" );
 	include_once( PLOG_CLASS_PATH."class/data/validator/integervalidator.class.php" );
 	include_once( PLOG_CLASS_PATH."class/view/admin/adminerrorview.class.php" );
+	include_once( PLOG_CLASS_PATH."class/gallery/dao/galleryresourcestorage.class.php" );
 
     /**
      * \ingroup Action

Modified: plog/trunk/class/action/admin/adminupdateblogsettingsaction.class.php
===================================================================
--- plog/trunk/class/action/admin/adminupdateblogsettingsaction.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/action/admin/adminupdateblogsettingsaction.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -57,7 +57,7 @@
 
         	// fetch the settings from the db and update them accordingly
             $blogs = new Blogs();
-            $blogSettings = $blogs->getBlogSettings( $this->_blogInfo->getId());
+            $blogSettings = $this->_blogInfo->getSettings();
             $blogSettings->setValue( "locale", $this->_request->getValue( "blogLocale" ));
             $blogSettings->setValue( "show_posts_max", $this->_request->getValue( "blogMaxMainPageItems" ));
             $blogSettings->setValue( "recent_posts_max", $this->_request->getValue( "blogMaxRecentItems" ));
@@ -81,7 +81,7 @@
             $blogs = new Blogs();
 			$this->notifyEvent( EVENT_PRE_BLOG_UPDATE, Array( "blog" => &$this->_blogInfo ));
             $blogInfoManager = BlogInfoManager::getBlogInfoManager();
-            if( !$blogInfoManager->updateBlogInfo( $this->_blogInfo->getId(), $this->_blogInfo )) {
+            if( !$blogInfoManager->updateBlogInfo( $this->_blogInfo )) {
             	$this->_view = new AdminBlogSettingsView( $this->_blogInfo );
                 $this->_view->setErrorMessage( $this->_locale->tr("error_updating_settings"));
                	$this->setCommonData();

Modified: plog/trunk/class/action/admin/adminupdateeditblogaction.class.php
===================================================================
--- plog/trunk/class/action/admin/adminupdateeditblogaction.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/action/admin/adminupdateeditblogaction.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -52,15 +52,6 @@
 			$this->setValidationErrorView( $view );
         }
 		
-		/**
-		 * updates the users of the blog
-		 * @private
-		 */
-		function updateBlogUsers()
-		{
-
-		}
-
         /**
          * Carries out the specified action
          */
@@ -117,7 +108,7 @@
 
             // and now update the settings in the database
 			$this->notifyEvent( EVENT_PRE_BLOG_UPDATE, Array( "blog" => &$blogInfo ));
-            if( !$blogs->updateBlog( $blogInfo->getId(), $blogInfo )) {
+            if( !$blogs->updateBlog( $blogInfo )) {
             	$this->_view = new AdminSiteBlogsListView( $this->_blogInfo );
                 $this->_view->setErrorMessage( $this->_locale->pr( "error_updating_blog_settings", $blogInfo->getBlog()));
                	$this->setCommonData();

Modified: plog/trunk/class/action/admin/adminupdatelinkcategoryaction.class.php
===================================================================
--- plog/trunk/class/action/admin/adminupdatelinkcategoryaction.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/action/admin/adminupdatelinkcategoryaction.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -5,6 +5,7 @@
 	include_once( PLOG_CLASS_PATH."class/view/admin/adminlinkcategorieslistview.class.php" );
 	include_once( PLOG_CLASS_PATH."class/data/validator/stringvalidator.class.php" );
     include_once( PLOG_CLASS_PATH."class/dao/mylinkscategories.class.php" );
+    include_once( PLOG_CLASS_PATH."class/data/validator/integervalidator.class.php" );    
 
     /**
      * \ingroup Action

Modified: plog/trunk/class/action/blogaction.class.php
===================================================================
--- plog/trunk/class/action/blogaction.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/action/blogaction.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -265,4 +265,4 @@
 			return true;
 		}
     }
-?>
+?>
\ No newline at end of file

Modified: plog/trunk/class/action/commentaction.class.php
===================================================================
--- plog/trunk/class/action/commentaction.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/action/commentaction.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -72,7 +72,7 @@
 			$postComments = $comments->getPostComments( $article->getId());
 			if( $this->_parentId > 0 ) {
 				// get a pre-set string for the subject field, for those users interested
-				$comment = $comments->getPostComment( $article->getId(), $this->_parentId );
+				$comment = $comments->getComment( $this->_parentId );
 				// create the string
 				if( $comment ) {
 					$replyString = $this->_locale->tr("reply_string").$comment->getTopic();

Modified: plog/trunk/class/action/defaultaction.class.php
===================================================================
--- plog/trunk/class/action/defaultaction.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/action/defaultaction.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -178,7 +178,7 @@
 				$blogArticles = $this->articles->getBlogArticles( $blogId, $this->_date,
 								$this->_postAmount, $this->_categoryId,
 								POST_STATUS_PUBLISHED, $this->_userId, $todayTimestamp );
-			}
+			}			
 
             // if we couldn't fetch the articles, send an error and quit
             if( count($blogArticles) == 0 ) {

Modified: plog/trunk/class/action/resourceserveraction.class.php
===================================================================
--- plog/trunk/class/action/resourceserveraction.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/action/resourceserveraction.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -7,7 +7,6 @@
 	include_once( PLOG_CLASS_PATH."class/config/config.class.php" );
 	include_once( PLOG_CLASS_PATH."class/net/http/httpcache.class.php" );
     include_once( PLOG_CLASS_PATH."class/gallery/dao/galleryresources.class.php" );	
-	include_once( PLOG_CLASS_PATH."class/net/url.class.php" );
     include_once( PLOG_CLASS_PATH."class/security/pipeline.class.php" );
     include_once( PLOG_CLASS_PATH."class/plugin/pluginmanager.class.php" );	
 

Modified: plog/trunk/class/action/viewarticleaction.class.php
===================================================================
--- plog/trunk/class/action/viewarticleaction.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/action/viewarticleaction.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -78,12 +78,7 @@
 		 * updates the article referrers, given a slug
 		 */
 		function _updateArticleReferrersByTitle($slug){
-			$id = 0;
-			$article = $this->articles->getBlogArticleByTitle($slug);
-			if ( $article )
-			{
-				$id = $article->getId();
-			}
+			$id = $this->articles->getArticleIdFromName($slug);
 			// if the article isn't found, we will save a referrer to
 		    // the main page, since $id will be 0.
 			$this->_updateArticleReferrersById($id);

Modified: plog/trunk/class/action/viewresourceaction.class.php
===================================================================
--- plog/trunk/class/action/viewresourceaction.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/action/viewresourceaction.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -55,7 +55,6 @@
         function perform()
         {
         	$galleryResources = new GalleryResources();
-			$galleryAlbums = new GalleryAlbums();
 			
 			// initialize the view
             $this->_view = new BlogView( $this->_blogInfo,
@@ -74,6 +73,8 @@
 			
 			// try to find the album to which this resource belongs
 			if( $this->_albumName ) {
+			    include_once( PLOG_CLASS_PATH."class/gallery/dao/galleryalbums.class.php" );			
+				$galleryAlbums = new GalleryAlbums();				
 				$album = $galleryAlbums->getAlbumByName( $this->_albumName, $this->_blogInfo->getId(), false, true );
 				if( !$album ) {
 					$this->_view = new ErrorView( $this->_blogInfo );

Modified: plog/trunk/class/bayesian/bayesianfilterutils.class.php
===================================================================
--- plog/trunk/class/bayesian/bayesianfilterutils.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/bayesian/bayesianfilterutils.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -32,29 +32,7 @@
          */
         function markArticlesAsNonSpam( $blogId = 0 )
         {
-        	// first, gather all posts that should be used to gather "good"
-            // for for the filter
-            $articles = new Articles();
-            if( $blogId == 0 )
-            	$blogArticles = $articles->getAllArticles();
-            else
-            	$blogArticles = $articles->getBlogArticles( $blogId );
-
-            // now, loop through each one of them marking the contents as
-            // non-spam
-            $bayesian = new BayesianFilterCore();
-            foreach( $blogArticles as $article ) {
-            	$owner = $article->getUserInfo();
-                $bayesian->train( $article->getBlog(),
-                                  $article->getTopic(),
-                                  $article->getText(),
-                                  $owner->getUsername(),
-                                  $owner->getEmail(),
-                                  "",
-                                  false );
-            }
-
-            return true;
+            die("is this even used!?");
         }
 
         /**
@@ -62,35 +40,7 @@
          */
         function _getAllComments( $blogId = 0 )
         {
-        	// we shouldn't be doing things like this but it actually makes things
-            // easier... we need to find the blog to which a comment belongs, but turns
-            // out that there is no reference to the blog table from the comment table...
-            // the solution, as you can see, is to run a nice join query that will
-            // give us as much information as we need :)
-        	$query = "SELECT c.id AS id, c.topic AS topic, c.text AS text,
-                     c.user_email AS user_email, c.user_name AS user_name,
-                     c.user_url AS user_url, a.id AS article_id, a.blog_id AS blog_id
-                     FROM ".$this->getPrefix()."articles_comments AS c,".$this->getPrefix()."articles AS a
-                     WHERE c.article_id = a.id";
-
-        	if( $blogId != 0 ) {
-            	$query .= " AND a.blog_id = $blogId";
-            }
-
-            $result = $this->Execute( $query );
-
-            $comments = Array();
-
-            // return empty array if problems...
-            if( !$result )
-            	return $comments;
-
-            // or continue anyway
-            while ($row = $result->FetchRow()) {
-                array_push( $comments, $row );
-            }
-
-            return $comments;
+            die("is this even used!?");
         }
 
         /**
@@ -104,23 +54,7 @@
          */
         function markCommentsAsNonSpam( $blogId = 0 )
         {
-        	// first, make an array with the comments that should be marked
-            $comments = $this->_getAllComments( $blogId );
-
-            // now, loop through each one of them marking the contents as
-            // non-spam
-            $bayesian = new BayesianFilterCore();
-            foreach( $comments as $comment ) {
-                $bayesian->train( $comment["blog_id"],
-                                  $comment["topic"],
-                                  $comment["text"],
-                                  $comment["user_name"],
-                                  $comment["user_email"],
-                                  $comment["user_url"],
-                                  false );
-            }
-
-            return true;
+            die("is this even used!?");        
         }
     }
 ?>
\ No newline at end of file

Modified: plog/trunk/class/cache/bloginfomanager.class.php
===================================================================
--- plog/trunk/class/cache/bloginfomanager.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/cache/bloginfomanager.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -34,11 +34,11 @@
             return $blogInfo;
         }
 
-        function updateBlogInfo( $blogId, $blogInfo )
+        function updateBlogInfo( $blogInfo )
         {
             require_once( PLOG_CLASS_PATH . "class/dao/blogs.class.php" );
             $blogs = new Blogs(); 
-            return $blogs->updateBlog( $blogId, $blogInfo );
+            return $blogs->updateBlog( $blogInfo );
 
             // remove all cached info
             $cache =& CacheManager::getCache();

Modified: plog/trunk/class/cache/cachemanager.class.php
===================================================================
--- plog/trunk/class/cache/cachemanager.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/cache/cachemanager.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -12,16 +12,13 @@
     define( "CACHE_USERIDBYNAME",      "userinfo_idbyname" );
     define( "CACHE_BLOGINFOS",         "bloginfo" );
     define( "CACHE_BLOGIDBYNAME",      "bloginfo_idbyname" );
-    define( "CACHE_ARTICLETEXT",       "article_text" );
     define( "CACHE_TRACKBACKS",        "trackbacks" );
     define( "CACHE_NUMTRACKBACKS",     "trackbacks_size" );
     define( "CACHE_CONFIGDBSTORAGE",   "config_db_storage" );
     define( "CACHE_SITEADMINS",        "permissions_siteadmin" );
     define( "CACHE_BLOGLINKS",         "blogLinks" );
     define( "CACHE_MYLINKS",           "myBlogLinks" );
-    define( "CACHE_ARTICLES",          "articles" );
-    define( "CACHE_ARTICLETITLES",     "articles_titles" );
-
+    
     // :TODO: implement a cache-lifetime per cache-category, so e.g. blogInfo or
     //        locales have a lifetime of several days, whereas articles, comments,
     //        etc will only be cached for an hour.

Modified: plog/trunk/class/dao/article.class.php
===================================================================
--- plog/trunk/class/dao/article.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/article.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -12,7 +12,7 @@
 	 * \ingroup DAO
      * This class represents an article from the database, and provides methods to access all its objects.
      */
-	class Article extends Object 
+	class Article extends DbObject 
 	{
 
         /**
@@ -26,16 +26,19 @@
         var $_categories;
 		var $_user;
 		var $_date;
+		var $_modificationDate;
 		var $_timestamp;
+		var $_modificationTimestamp;
 		var $_comments;
 		var $_userInfo;
 		var $_blog;
 		var $_blogInfo;
 		var $_status;
         var $_totalComments;
-		var $_totalRealComments;
+		var $_numComments;
         var $_numReads;
         var $_numTrackbacks;
+        var $_totalTrackbacks;
         var $_properties;
 		var $_timeOffset;
 		var $_fields;
@@ -66,13 +69,16 @@
 			$this->_topic    = $topic;
 			$this->_text     = $text;
 			$this->_categoryIds = $categories;
+			$this->_categories = null;
 			$this->_user     = $user;
 			$this->_blog     = $blog;
 			$this->_id       = $id;
 			$this->_status   = $status;
 			$this->_comments = null;
             $this->_totalComments = 0;
+            $this->_numComments = 0;
             $this->_numTrackbacks = 0;
+            $this->_totalTrackbacks = 0;
             $this->_numReads = $numReads;
 			if( $slug == "" ) {
 	            include_once( PLOG_CLASS_PATH.'class/data/textfilter.class.php' );
@@ -83,6 +89,8 @@
 			// by default it'll have current time
 			$this->_timestamp = new Timestamp();
 			$this->_date      = $this->_timestamp->getTimestamp();
+			$this->_modificationTimestamp = new Timestamp();
+			$this->_modificationDate = $this->_timestamp->getTimestamp();
 			//$this->_timestamp = 0;
 			//$this->_date = 0;
             $this->_properties = $properties;
@@ -90,8 +98,23 @@
 			$this->_fields = null;
 			$this->_trackbacks = null;
 			$this->_userInfo = null;
+			$this->_blogInfo = null;
 
-            //print_r($this);
+			$this->_pk = "id";
+			$this->_fields = Array(
+			    "date" => "getDate",
+			    "modification_date" => "getModificationDate",
+			    "user_id" => "getUserId",
+			    "blog_id" => "getBlogId",
+			    "status" => "getStatus",
+			    "num_reads" => "getNumReads",
+			    "properties" => "getProperties",
+			    "slug" => "getPostSlug",
+			    "num_comments" => "getTotalComments",
+			    "num_trackbacks" => "getTotalTrackbacks",
+			    "num_nonspam_trackbacks" => "getNumTrackbacks",
+			    "num_nonspam_comments" => "getNumComments"
+			);
 		}
 
         /**
@@ -198,6 +221,14 @@
          */
         function getCategories()
         {
+        	if( $this->_categories == null ) {
+        		include_once( PLOG_CLASS_PATH."class/dao/articlecategories.class.php" );        			
+        		foreach( $this->getCategoryIds() as $categoryId ) {
+        			if(( $category = $categories->getCategory( $categoryId )))
+	        			$this->_categories[] = $category;
+        		}
+        	}
+        	
         	return $this->_categories;
         }
 		
@@ -386,7 +417,13 @@
          */
 		function getBlogInfo()
 		{
-			return $this->_blogInfo;
+			if( $this->_blogInfo == null ) {
+				include_once( PLOG_CLASS_PATH."class/dao/blogs.class.php" );
+				$blogs = new Blogs();
+				$this->_blogInfo = $blogs->getBlogInfo( $this->getBlogId());
+			}
+			
+			return( $this->_blogInfo );
 		}
 
         /**
@@ -553,60 +590,44 @@
         }
 
         /**
+         * Returns the total number of comments that this post has (only the number!!)
+         *
+         * @return An integer containing the total number of comments that this post has.
+         */
+		function getTotalComments()
+		{
+			return( $this->_totalComments );
+		}
+		
+        /**
          * Returns the number of comments that this post has (only the number!!)
          *
-		 * @param onlyActive return only the number of active (as in non-spam, etc)
          * @return An integer containing the number of comments that this post has.
          */
-		function getTotalComments( $onlyActive = true )
+		function getNumComments()
 		{
-			// trigger the loading of the comments
-			$this->getComments( $onlyActive );			
-		
-			if( $onlyActive ) {
-				$num = 0;
-				foreach( $this->_comments as $comment ) {
-					if( $comment->getStatus() == COMMENT_STATUS_NONSPAM )
-						$num++;
-				}
-			}
-			else
-				$num = count( $this->_comments );
-				
-			return( $num );
-		}
+			return( $this->_numComments );
+		}		
 
         /**
+         * Returns the total number of trackback pings that this post has received.
+         *
+         * @return An integer representing the number of trackback pings.
+         */
+		function getTotalTrackbacks()
+		{
+			return( $this->_totalTrackbacks );
+		}
+		
+        /**
          * Returns the number of trackback pings that this post has received.
          *
 		 * @param onlyActive return only the number of active (as in non-spam, etc)		 
          * @return An integer representing the number of trackback pings.
-         */
-        function getNumTrackbacks( $onlyActive = true )
-        {
-			// trigger the loading of the comments
-			$this->getTrackbacks( $onlyActive );
-		
-			if( $onlyActive ) {
-				$num = 0;
-				foreach( $this->_trackbacks as $trackback ) {
-					if( $trackback->getStatus() == COMMENT_STATUS_NONSPAM )
-						$num++;
-				}
-			}
-			else
-				$num = count( $this->_trackbacks );
-				
-			return( $num );
-        }
-		
-		/**
-		 * alias for the one above
-		 * @see getNumTrackbacks
-		 */
-		function getTotalTrackbacks( $onlyActive = true )
+         */		
+		function getNumTrackbacks()
 		{
-			return( $this->getNumTrackbacks( $onlyActive ));
+			return( $this->_numTrackbacks );
 		}
 
         /**
@@ -618,6 +639,14 @@
         {
         	$this->_totalComments = $totalComments;
         }
+        
+        /**
+         * @private
+         */
+        function setNumComments( $numComments )
+        {
+        	$this->_numComments = $numComments;
+        }
 		
         /**
          * @private
@@ -626,6 +655,14 @@
         {
         	$this->_numTrackbacks = $numTrackbacks;
         }
+        
+        /**
+         * @private
+         */
+        function setTotalTrackbacks( $totalTrackbacks )
+        {
+        	$this->_totalTrackbacks = $totalTrackbacks;
+        }        
 
         /**
          * @private
@@ -638,6 +675,22 @@
 
 			$this->_timestamp = new Timestamp( $newDate );
 		}
+		
+		function setModificationDate( $newDate )
+		{
+			$this->_modificationDate = $newDate;
+			$this->_modificationTimestamp = new Timestamp( $newDate );
+		}
+		
+		function getModificationDate()
+		{
+			return( $this->_modificationDate );
+		}
+		
+		function getModificationTimestamp()
+		{
+			return( $this->_modificationTimestamp );
+		}
 
         /**
          * Returns the Timestamp object representing the date when this post was posed.
@@ -726,7 +779,7 @@
 		 */
 		function setFields( $fields )
 		{
-			$this->_fields = $fields;
+			$this->_customFields = $fields;
 			
 			return true;
 		}
@@ -736,17 +789,17 @@
 		 *
 		 * @return An array of CustomFieldValue objects
 		 */
-		function getFields()
+		function getCustomFields()
 		{
-			if( is_null($this->_fields) ) {
+			if( is_null($this->_customFields) ) {
                 include_once( PLOG_CLASS_PATH.'class/dao/customfields/customfieldsvalues.class.php' );	
 				// get the custom fields
 				$customFields = new CustomFieldsValues();
 				$fields = $customFields->getArticleCustomFieldsValues( $this->getId(), $this->getBlog());
-				$this->setFields( $fields );			
-			}
+				$this->setFields( $fields );
+			}						
 			
-			return $this->_fields;
+			return $this->_customFields;
 		}
 		
 		/**
@@ -759,7 +812,7 @@
 		{
 			// if fields haven't been loaded yet, do so now
 			if( is_null($this->_fields) )
-				$this->getFields();
+				$this->getCustomFields();
 		
 			return $this->_fields["$fieldName"];
 		}
@@ -774,7 +827,7 @@
 		{
 			// if fields haven't been loaded yet, do so now
 			if( is_null($this->_fields) )
-				$this->getFields();		
+				$this->getCustomFields();		
 		
 			$fieldName = $fieldValue->getName();
 			$this->_fields["$fieldName"] = $fieldValue;
@@ -853,18 +906,6 @@
 		}
 
 		/**
-		 * left here for compatilibity reasons, but please use getDateObject
-		 * and then Locale::formatDate for formatting dates
-		 * @deprecated
-		 * @see Locale::formatDate
-		 * @see Article::getDateObject
-		 */
-		function getDay()
-		{
-			return( $this->_timestamp->getDay());
-		}
-		
-		/**
 		 * returns the previous article in time
 		 *
 		 * @return an Article object representing the previous article, in time, in the database

Modified: plog/trunk/class/dao/articlecategories.class.php
===================================================================
--- plog/trunk/class/dao/articlecategories.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/articlecategories.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -14,6 +14,14 @@
 	define( "BLOG_CATEGORIES_ALPHABETICAL_ORDER", 4 );
 	define( "BLOG_CATEGORIES_REVERSE_ALPHABETICAL_ORDER", 5 );
 	define( "BLOG_CATEGORIES_MOST_ARTICLES_FIRST", 6 );
+	
+	/**
+	 * cache ids used by this class
+	 */
+	define( "CACHE_ARTICLE_CATEGORIES", "article_categories" );
+	define( "CACHE_ARTICLE_CATEGORIES_BYNAME", "article_categories_byname" );
+	define( "CACHE_ARTICLE_CATEGORIES_BLOG", "article_categories_blog" );
+	define( "CACHE_ARTICLE_CATEGORIES_LINK", "article_categories_link" );
 
 	/**
 	 * \ingroup DAO
@@ -30,9 +38,8 @@
     	function ArticleCategories()
         {
         	$this->Model();
-
-            $this->totalCategories = Array();
-            $this->cache = Array();
+        	
+        	$this->table = $this->getPrefix()."articles_categories";
         }
 
         /**
@@ -44,18 +51,15 @@
          */
         function getCategory( $categoryId, $blogId = -1 )
         {
-        	// check if we already loaded that category
-            if( isset($this->cache[$categoryId])) {
-            	return $this->cache[$categoryId];
-            }
-
-            // if not, do the normal process...
-            $query = "SELECT * FROM ".$this->getPrefix()."articles_categories WHERE id = ".Db::qstr($categoryId);
-            if( $blogId != -1 )
-            	$query .= " AND blog_id = ".$blogId;
-            $query .= ";";
-
-            return $this->_getCategoryFromQuery( $query );
+        	$category = $this->get( "id", $categoryId, 
+        	                        CACHE_ARTICLE_CATEGORIES,
+        	                        Array( CACHE_ARTICLE_CATEGORIES_BYNAME => "getMangledName" ));
+        	if( !$category )
+        		return false;
+        	if( $blogId > -1 && $category->getBlogId() != $blogId )
+        		return false;
+        		
+        	return( $category );
         }
         
         /**
@@ -67,70 +71,18 @@
          */
         function getCategoryByName( $categoryName, $blogId = -1 )
         {
-            // if not, do the normal process...
-            $query = "SELECT * FROM ".$this->getPrefix()."articles_categories WHERE 
-                      mangled_name = '".Db::qstr($categoryName)."'";
-            if( $blogId != -1 )
-            	$query .= " AND blog_id = ".$blogId;
-            $query .= ";";
-        
-            return $this->_getCategoryFromQuery( $query );
+        	$category = $this->get( "mangled_name", $categoryName, 
+        	                        CACHE_ARTICLE_CATEGORIES_BYNAME,
+        	                        Array( CACHE_ARTICLE_CATEGORIES => "getId" ));
+        	if( !$category )
+        		return false;
+        	if( $blogId > -1 && $category->getBlogId() != $blogId )
+        		return false;
+        		
+        	return( $category );        	                        
         }
         
         /**
-         * @private
-         */
-        function _getCategoryFromQuery( $query )
-        {
-            $result = $this->Execute( $query );
-
-            if( !$result )
-            	return false;
-
-            if( $result->RowCount() == 0 )
-            	return false;
-
-            $row = $result->FetchRow($result);
-            if( !array_key_exists('num_articles', $row) )
-                $row['num_articles'] = 0;
-            $category = $this->_fillCategoryInformation( $row );
-            $categoryId = $category->getId();
-
-            // ...and store the result
-            $this->cache[$categoryId] = $category;
-
-            return $category;        
-        }
-
-        /**
-         * Returns all the categories in the database
-         *
-		 * @param onlyInMainPage Whether we should return only the categories that are meant to appear in the 
-		 * main page. Disabled by default.
-         * @return An array containing <b>all</b> the categories from the database.
-         */
-        function getAllCategories( $onlyInMainPage = false )
-        {
-			$query = "SELECT * FROM ".$this->getPrefix()."articles_categories ";
-			if( $onlyInMainPage ) 
-				$query .= " WHERE in_main_page = 1 ";
-			$query .= " ORDER BY id ASC;";
-
-			$result = $this->Execute( $query );
-			
-			if( !$result )
-				return Array();
-
-			$categories = array();
-			while( $row = $result->FetchRow( $result )) {
-            	$category = $this->_fillCategoryInformation( $row );
-                $categories[$category->getId()] = $category;
-            }
-
-			return $categories;
-        }
-
-        /**
          * Returns the categories that belong to a given blog
          *
          * @param blogId The identifer of the blog from which we want to fetch the
@@ -158,152 +110,56 @@
          */
         function getBlogCategories( $blogId, $onlyInMainPage = false, $order = BLOG_CATEGORIES_DEFAULT_ORDER, $searchTerms = "", $page = -1, $itemsPerPage = 15 )
         {
-			// this part of the query is the same in all the cases
-			$prefix = $this->getPrefix();		
-			$query = "SELECT c.id AS id, c.name AS name, c.url AS url, c.blog_id AS blog_id, 
-				          c.last_modification AS last_modification, c.in_main_page AS in_main_page, 
-						  c.parent_id AS parent_id, c.description AS description, c.properties AS properties, 
-						  c.mangled_name AS mangled_name, IF(a.id IS NULL, 0, COUNT(*)) AS num_articles, a.date AS last_update 
-						  FROM {$prefix}articles_categories c LEFT JOIN {$prefix}article_categories_link l
-						  ON c.id=l.category_id LEFT JOIN {$prefix}articles a ON a.id = l.article_id";
-						  
-			if( $onlyInMainPage )
-				$whereMainPage .= "c.in_main_page = 1 ";
-			if( $searchTerms )
-			    $whereSearch = $this->buildSearchCondition( $searchTerms );
-			$whereBlogId = 	"c.blog_id = '".Db::qstr($blogId)."'";
+			$categories = $this->getMany( "blog_id",
+			                              $blogId,
+			                              CACHE_ARTICLE_CATEGORIES_BLOG,
+			                              Array( CACHE_ARTICLE_CATEGORIES => "getId",
+			                                     CACHE_ARTICLE_CATEGORIES_BYNAME => "getMangledName" ),
+			                              $page,
+			                              $itemsPerPage );
+			                              
+			if( !$categories )
+				return Array();
 			
-			$where = $this->buildWhereCondition( Array( $whereMainPage, $whereSearch, $whereBlogId ));
-				
-			$query .= " $where GROUP BY c.id ";
-			
-			// and now we simply have to change select the correct way of ordering things
-			if( $order == BLOG_CATEGORIES_OLDEST_FIRST ) {
-				$query .= " ORDER BY c.last_modification ASC;";
-			}
-			elseif( $order == BLOG_CATEGORIES_NEWEST_FIRST ) {
-				$query .= " ORDER BY c.last_modification DESC;";
-			}
-			elseif( $order == BLOG_CATEGORIES_ALPHABETICAL_ORDER ) {
-				$query .= " ORDER BY c.name ASC";
-			}
-			elseif( $order == BLOG_CATEGORIES_REVERSE_ALPHABETICAL_ORDER ) {
-				$query .= " ORDER BY c.name DESC";
-			}
-			elseif( $order == BLOG_CATEGORIES_MOST_ARTICLES_FIRST ) {
-				$query .= " ORDER BY num_articles DESC, name ASC;";
-			}
-			elseif( $order == BLOG_CATEGORIES_MOST_RECENT_UPDATED_FIRST ) {
-				$query .= "ORDER BY last_update DESC, name ASC;";
-			}
-			
-			return $this->_getBlogCategoriesFromQuery( $query, $page, $itemsPerPage );
-		}
-		
-		/**
-		 * @see Model::buildSearchCondition
-		 */
-		function buildSearchCondition( $searchTerms )
-		{
-		    $searchTerms = trim($searchTerms);
-		    $searchCond = "(description LIKE '%".Db::qstr($searchTerms)."%' OR name LIKE '%".Db::qstr($searchTerms)."%')";
-		    
-		    return( $searchCond );
+			/**
+			 * :TODO:
+			 * implement the ordering conditions!
+			 */
+
+            $result = Array();
+            if( $onlyInMainPage && $categories ) {
+            	foreach( $categories as $category )
+            		if( $category->getInMainPage())
+            			$result[] = $categories;
+            }
+            else
+            	$result = $categories;
+            	
+            return( $result );
 		}		
 		
 		/**
-		 * @see getBlogCategories
-		 */
-        function getBlogCategoriesAdmin( $blogId, $onlyInMainPage = false, $order = BLOG_CATEGORIES_DEFAULT_ORDER, $searchTerms = "", $page = -1, $itemsPerPage = 15 )
-        {
-			// this part of the query is the same in all the cases
-			$prefix = $this->getPrefix();			
-			$query = "SELECT c.id AS id, c.name AS name, c.url AS url, c.blog_id AS blog_id, 
-				          c.last_modification AS last_modification, c.in_main_page AS in_main_page, 
-						  c.parent_id AS parent_id, c.properties AS properties, c.description AS description,
-						  c.mangled_name AS mangled_name, IF(a.id IS NULL, 0, COUNT(*)) AS num_articles, a.date AS last_update 
-						  FROM {$prefix}articles_categories c LEFT JOIN {$prefix}article_categories_link l
-						  ON c.id=l.category_id LEFT JOIN {$prefix}articles a ON a.id = l.article_id";
-						  
-			  if( $onlyInMainPage )
-			  	$whereMainPage .= "c.in_main_page = 1 ";
-			  if( $searchTerms )
-			      $whereSearch = $this->buildSearchCondition( $searchTerms );
-			  $whereBlogId = 	"c.blog_id = '".Db::qstr($blogId)."'";
-
-			  $where = $this->buildWhereCondition( Array( $whereMainPage, $whereSearch, $whereBlogId ));
-			  	
-			  $query .= " $where GROUP BY c.id ";
-			
-			// and now we simply have to change select the correct way of ordering things
-			if( $order == BLOG_CATEGORIES_OLDEST_FIRST ) {
-				$query .= " ORDER BY c.last_modification ASC";
-			}
-			elseif( $order == BLOG_CATEGORIES_NEWEST_FIRST ) {
-				$query .= " ORDER BY c.last_modification DESC";
-			}
-			elseif( $order == BLOG_CATEGORIES_ALPHABETICAL_ORDER ) {
-				$query .= " ORDER BY c.name ASC";
-			}
-			elseif( $order == BLOG_CATEGORIES_REVERSE_ALPHABETICAL_ORDER ) {
-				$query .= " ORDER BY c.name DESC";
-			}
-			elseif( $order == BLOG_CATEGORIES_MOST_ARTICLES_FIRST ) {
-				$query .= " ORDER BY num_articles DESC, name ASC";
-			}
-			elseif( $order == BLOG_CATEGORIES_MOST_RECENT_UPDATED_FIRST ) {
-				$query .= "ORDER BY last_update DESC, name ASC";
-			}
-			
-			return $this->_getBlogCategoriesFromQuery( $query, $page, $itemsPerPage );
-        }
-		
-		/**
 		 * @private
 		 */
-		function _getBlogCategoriesFromQuery( $query, $page = -1, $itemsPerPage = DEFAULT_ITEMS_PER_PAGE )
+		function mapRow( $row )
 		{
-            $result = $this->Execute( $query, $page, $itemsPerPage );
+        	$category = new ArticleCategory( $row["name"],
+                                             $row["url"],
+                                             $row["blog_id"],
+                                             $row["in_main_page"],
+											 $row["description"],
+                                             $row["num_articles"],
+											 unserialize($row["properties"]),
+                                             $row["id"]);
+            $category->setNumArticles( $row["num_articles"] );
+            $category->setNumPublishedArticles( $row["num_published_articles"] );
+            $category->setLastModification( $row["last_modification"] );
 
-            if( !$result )
-            	return false;
-
-            $categories = Array();
-            while( $row = $result->FetchRow( $result )) {
-            	$category = $this->_fillCategoryInformation( $row );
-                $categories[$category->getId()] = $category;
-
-                // we can cache this information for later...
-                $this->cache[$category->getId()] = $category;
-            }
-
-            return $categories;		
+            return( $category );
 		}
 		
 
         /**
-         * Private function that takes an associative array from the database and returns
-         * an object of the type ArticleCategory properly filled
-         *
-         * @param query_result Resulting resource of executing a query
-         * @return Returns an ArticleCategory object
-		 * @private
-         */
-        function _fillCategoryInformation( $query_result )
-        {
-        	$category = new ArticleCategory( $query_result["name"],
-                                             $query_result["url"],
-                                             $query_result["blog_id"],
-                                             $query_result["in_main_page"],
-											 $query_result["description"],
-                                             $query_result["num_articles"],
-											 unserialize($query_result["properties"]),
-                                             $query_result["id"]);											 
-
-            return $category;
-        }
-
-        /**
          * Adds an article category to the database.
          *
          * @param category A Category object with all the information needed to add it
@@ -313,57 +169,14 @@
          */
         function addArticleCategory( $articleCategory )
         {
-        	$query = "INSERT INTO ".$this->getPrefix()."articles_categories
-                      (name,url,blog_id,in_main_page,properties,mangled_name,description) VALUES 
-					  ('".Db::qstr($articleCategory->getName()).
-                      "','".Db::qstr($articleCategory->getURL()).
-                      "','".Db::qstr($articleCategory->getBlogId()).
-                      "','".Db::qstr($articleCategory->isInMainPage()).
-					  "','".Db::qstr(serialize($articleCategory->getProperties())).
-					  "', '".TextFilter::urlize($articleCategory->getName()).
-					  "', '".Db::qstr($articleCategory->getDescription()).
-					  "');";
-
-            $result = $this->Execute( $query );
-
-            if( !$result )
-            	return false;
-				
-			// return the id of the last row inserted
-			return $this->_db->Insert_ID();
+        	if(( $result = $this->add( $articleCategory, Array( CACHE_ARTICLE_CATEGORIES => "getId", CACHE_ARTICLE_CATEGORIES_BYNAME => "getMangledName" )))) {
+        		$this->_cache->removeData( $articleCategory->getBlogId(), CACHE_ARTICLE_CATEGORIES_BLOG, $articleCategory );
+        	}
+        	
+        	return( $result );
         }
 
         /**
-         * Returns how many articles have been classified under this category
-         *
-         * @param categoryId The identifier of that category.
-		 * @param status The status that posts of that category should have. If none specified,
-		 * POST_STATUS_PUBLISHED will be used.
-		 * @param searchTerms
-         * @return The number of articles, or 0 if none.
-         */
-        function getNumArticlesCategory( $categoryId, $status = POST_STATUS_PUBLISHED )
-        {
-            $prefix = $this->getPrefix();
-       		$query1 = "SELECT COUNT(*) AS 'count' FROM
-       		           {$prefix}article_categories_link AS l, {$prefix}articles AS a
-       		           WHERE l.article_id = a.id AND l.category_id = '".Db::qstr($categoryId)."'";
-    		if( $status != POST_STATUS_ALL )
-    			$query1 .= " AND a.status = '".Db::qstr($status)."'";
-
-    		$result = $this->Execute( $query1 );
-		
-    		if( !$result )
-    			return 0;
-			
-    		$row = $result->FetchRow();
-    		$total = $row["count"];
-    		if( $total == "" ) $total = 0;
-		
-    		return( $total );
-        }
-
-        /**
          * Removes a category from the database. We should check <b>beforehand</b> that such category
          * does not have any article classified under it, since then we would have problems
          * with the database.
@@ -374,15 +187,11 @@
          */
         function deleteCategory( $categoryId, $blogId )
         {
-        	$query = "DELETE FROM ".$this->getPrefix()."articles_categories
-			          WHERE id = ".Db::qstr($categoryId)." AND blog_id = ".$blogId;
-
-            $result = $this->Execute( $query );
-
-            if( !$result )
-            	return false;
-            else
-            	return true;
+        	$category = $this->getCategory( $categoryId, $blogId );
+        	if( $category )
+        		return( $this->delete( "id", $categoryId ));
+        	else
+        		return( false );
         }
 
         /**
@@ -392,19 +201,15 @@
          */
         function deleteBlogCategories( $blogId )
         {
-            // first delete all article category links
-            $query = "DELETE FROM ".$this->getPrefix()."article_categories_link 
-                      WHERE category_id IN 
-                          (SELECT id FROM ".$this->getPrefix()."articles_categories 
-                              WHERE blog_id = $blogId)";
-            $this->Execute( $query );
-
-        	$query = "DELETE FROM ".$this->getPrefix()."articles_categories 
-			          WHERE blog_id = $blogId";
-
-            $result = $this->Execute( $query );
-
-            return $result;
+        	if(($result = $this->delete( "blog_id", $blogId ))) {
+        		$this->_cache->removeData( "all", CACHE_ARTICLE_CATEGORIES_BLOG );
+        		/**
+        		 * :TODO:
+        		 * remove each single cached category!
+        		 */
+        	}
+        	
+        	return( $result );
         }
 
         /**
@@ -416,21 +221,13 @@
          */
         function updateCategory( $category )
         {
-        	$query = "UPDATE ".$this->getPrefix()."articles_categories
-                      SET name = '".Db::qstr($category->getName())."',
-                      url = '".Db::qstr($category->getUrl())."',
-                      in_main_page = ".$category->isInMainPage().",
-					  properties = '".Db::qstr(serialize($category->getProperties()))."',
-					  mangled_name = '".Db::qstr(TextFilter::urlize($category->getName()))."',
-					  description = '".Db::qstr($category->getDescription())."' 
-                      WHERE id = ".$category->getId().";";
-
-            $result = $this->Execute( $query );
-
-            if( !$result )
-            	return false;
-            else
-            	return true;
+        	if( $result = $this->update( $category )) {
+				$this->_cache->removeData( $category->getBlogId(), CACHE_ARTICLE_CATEGORIES_BLOG );
+        		$this->_cache->setData( $category->getId(), CACHE_ARTICLE_CATEGORIES, $category );
+        		$this->_cache->setData( $category->getMangledName(), CACHE_ARTICLE_CATEGORIES_BYNAME, $category );        	
+        	}
+        	
+        	return( $result );
         }
 		
 		
@@ -444,81 +241,30 @@
          */
         function getArticleCategories( $articleId, $blogId = -1 )
         {
-			$prefix = $this->getPrefix();
-			$query = "SELECT c.id AS id, c.name AS name, c.url AS url, c.blog_id AS blog_id, 
-				          c.last_modification AS last_modification, c.in_main_page AS in_main_page, 
-						  c.parent_id AS parent_id, c.properties AS properties, c.description AS description,
-						  c.mangled_name AS mangled_name, IF(a.id IS NULL, 0, COUNT(*)) AS num_articles, a.date AS last_update 
-						  FROM {$prefix}articles_categories c LEFT JOIN {$prefix}article_categories_link l
-						  ON c.id=l.category_id LEFT JOIN {$prefix}articles a ON a.id = l.article_id 
-						  WHERE a.id = $articleId ";
-			if( $blogId > -1 ) {
-				$query .= " AND a.blog_id = '".Db::qstr($blogId)."' AND c.blog_id = '".Db::qstr($blogId)."'";	
-			}
-						  
-			$query .= " GROUP BY c.id";
-            
-            $result = $this->Execute( $query );
+        	$categoryLinks = $this->_cache->getData( $articleId, CACHE_ARTICLE_CATEGORIES_LINK );
+        	if( !$categoryLinks ) {
+				$query = "SELECT category_id FROM ".$this->getPrefix()."article_categories_link
+				          WHERE article_id = '".Db::qstr( $articleId )."'";
+				if(( $result = $this->Execute( $query ))) {
+					$categoryLinks = Array();
+					while( $row = $result->FetchRow()) {
+						$categoryLinks[] = $row["category_id"];
+					}
+					$this->_cache->setData( $articleId, CACHE_ARTICLE_CATEGORIES_LINK, $categoryLinks );
+				}
+				else
+					return( Array());
+        	}        	
 
-            // it's impossible that an article has no categories, but
-            // we'll bear with it...
-            if( !$result )
-                return Array();
-
-            // otherwise, fetch them
-            $categories = Array();
-            while( $row = $result->FetchRow()) {
-				$category = $this->_fillCategoryInformation( $row );            	
-                array_push( $categories, $category );
-            }
-
+			foreach( $categoryLinks as $categoryLink ) {
+				$category = $this->getCategory( $categoryLink );
+				if( $category )
+					$categories[] = $category;
+			}
             return $categories;
         }
         
 		/**
-		 * returns all the article categories given an array of category ids
-		 *
-		 * @param articleIds an array of category ids
-		 * @param blogId The blog id to which these article categories belong. It is recommeded to pass this
-		 * parameter as it will greatly speed up the query.
-		 * @return an array of ArticleCategory objects
-		 */
-        function getArticleCategoriesByIds( $articleIds, $blogId = -1 )
-        {
-        	
-			$prefix = $this->getPrefix();
-			$query = "SELECT a.id as article_id, c.id AS id, c.name AS name, c.url AS url, c.blog_id AS blog_id, 
-				          c.last_modification AS last_modification, c.in_main_page AS in_main_page, 
-						  c.parent_id AS parent_id, c.properties AS properties, c.description AS description,
-						  c.mangled_name AS mangled_name, IF(a.id IS NULL, 0, COUNT(*)) AS num_articles, a.date AS last_update 
-						  FROM {$prefix}articles_categories c LEFT JOIN {$prefix}article_categories_link l
-						  ON c.id=l.category_id LEFT JOIN {$prefix}articles a ON a.id = l.article_id 
-						  WHERE a.id IN (".$articleIds.") ";
-			if( $blogId > -1 ) {
-				$query .= " AND a.blog_id = '".Db::qstr( $blogId )."' AND c.blog_id = '".Db::qstr( $blogId )."'";	
-			}			
-						    
-			$query .= " GROUP BY c.id, a.id";
-			            
-            $result = $this->Execute( $query );
-
-            // it's impossible that an article has no categories, but
-            // we'll bear with it...
-            if( !$result )
-                return Array();
-
-            // otherwise, fetch them
-            while ($row = $result->FetchRow()) {
-            	$lastArticleId=$row["article_id"];
-                $category = $this->_fillCategoryInformation( $row );            	
-                $categories[$lastArticleId][]=$category;
-			}
-
-
-            return $categories;
-        }
-		
-		/**
 		 * returns how many categories a blog has
 		 *
 		 * @param blogId
@@ -528,23 +274,7 @@
 		 */
 		function getBlogNumCategories( $blogId, $includeHidden = false, $searchTerms =  "" )
 		{
-			// table name
-			$prefix = $this->getPrefix();
-			$table = "{$prefix}articles_categories";
-
-			// conditions
-			$cond1 = "blog_id = '".Db::qstr($blogId)."'";
-			if( $includeHidden )
-    			$cond2 =  "in_main_page = 1";
-    		if( $searchTerms != "" )
-    			$cond3 = $this->buildSearchCondition( $searchTerms );    			
-			
-			$cond = " ".$this->buildWhereCondition( Array( $cond1, $cond2, $cond3 ), false );
-				
-			// return the total number
-			$total = $this->getNumItems( $table, $cond );
-
-			return( $total );
+			return(count($this->getBlogCategories( $blogId, !$includeHidden, BLOG_CATEGORIES_DEFAULT_ORDER, $searchTerms )));
 		}
     }
-?>
+?>
\ No newline at end of file

Modified: plog/trunk/class/dao/articlecategory.class.php
===================================================================
--- plog/trunk/class/dao/articlecategory.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/articlecategory.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -28,6 +28,7 @@
 	        include_once( PLOG_CLASS_PATH."class/data/timestamp.class.php" );
 
 			$this->DbObject();
+			
 			$this->_name = $name;
             $this->_url = $url;
 			$this->_id = $id;
@@ -39,7 +40,21 @@
 			$this->_description = $description;
 			$this->_lastModification = new Timestamp($lastModification);
 			$this->_articles = Array();
-			$this->_numArticles = Array();
+			$this->_numArticles = 0;
+			$this->_numPublishedArticles = 0;
+			
+			$this->_pk = "id";
+			$this->_fields = Array( "name" => "getName",
+			                        "url" => "getUrl",
+			                        "blog_id" => "getBlogId",
+			                        "parent_id" => "getParentId",
+			                        "description" => "getDescription",
+			                        "in_main_page" => "isInMainPage",
+			                        "last_modification" => "getLastModification",
+			                        "properties" => "getProperties",
+			                        "num_articles" => "getNumAllArticles",
+			                        "num_published_articles" => "getNumPublishedArticles",
+			                        "mangled_name" => "getMangledName" );
 		}
 
         /**
@@ -150,16 +165,19 @@
          */
         function getNumArticles( $status = POST_STATUS_PUBLISHED )
         {
-			$origStatus = $status;
-			if( $status == POST_STATUS_ALL ) 
-				$status = 0;
-		
-			if( !is_array( $this->_numArticles[$status] ) || $this->_numArticles[$status] == null ) {
-				$categories = new ArticleCategories();
-				$this->_numArticles[$status] = $categories->getNumArticlesCategory( $this->getId(), $origStatus );
-			}
+        	if( $status == POST_STATUS_ALL )
+        		return( $this->_numArticles );
+        	elseif( $status == POST_STATUS_PUBLISHED )
+        		return( $this->_numPublishedArticles );
+        	else {
+				$origStatus = $status;        	
+				if( !is_array( $this->_numArticles[$status] ) || $this->_numArticles[$status] == null ) {
+					$categories = new ArticleCategories();
+					$this->_numArticles[$status] = $categories->getNumArticlesCategory( $this->getId(), $origStatus );
+				}
 			
-			return( $this->_numArticles[$status] );
+				return( $this->_numArticles[$status] );			
+        	}
         }
 		
 		/**
@@ -173,6 +191,21 @@
 			return( $this->getNumArticles( POST_STATUS_ALL ));
 		}
 		
+		function getNumPublishedArticles()
+		{
+			return( $this->_numPublishedArticles );
+		}
+		
+		function setNumPublishedArticles( $num )
+		{
+			$this->_numPublishedArticles = $num;
+		}
+		
+		function setNumArticles( $num )
+		{
+			$this->_numArticles = $num;
+		}		
+		
 		/**
 		 * returns the articles categorized here
 		 *
@@ -264,7 +297,12 @@
         function setLastModification( $newDate )
         {
             $this->_lastModification = $newDate;
-        }
+        }      
         
+        function getMangledName()
+        {
+        	include_once( PLOG_CLASS_PATH."class/data/textfilter.class.php" );
+        	return( Textfilter::urlize( $this->getName()));
+        }        
 	}
-?>
+?>
\ No newline at end of file

Modified: plog/trunk/class/dao/articlecomments.class.php
===================================================================
--- plog/trunk/class/dao/articlecomments.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/articlecomments.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -32,16 +32,6 @@
 			return( CommentsCommon::getPostComments( $artid, $order, $status, COMMENT_TYPE_COMMENT, $page, $itemsPerPage ));
 		}
 		
-		/**
-		 * Retrieves all the comments for subquery of posts
-		 *
-		 * @private
-		 */
-		function getPostCommentsByIds( $ids, $order = COMMENT_ORDER_NEWEST_FIRST, $status = COMMENT_STATUS_ALL )
-		{
-			return( CommentsCommon::getPostCommentsByIds( $ids, $order, $status, COMMENT_TYPE_COMMENT ));
-		}
-		
         /**
          * Returns the total number of comments for a post
 		 *
@@ -56,14 +46,6 @@
         }
 
         /**
-         * Retrieves only one post from a given article
-         */
-        function getPostComment( $artid, $commentid )
-		{
-			return( CommentsCommon::getPostComment( $artid, $commentid, COMMENT_TYPE_COMMENT ));			
-		}
-
-        /**
          * Returns true if there already is a comment in the database with the same
          * article_id field, topic, text, replying to the same comment, username and so on
          * Useful in case we want to check if the user sent the same comment by mistake
@@ -78,43 +60,7 @@
 														 $userUrl, $clientIp, COMMENT_TYPE_COMMENT ));
         }
 
-		/**
-		 * Removes a comment from a post. It also updates all the other posts that
-         * have this one as the parent and makes them look as if they were 'top level'
-         * comments with no parent.
-         *
-         * @param artid The article identifier.
-         * @param commentid The comment identifier.
-		 */
-		function deletePostComment( $artid, $commentid )
-		{
-			return( CommentsCommon::deletePostComment( $artid, $commentid, COMMENT_TYPE_COMMENT ));
-		}
-		
-		/**
-		 * Removes a comment from a post. It also updates all the other posts that
-         * have this one as the parent and makes them look as if they were 'top level'
-         * comments with no parent.
-         *
-         * @param commentid The comment identifier.
-         * @param articleId The article identifier.		 
-		 */
-		function deleteComment( $commentid, $articleId = -1 )
-		{
-			return( $this->deletePostComment( $articleId, $commentid ));
-		}		
-
         /**
-         * Removes all the comments from a post.
-         *
-         * @param artId The article identifier
-         */
-        function deletePostComments( $artId )
-        {
-			return( CommentsCommon::deletePostComments( $artId, COMMENT_TYPE_COMMENT ));
-        }
-
-        /**
          * updates the status of a comment, regarding its spam status...
          *
          * @param commentId

Modified: plog/trunk/class/dao/articlenotifications.class.php
===================================================================
--- plog/trunk/class/dao/articlenotifications.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/articlenotifications.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -183,6 +183,8 @@
 
             return $result;
          }
+         
+
         /**
          * Sends a weblogsUpdate.ping xmlrpc call to notifiy of changes in this blog
          *
          * @param blogInfo The BlogInfo object containing information about the blog
          * @return Returns true if successful or false otherwise.
          */
         function updateNotify( $blogInfo )
         {
            // source classes
            include_once( PLOG_CLASS_PATH."class/net/xmlrpcclient.class.php" );
            require_once( PLOG_CLASS_PATH . 'class/config/config.class.php' );            

            // if this feature is not enabled, we quit
            $config =& Config::getConfig();
            if( !$config->getValue( "xmlrpc_ping_enabled" ))
                return;

            // get the array which contains the hosts
            $hosts = $config->getValue( "xmlrpc_ping_hosts" );

            // if it is not an array, quit
            if( !is_array($hosts))
                return;

            // if no hosts, we can quit too
            if( empty($hosts))
                return;

            // otherwise, we continue
            $xmlrpcPingResult = Array();
            $rg = $blogInfo->getBlogRequestGenerator();
            $blogLink = $rg->blogLink();
            foreach( $hosts as $host ) {
                $client = new XmlRpcClient( $host );
                $result = $client->ping( $blogInfo->getBlog(), $blogLink);
                //print("result = ".$result. "is Error = ".$client->isError()." message: ".$client->getErrorMessage()."<br/>");
                //$xmlrpcPingResult[$result["host"]
                $xmlrpcPingResult=array_merge($xmlrpcPingResult, $result);
            }

            return $xmlrpcPingResult;
         }         
 
          /**
           * Returns the notifications but only for a particular user, a particular blog and

Modified: plog/trunk/class/dao/articles.class.php
===================================================================
--- plog/trunk/class/dao/articles.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/articles.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -4,6 +4,16 @@
     include_once( PLOG_CLASS_PATH.'class/dao/article.class.php' );
     include_once( PLOG_CLASS_PATH.'class/dao/articlestatus.class.php' );
     include_once( PLOG_CLASS_PATH.'class/config/config.class.php' );
+
+	/**
+	 * cache ids used by this class
+	 */
+    define( "CACHE_ARTICLES",            "articles" );
+    define( "CACHE_ARTICLES_BYNAME",     "articles_byname" );    
+    define( "CACHE_ARTICLETEXT",         "article_text" );    
+    define( "CACHE_ARTICLES_BYBLOG",     "articles_byblog" );
+    define( "CACHE_ARTICLESPERMONTH",    "articles_per_month" );
+    
     /**
 	 * \ingroup DAO
 	 *
@@ -11,24 +21,12 @@
      */
     class Articles extends Model
     {
-        // DAO objects that we keep for later, so that we don't have
-        // to create them eeeeevery time!
-        var $categories    = null;
-        var $comments      = null;
-        var $trackbacks    = null;
-        var $users         = null;
-        var $blogs         = null;
-		var $customfields  = null;
-		var $_blogInfo     = null;
-		var $_blogSettings = null;
-		var $_timeDiff     = null;
-
         function Articles()
         {
             $this->Model();
-			$this->_blogInfo     = null;
-			$this->_timeDiff     = 0;
-			$this->_blogsettings = null;
+			
+			$this->table = $this->getPrefix()."articles";
+			$this->pk = "id";
         }
 
         /**
@@ -40,29 +38,7 @@
          */
         function getArticle( $articleId )
         {
-            $article = $this->_cache->getData( $articleId, CACHE_ARTICLES );
-
-            if ( !$article ) {
-                include_once( PLOG_CLASS_PATH."class/database/db.class.php" );
-
-                $query = Db::buildSelectQuery( ARTICLES_TABLENAME,
-                                               array(),
-                                               'id',
-                                               $articleId );
-
-                // we send the query and then fetch the first array with the result
-                $result = $this->Execute( $query );
-
-                if ( $result->RecordCount() == 0 )
-                    return false;
-
-                $article = $this->_fillArticleInformation( $result->FetchRow( $result ) );
-
-                $article->getFields();
-
-                $this->_cache->setData( $article->getId(), CACHE_ARTICLES, $article );
-            }
-            return $article;
+        	return( $this->get( "id", $articleId, CACHE_ARTICLES ));
         }
 
         /**
@@ -73,38 +49,11 @@
          */
         function getArticles( $blogId )
         {
-            require_once( PLOG_CLASS_PATH . 'class/dao/blogarticles.class.php' );
-
-            $blogArticles = $this->_cache->getData( $blogId, CACHE_BLOGARTICLES );
-
-            if( !$blogArticles ) {
-                require_once( PLOG_CLASS_PATH . 'class/database/db.class.php' );
-
-                $prefix = $this->getPrefix();
-
-                // as much as i would like to, i don't know how to use a less complicated
-                // sql statement or how to use an abstract method to build an statement
-                // like this one.
-                $query = "SELECT a.id as id, c.category_id as category_id, a.date as date, 
-                                 a.status as status, a.user_id as user_id
-                          FROM {$prefix}article_categories_link c LEFT JOIN {$prefix}articles a 
-                               ON a.id = c.article_id
-                          WHERE a.blog_id = $blogId
-                          ORDER BY a.date DESC";
-
-                $result = $this->Execute( $query );
-
-                $rows = array();
-                while( $row = $result->FetchRow($result) ) {
-                    $rows[] = $row;
-                }
-
-                $blogArticles = new BlogArticles( $blogId, $rows );
-
-                $this->_cache->setData( $blogId, CACHE_BLOGARTICLES, $blogArticles );
-            }
-
-            return $blogArticles;
+        	$blogArticles = $this->getMany( "blog_id",
+        	                                $blogId,
+        	                                CACHE_ARTICLES_BYBLOG,
+        	                                Array( CACHE_ARTICLES => "getId" ));
+			return( $blogArticles );
         }
 
         /**
@@ -117,19 +66,13 @@
          */
         function getUserArticle( $artId, $userId = -1 )
         {
-            $article =  $this->getArticle( $artId );
-            if( !$article )
-                return false;
-
-            if ( $userId != -1 ) {
-                $article      = $this->getArticle( $artId );
-                $articleOwner = $article->getUser();
-
-                if( $articleOwner->getId() != $userId ) {
-                    return false;
-                }
-            }
-            return $article;
+        	$article = $this->getArticle( $artId );
+        	if( !$article )
+        		return false;
+        	if( $userId > -1 && $article->getOwnerId() != $userId )
+        		return false;
+        		
+        	return( $article );
         }
 
         /**
@@ -139,7 +82,14 @@
          * @param blogId If set, the article must belong to the given blog
          * @return Returns an Article object or 'false' otherwise.
          */
-        function getBlogArticle( $artId, $blogId = -1 )
+        function getBlogArticle( $artId, 
+                                 $blogId = -1,
+                                 $includeHiddenFields = true, 
+                                 $date = -1, 
+                                 $categoryId = -1, 
+                                 $userId = -1, 
+                                 $status = POST_STATUS_PUBLISHED )
+                                 
         {
             $article = $this->getArticle( $artId );
 
@@ -147,12 +97,18 @@
                 return false;
 
             if( $blogId != -1 ) {
-                $article     = $this->getArticle( $artId );
-
                 if( $article->getBlogId() != $blogId ) {
                     return false;
                 }
             }
+            if( $userId != -1 ) {
+            	if( $article->getUserId() != $userId ) {
+            		return false;
+            	}
+            }
+            if( $article->getStatus() != $status )
+            	return false;
+            	
             return $article;
         }
         
@@ -259,7 +215,7 @@
 
             $row = $result->FetchRow( $result );
 
-            $article = $this->_fillArticleInformation( $row, $includeHiddenFields );
+            $article = $this->mapRow( $row, $includeHiddenFields );
 
             return $article;        
         }
@@ -293,7 +249,9 @@
                                            'date',
                                            1 );
 
-			return( $this->_getBlogArticleFromQuery( $query, false ));
+			$article = $this->_getBlogArticleFromQuery( $query, false );
+			
+			return( $article );
         }
 
         /**
@@ -327,7 +285,9 @@
                                            'date',
                                            1 );
 									 
-			return( $this->_getBlogArticleFromQuery( $query, false ));
+			$article = $this->_getBlogArticleFromQuery( $query, false );
+			
+			return( $article );
 		}
 		
 		/**
@@ -362,6 +322,50 @@
 
             return count($articles);
 		}
+		
+		/**
+		 * @private
+		 * returns true whether the given article matches the given conditions, or false otherwise
+		 */
+		function check( $article, 
+		                $date = -1, 
+		                $categoryId = 0, 
+		                $status = POST_STATUS_PUBLISHED, 
+		                $userId = 0, 
+		                $maxDate = 0, 
+		                $searchTerms = "" )
+		{
+			if( $status != POST_STATUS_ALL ) {
+				if( $article->getStatus() != $status )
+					return false;
+			}
+			if( $categoryId > 0 ) {
+				$found = false;
+				foreach( $article->getCategoryIds() as $catId ) {
+					if( $categoryId == $catId ) {
+						$found = true;
+					}
+				}
+				if( !$found )
+					return false;
+			}
+			if( $userId > 0 ) {
+				if( $article->getUserId() != $userId )
+					return false;
+			}
+			if( $date > -1 ) {
+				$postDate = substr($article->getDate(),0,strlen($date));
+				if( $postDate != $date )
+					return false;
+			}
+			if( $maxDate > 0 ) {			
+				$postDate = substr($article->getDate(),0,strlen($maxDate));
+				if( $postDate > $maxDate )
+					return false;				
+			}
+			
+			return( true );
+		}
 
         /**
          * Returns all the articles for a given blog, according to the conditions specified in 
@@ -392,39 +396,22 @@
                                   $searchTerms = "", 
                                   $page        = -1 )
         {
-            $blogArticles      = $this->getArticles( $blogId );
-            $requestedArticles = $blogArticles->getArticleIdsByStatus( $status );
-
-            if( $categoryId > 0 ) 
-                $requestedArticles = $blogArticles->getArticleIdsByCategory( $categoryId, 
-                                                                             $requestedArticles );
-            if( $userId > 0 )
-                $requestedArticles = $blogArticles->getArticleIdsByUserId( $userId,
-                                                                           $requestedArticles );
-            if( $date != -1 )
-                $requestedArticles = $blogArticles->getArticleIdsByDate( $date, 
-                                                                         $requestedArticles );
-
-            if( $maxDate != 0 )
-                $requestedArticles = $blogArticles->getArticleIdsBefore( $maxDate, 
-                                                                         $requestedArticles );
-
-            if( $searchTerms != '' )
-                $requestedArticles = $this->searchArticles( $searchTerms, $requestedArticles );
-
-            if( ($amount > 0) && ($date == -1) && ($page == -1 ) )
-                $requestedArticles = array_slice( $requestedArticles, 0, $amount );
-
-            if( $page > 0 ) {
-				$start = (($page - 1) * $amount);
-                $requestedArticles = array_slice( $requestedArticles, $start, $amount );
-            }
-
-            $articles = array();
-            foreach( $requestedArticles as $article ) {
-                $articles[] = $this->getArticle( $article );
-            }
-            return $articles;
+        	$articles = $this->getArticles( $blogId );        	
+        	
+        	$result = Array();
+        	$total = 0;
+        	foreach( $articles as $article ) {
+        		if( $this->check( $article, $date, $categoryId, $status, $userId, $maxDate, $searchTerms )) {
+        			$result[] = $article;
+        			$total++;
+        		}
+        		if( $amount != -1 ) {
+	        		if( $total >= $amount )
+    	    			break;
+    	    	}
+        	}
+        	
+        	return( $result );
         }
 		
         /**
@@ -439,27 +426,30 @@
         {
 
             $archives = $this->_cache->getData( $blogId, CACHE_ARTICLESPERMONTH );
+            $arcnives = false;
 
             if( !$archives ) {
                 require_once( PLOG_CLASS_PATH . 'class/dao/blogs.class.php' );
                 $blogs = new Blogs();
-                $blogSettings = $blogs->getBlogSettings( $blogId );
+                $blogInfo = $blogs->getBlogInfo( $blogId );
+                $blogSettings = $blogInfo->getSettings();
 
+				$prefix = $this->getPrefix();
                 if( $blogSettings->getValue("show_future_posts_in_calendar") )
                     $numPostsPerMonthQuery = "SELECT COUNT(*) AS 'count',
-                                                YEAR(date) AS 'year',
-                                                MONTH(date) AS 'month'
-                                              FROM ".$this->getPrefix().ARTICLES_TABLENAME." 
-                                              WHERE status = 1 AND blog_id = ".$blogId." 
+                                              YEAR(date) AS 'year',
+                                              MONTH(date) AS 'month'
+                                              FROM {$prefix}articles 
+                                              WHERE status = 1 AND blog_id = $blogId
                                               GROUP BY YEAR(date),MONTH(date) 
                                               ORDER BY YEAR(date) DESC,MONTH(date) DESC;";
                 else
                     $numPostsPerMonthQuery = "SELECT COUNT(*) AS 'count',
                                                 YEAR(date) AS 'year',
                                                 MONTH(date) AS 'month'
-                                              FROM ".$this->getPrefix().ARTICLES_TABLENAME." 
-                                              WHERE status = 1 AND blog_id = ".$blogId." 
-                                                AND date <= NOW() 
+                                              FROM {$prefix}articles
+                                              WHERE status = 1 AND blog_id = $blogId 
+                                              AND date <= NOW() 
                                               GROUP BY YEAR(date),MONTH(date) 
                                               ORDER BY YEAR(date) DESC,MONTH(date) DESC;";
 
@@ -484,22 +474,21 @@
          */
         function getNumberPostsPerMonthAdmin( $blogId )
         {
-        	// query to get the earliest post
-            // this must be my longest and most complex SQL query ever :)
-			$numPostsPerMonthQuery = "SELECT COUNT(*) AS 'count', YEAR(date) AS 'year',
-			                          MONTH(date) AS 'month', DAYOFMONTH(date) AS 'daymonth' 
-			                          FROM ".$this->getPrefix()."articles 
-			                          WHERE blog_id = $blogId 
-			                          GROUP BY YEAR(date), MONTH(date) 
+        	$prefix = $this->getPrefix();
+			$numPostsPerMonthQuery = "SELECT date 
+			                          FROM {$prefix}articles 
+			                          WHERE blog_id = '".Db::qstr($blogId)."'
 			                          ORDER BY YEAR(date) DESC,MONTH(date) DESC;";
 
             $result = $this->Execute( $numPostsPerMonthQuery);
-            if( $result == false )
-            	return false;
+            if( !$result )
+            	return Array();
             	
             while( $row = $result->FetchRow()) {
-            	$archives[$row["year"]][$row["month"]] = $row["count"];
-            }
+            	$year = substr($row["date"],0,4);
+            	$month = substr($row["date"],4,2);
+            	$archives[$year][$month] = 1;
+            }            
 
             return $archives;
         }
@@ -508,43 +497,48 @@
          * The same as the one above but for just one month
          *
          * @param blogId The identifier of the blog from which we'd like to calculate this
-         * @param year Year
+         * @param year Yeardddd
          * @param month Month from which we'd like to calculate this
          * @return An associative array where the index is the day of the month and the value
          * is the number of posts made that day.
          */
-        function getNumberPostsPerDay( $blogId, $year = null , $month = null )
+        function getDaysWithPosts( $blogId, $year = null , $month = null )
         {
             include_once( PLOG_CLASS_PATH.'class/data/timestamp.class.php' );
+            $t = new Timestamp();            
             // if month and/or year are empty, get the current ones
-            if( $year == null ) {
-                $t = new Timestamp();
+            if( $year == null ) 
                 $year = $t->getYear();
-            }
-            if( $month == null ) {
-                $t = new Timestamp();
+            if( $month == null )
                 $month = $t->getMonth();
-            }
+                
+            // build a valid timestamp for the query
+            $dateTimestamp = $year.$month."00000000";
 
-            // another long sql query :) the id and date fields are there just in case we need to debug
-            // but they're not included in the resulting array
             $blogs = new Blogs();
-            $blogSettings = $blogs->getBlogSettings( $blogId );
+            $blogInfo = $blogs->getBlogInfo( $blogId );
+            $blogSettings = $blogInfo->getSettings();
+
             // check whether we're supposed to show posts that happen in the future or not
-            if( $blogSettings->getValue( "show_future_posts_in_calendar" ))
-                $numPostsPerDayQuery = "SELECT COUNT(*) AS 'count', DAYOFMONTH(date) AS 'day', id AS 'id', date AS 'date' FROM ".$this->getPrefix()."articles WHERE status = 1 AND blog_id = ".$blogId." AND MONTH(date) = ".$month." AND YEAR(date) = ".$year." GROUP BY DAYOFMONTH(date);";
-            else
-                $numPostsPerDayQuery = "SELECT COUNT(*) AS 'count', DAYOFMONTH(date) AS 'day', id AS 'id', date AS 'date' FROM ".$this->getPrefix()."articles WHERE status = 1 AND blog_id = ".$blogId." AND date <= NOW() AND MONTH(date) = ".$month." AND YEAR(date) = ".$year." GROUP BY DAYOFMONTH(date);";
+            $prefix = $this->getPrefix();
+            $numPostsPerDayQuery = "SELECT date 
+                                    FROM {$prefix}articles 
+                                    WHERE status = 1 
+                                    AND blog_id = $blogId
+                                    AND date >= $dateTimestamp";           
+            if( !$blogSettings->getValue( "show_future_posts_in_calendar" ))
+            	$numPostsPerDayQuery .= " AND date <= NOW()";
 
             $result = $this->Execute( $numPostsPerDayQuery );
 
-            if( $result == false )
-                return 0;
+            if( !$result )
+                return Array();
 
             $postPerDay = Array();
             while( $row = $result->FetchRow()) {
-                $postsPerDay[$row["day"]] = $row["count"];
-            }
+            	$day = substr($row['date'],6,2);
+            	$postsPerDay[$day] = 1;
+            }           
 
             return $postsPerDay;
         }
@@ -557,14 +551,19 @@
 		 * @param categories
 		 * @return True
          */
-        function addPostCategoriesLink( $articleId, $categories )
-        {
+        function addPostCategoriesLink( $article )
+        {        	
             require_once( PLOG_CLASS_PATH.'class/database/db.class.php' );
+            require_once( PLOG_CLASS_PATH."class/dao/articlecategories.class.php" );
+            
+            $articleId = $article->getId();
+            $categories = $article->getCategoryIds();
 
 			// nothing to do if the $categories array is not ehem, an array :)
 			if( !is_array( $categories ))
 				return true;
 				
+			$articleCategories = new ArticleCategories();
             foreach( $categories as $categoryId ) {
                 $keyValuePairs = array();
                 $keyValuePairs['article_id']  = $articleId;
@@ -573,6 +572,13 @@
                 $query = Db::buildInsertQuery( ARTICLE_CATEGORIES_RELATIONSHIP_TABLENAME,
                                                $keyValuePairs );
                 $this->Execute( $query );
+                
+               	$category = $articleCategories->getCategory( $categoryId );                
+                if( $article->getStatus() == POST_STATUS_PUBLISHED ) {
+                	$category->setNumPublishedArticles( $category->getNumPublishedArticles() +1 );
+                }
+				$category->setNumArticles( $category->getNumAllArticles() + 1 );
+				$articleCategories->updateCategory( $category );
             }
 
             return true;
@@ -582,15 +588,29 @@
          * removes the relationship between posts and categories from the database. This
          * method should only be used when removing an article!!
          */
-        function deletePostCategoriesLink( $articleId )
+        function deletePostCategoriesLink( $article )
         {
             require_once( PLOG_CLASS_PATH.'class/database/db.class.php' );
+            require_once( PLOG_CLASS_PATH."class/dao/articlecategories.class.php" );
 
+			$articleId = $article->getId();
             $query = Db::buildDeleteQuery( ARTICLE_CATEGORIES_RELATIONSHIP_TABLENAME,
                                            'article_id',
                                            $articleId );
 
-            return $this->Execute( $query );
+            if( ( $result = $this->Execute( $query ))) {
+            	// updated the category counters
+            	$articleCategories = new ArticleCategories();
+            	foreach( $article->getCategories() as $category ) {
+					$category->setNumArticles( $category->getNumArticles() - 1 );
+					if( $article->getStatus() == POST_STATUS_PUBLISHED ) {
+						$category->setNumPublishedArticles( $category->getNumPublishedArticles() - 1 );
+					}
+					$articleCategories->updateCategory( $category );
+            	}
+            }
+            
+            return( $result );
         }
 
         /**
@@ -598,12 +618,12 @@
          * (basically, we use brute force here: first remove them and then recreate them again...
          * It takes less time than going through all of them and checking if they exist or not.
          */
-        function updatePostCategoriesLink( $articleId, $categories )
+        function updatePostCategoriesLink( $article )
         {
-            if( !$this->deletePostCategoriesLink( $articleId ))
+            if( !$this->deletePostCategoriesLink( $article ))
                 return false;
 
-            return $this->addPostCategoriesLink( $articleId, $categories );
+            return $this->addPostCategoriesLink( $article );
         }
 
         /**
@@ -616,44 +636,40 @@
         function addArticle( &$newArticle )
         {
             include_once( PLOG_CLASS_PATH.'class/dao/customfields/customfields.class.php' );
-            require_once( PLOG_CLASS_PATH.'class/database/db.class.php' );
+            include_once( PLOG_CLASS_PATH."class/dao/blogs.class.php" );
+            
+            $result = $this->add( $newArticle );
+            
+            if( !$result )
+            	return false;
 
-            $valuesToInsert = array();
-
-            $valuesToInsert['user_id']    = $newArticle->getUser();
-            $valuesToInsert['blog_id']    = $newArticle->getBlogId();
-            $valuesToInsert['status']     = $newArticle->getStatus();
-            $valuesToInsert['date']       = $newArticle->getDate();
-            $valuesToInsert['properties'] = serialize( $newArticle->getProperties() );
-            $valuesToInsert['slug']       = $newArticle->getPostSlug();
-
-            $query = Db::buildInsertQuery( ARTICLES_TABLENAME,
-                                           $valuesToInsert );
-
-            $result = $this->Execute( $query );
-
-            if( !$result ){
-                return false;
-            }
-
-            // get id of the post from the database
-            $postId = $this->_db->Insert_ID();
-			
-			// save the post text
-			$newArticle->setId( $postId );
 			$this->addArticleText( $newArticle );
 
-            // and create the link between the post and its categoriesç
-            $this->addPostCategoriesLink( $postId, $newArticle->getCategoryIds());
+            // and create the link between the post and its categories
+            $this->addPostCategoriesLink( $newArticle );
 
             // and save the custom fields
-            $this->addArticleCustomFields( $postId, $newArticle->getBlog(), $newArticle->getFields());
+            $customFields = new CustomFieldsValues();
+            foreach( $fields as $field ) {
+                $customFields->addCustomFieldValue( $field->getFieldId(), 
+                                                    $field->getValue(), 
+                                                    $artId, 
+                                                    $blogId );
+            }
+            
+            // update the blog counters
+            if( $newArticle->getStatus() == POST_STATUS_PUBLISHED ) {
+	            $blogs = new Blogs();
+    	        $blogInfo = $newArticle->getBlogInfo();
+        	    $blogInfo->setTotalPosts( $blogInfo->getTotalPosts() + 1 );
+            	$blogs->updateBlog( $blogInfo );
+            }
 
             // and finally clear the cache :)
-            $this->_cache->removeData( $newArticle->getBlogId(), CACHE_BLOGARTICLES );
+            $this->_cache->removeData( $newArticle->getBlogId(), CACHE_ARTICLES_BYBLOG );
             $this->_cache->removeData( $newArticle->getBlogId(), CACHE_ARTICLESPERMONTH );
 
-            return $postId;
+            return( $newArticle->getId());
         }
 		
 		/**
@@ -738,28 +754,8 @@
 
 			return($this->Execute( $query ));
 		}
-
+		
         /**
-         * Saves the custom fields of an article
-         *
-         * @param artId
-         * @param blogId
-         * @param fields
-         * @return True if successful or false otherwise
-         */
-        function addArticleCustomFields( $artId, $blogId, $fields )
-        {
-            $customFields = new CustomFieldsValues();
-
-            foreach( $fields as $field ) {
-                $customFields->addCustomFieldValue( $field->getFieldId(), $field->getValue(), 
-                                                    $artId, $blogId );
-            }
-
-            return true;
-        }
-
-        /**
          * Updates an article in the database
          *
          * @param article The Article object that we'd like to update in the database.
@@ -767,29 +763,8 @@
          */
         function updateArticle( $article )
         {
-            include_once( PLOG_CLASS_PATH.'class/data/timestamp.class.php' );
-            include_once( PLOG_CLASS_PATH.'class/database/db.class.php' );
+        	$result = $this->update( $article );
 
-            // we have to build up the query, which will be pretty long...
-            $articleDate = Timestamp::getDateWithOffset( $article->getDate(), -($article->getTimeOffset()));
-            $filter = new Textfilter();
-
-            $keyValuePairs = array();
-            $keyValuePairs['user_id']    = $article->getUser();
-            $keyValuePairs['date']       = $articleDate;
-            $keyValuePairs['blog_id']    = $article->getBlogId();
-            $keyValuePairs['status']     = $article->getStatus();
-            $keyValuePairs['num_reads']  = $article->getNumReads();
-            $keyValuePairs['properties'] = serialize( $article->getProperties() );
-            $keyValuePairs['slug']       = $article->getPostSlug();
-            
-            $query = Db::buildUpdateQuery( ARTICLES_TABLENAME,
-                                           $keyValuePairs,
-                                           'id',
-                                           $article->getId() );
-
-            $result = $this->Execute( $query );
-
             // we don't bother doing anything else if the query above failed...
             if( !$result )
                 return false;
@@ -797,7 +772,7 @@
 			// update the article text
 			$this->updateArticleText( $article );
 
-            if( !$this->updatePostCategoriesLink( $article->getId(), $article->getCategoryIds()) ||
+            if( !$this->updatePostCategoriesLink( $article ) ||
                 !$this->updateArticleCustomFields( $article->getId(), $article->getBlog(), 
                                                    $article->getFields()) )
                 return false;
@@ -805,6 +780,7 @@
             // clean up the cache
             $this->_cache->removeData( $article->getBlogId(), CACHE_ARTICLESPERMONTH );
             $this->_cache->removeData( $article->getId(), CACHE_ARTICLES );
+            $this->_cache->removeData( $article->getBlogId(), CACHE_ARTICLES_BYBLOG );
 
             return true;
         }
@@ -915,48 +891,51 @@
             include_once( PLOG_CLASS_PATH.'class/dao/articlecomments.class.php' );
             include_once( PLOG_CLASS_PATH.'class/database/db.class.php' );
             include_once( PLOG_CLASS_PATH.'class/dao/trackbacks.class.php' );            
-            include_once( PLOG_CLASS_PATH.'class/dao/customfields/customfieldsvalues.class.php' );            
+            include_once( PLOG_CLASS_PATH.'class/dao/customfields/customfieldsvalues.class.php' );
+            
+            $article = $this->getBlogArticle( $artId, $blogId, true, -1, -1, $userId );
+            if( !$article )
+            	return false;
 
             if( $forever ) {
-                $query = "DELETE FROM ".$this->getPrefix()."articles WHERE id = ".$artId." AND user_id = ".$userId." AND blog_id = ".$blogId.";";
+            	if( !$this->delete( $artId ))
+            		return false;
+            		
 				// -- text --
 				$this->deleteArticleText( $artId );
                 // we also have to remove its comments and trackbacks if the article is being deleted forever
                 // -- comments --
-                $comments = new ArticleComments();
-                $comments->deletePostComments( $artId );
+                $articleComments = new ArticleComments();
+                foreach( $article->getComments() as $comment )
+                	$comments->deletePostComment( $artId, $comment->getId());
+                	
                 // -- trackbacks --
-                $trackbacks = new Trackbacks();
-                $trackbacks->deletePostTrackbacks( $artId );
+                foreach( $article->getTrackbacks() as $trackback )
+                	$comments->deleteTrackback( $artId, $trackback->getId());
+
                 // -- post-to-categories mappings --
-                $this->deletePostCategoriesLink( $artId );
+                $this->deletePostCategoriesLink( $article );
                 // -- custom fields --
                 $customFields = new CustomFieldsValues();
                 $customFields->removeArticleCustomFields( $artId );
+                
+	            $this->_cache->removeData( $blogId, CACHE_ARTICLES_BYBLOG );
+    	        $this->_cache->removeData( $blogId, CACHE_ARTICLESPERMONTH );
+        	    $this->_cache->removeData( $artId, CACHE_ARTICLES );                
             }
             else {
-                $keyValuePairs = array();
-                $keyValuePairs['date']   = '@date';
-                $keyValuePairs['status'] = POST_STATUS_DELETED;
-
-                $query = Db::buildUpdateQuery( ARTICLES_TABLENAME,
-                                               $keyValuePairs,
-                                               'id',
-                                               $artId );
+            	$article->setStatus( POST_STATUS_DELETED );
+            	$this->updateArticle( $article );
             }
 
-            $result = $this->Execute( $query );
-
-            if( !$result )
-                return false;
-
-            if( $this->_db->Affected_Rows() == 0 )
-                return false;
-
-            $this->_cache->removeData( $blogId, CACHE_BLOGARTICLES );
-            $this->_cache->removeData( $blogId, CACHE_ARTICLESPERMONTH );
-            $this->_cache->removeData( $artId, CACHE_ARTICLES );
-
+			// update the blog counters
+			if( $article->getStatus() == POST_STATUS_PUBLISHED ) {            
+	            $blogs = new Blogs();
+    	        $blogInfo = $article->getBlogInfo();
+        	    $blogInfo->setTotalArticles( $blogInfo->getTotalArticles() - 1 );
+            	$blogs->updateBlog( $blogInfo );
+            }
+            
             return true;
         }
 		
@@ -978,56 +957,6 @@
 		}
 
         /**
-         * returns true if the user posted this article/post, or false
-         * if he or she doesn't own it
-         *
-         * @param userInfo A UserInfo object with information about the user
-         * @param artId A valid article identifier
-         * @return Returns true if the article is owned by the user or false otherwise.
-         */
-        function doesUserOwnArticle( $userinfo, $artid )
-        {
-            $article = $this->getArticle( $artid );
-            $articleOwnerInfo = $article->getUserInfo();
-
-            if( $articleOwnerInfo->getId() == $userinfo->getId())
-                return true;
-            else
-                return false;
-        }
-
-        /**
-         * Returns all the posts in the database or the 'maxPosts' recent ones that have been
-         * published (status=='published')
-         *
-         * @param maxPosts The amount of post we want.
-         * @return Returns an array of Article objects containing the information about the posts.
-         */
-        function getAllArticles( $maxPosts = 0, $date = 0)
-        {
-            $query = "SELECT * FROM ".$this->getPrefix()."articles WHERE status = 1";
-            if( $date > 0 )
-                $query .= " AND date < '$date'";
-
-            $query .= " ORDER BY date DESC";
-
-            if( $maxPosts > 0 )
-                $query .= " LIMIT 0,".$maxPosts;
-
-            $result = $this->Execute( $query );
-
-            if( !$result )
-                return false;
-
-            $posts = Array();
-            while( $row = $result->FetchRow()) {
-				$posts[] = $this->_fillArticleInformation( $row );
-            }
-
-            return $posts;
-        }
-
-        /**
          * Removes all the posts from the given blog
          *
          * @param blogId The blog identifier
@@ -1070,42 +999,9 @@
             return true;
         }
 
-        /**
-         * returns all the categories that an article has been assigned to
-         */
-        function getArticleCategories( $articleId, $blogId = -1 )
+        function mapRow( $query_result )
         {
-            include_once( PLOG_CLASS_PATH.'class/dao/articlecategories.class.php' );
-
-            if( $this->categories === null )
-                $this->categories = new ArticleCategories();
-
-			return $this->categories->getArticleCategories( $articleId, $blogId );
-        }
-
-        /**
-         * sets a time difference that will be added to each
-         * date and time
-         *
-         * @param timeDiff The time difference. IT should be between +12 and -12
-         * @return Always returns true.
-         */
-        function setTimeDiff( $timeDiff )
-        {
-            $this->_timeDiff = $timeDiff;
-
-            return true;
-        }
-
-        /**
-         * Does exactly the same as _fillUserInformation, so that it can be reused
-         * by the different functions that work on articles from the database. This method is
-         * private and shouldn't be used outside this class.
-         *
-         * @private
-         */
-        function _fillArticleInformation( $query_result, $includeHiddenFields = true )
-        {
+        	include_once( PLOG_CLASS_PATH."class/dao/articlecategories.class.php" );
             include_once( PLOG_CLASS_PATH.'class/data/timestamp.class.php' );
             include_once( PLOG_CLASS_PATH.'class/dao/users.class.php' );
             include_once( PLOG_CLASS_PATH.'class/dao/blogs.class.php' );
@@ -1120,23 +1016,17 @@
                 $query_result['properties'] = serialize($tmpArray);
             }
 
-            //
-            // if there's a time difference applied to all dates, then we'd better
-            // calculate it here!!
-            //
-            if( $this->blogs === null )
-                $this->blogs  = new Blogs();
-
+			$blogs         = new Blogs();
             $blogId        = $query_result['blog_id'];
-            $blogInfo      = $this->blogs->getBlogInfo( $blogId );
+            $blogInfo      = $blogs->getBlogInfo( $blogId );
 			$blogSettings  = $blogInfo->getSettings();
             $timeDiff      = $blogSettings->getValue( 'time_offset' );
 
             // we can use this auxiliary function to help us...
             $date = Timestamp::getDateWithOffset( $query_result['date'], $timeDiff );
 
-			$articleCategories = $this->getArticleCategories( $query_result['id'], 
-                                                              $query_result['blog_id'] );
+            $categories = new ArticleCategories();
+			$articleCategories = $categories->getArticleCategories( $query_result['id'], $query_result['blog_id'] );
             $categoryIds = Array();
 			foreach( $articleCategories as $category )
 				array_push( $categoryIds, $category->getId());
@@ -1158,14 +1048,21 @@
             // and fill in all the fields with the information we just got from the db
             $article->setDate( $date );
             $article->setTimeOffset( $timeDiff );
+			$article->setCategories( $articleCategories );            
             // get information about the categories of the article
-            $article->setCategories( $articleCategories );
 			$article->setBlogInfo( $blogInfo );
             if ( $this->users === null )
                 $this->users = new Users();
-			$article->setUserInfo( $this->users->getUserInfoFromId( $query_result['user_id'] ));			
+			$article->setUserInfo( $this->users->getUserInfoFromId( $query_result['user_id'] ));
+			
+			// counters
+			$article->setTotalComments( $query_result['num_comments'] );
+			$article->setNumComments( $query_result['num_nonspam_comments'] );
+			$article->setNumTrackbacks( $query_result['num_nonspam_trackbacks'] );
+			$article->setTotalTrackbacks( $query_result['num_trackbacks'] );
 
             return $article;
+
         }
     }
-?>
+?>
\ No newline at end of file

Modified: plog/trunk/class/dao/blogarticles.class.php
===================================================================
--- plog/trunk/class/dao/blogarticles.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/blogarticles.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -31,28 +31,28 @@
          * @param blogId The blogId of the links to fetch
          * @blogArticlesSqlRows array containing sql row objects of articles
          */
-        function BlogArticles( $blogId, $blogArticlesSqlRows )
+        function BlogArticles( $blogId, $blogArticles )
         {
             $this->_blogId = $blogId;
 
-            foreach( $blogArticlesSqlRows as $articleSqlRow ) {
-                $articleId  = $articleSqlRow['id'];
-                $categoryId = $articleSqlRow['category_id'];
-                $userId     = $articleSqlRow['user_id'];
-                $date       = $articleSqlRow['date'];
+            foreach( $blogArticles as $article ) {
+                $articleId  = $article->getId();
+                $userId     = $article->getUserId();
+                $date       = $article->getDate();
                 $year       = substr( $date, 0, 3 );
                 $month      = substr( $date, 4, 5 );
-                $status     = $articleSqlRow['status'];
+                $status     = $article->getStatus();
 
-                $this->_articles[]                        = $articleId;
-                $this->_articlesByCategory[$categoryId][] = $articleId;
-                $this->_articlesByDate[$date][]           = $articleId;
-                $this->_articlesByStatus[$status][]       = $articleId;
-                $this->_articlesByUser[$userId][]         = $articleId;
+                $this->_articles[]                        = $article;
+                $this->_articlesByCategory[$categoryId][] = $article;
+                $this->_articlesByDate[$date][]           = $article;
+                $this->_articlesByStatus[$status][]       = $article;
+                $this->_articlesByUser[$userId][]         = $article;
                 $this->_articleStatus[$articleId]         = $status;
                 $this->_articleDate[$articleId]           = $date;
-                $this->_articleDates[$year][$month][]     = $articleId;
-                $this->_articleCategories[$articleId][]   = $categoryId;
+                $this->_articleDates[$year][$month][]     = $article;
+                foreach( $article->getCategoryIds() as $categoryId )
+	                $this->_articleCategories[$articleId][]   = $categoryId;
             }
         }
 
@@ -80,7 +80,7 @@
             if( $articleIds == null )
                 return $this->_articlesByCategory[$categoryId];
 
-            $returnIds = array_intersect( $articleIds, $this->_articlesByCategory[$categoryId] );
+            $returnIds = array_intersect( $articleIds, $this->_articlesByCategory[$categoryId] );            
 
             return $returnIds;
         }

Modified: plog/trunk/class/dao/blogcategories.class.php
===================================================================
--- plog/trunk/class/dao/blogcategories.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/blogcategories.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -3,12 +3,16 @@
 	include_once( PLOG_CLASS_PATH."class/dao/model.class.php" );
 	include_once( PLOG_CLASS_PATH."class/dao/blogcategory.class.php" );
 	
+	define( "CACHE_BLOGCATEGORIES", "cache_blog_categories" );
+	define( "CACHE_BLOGCATEGORIES_ALL", "cache_blog_categories_all" );	
+	
 	class BlogCategories extends Model
 	{
 	
 		function BlogCategories()
 		{
-			$this->Model();
+			$this->Model();			
+			$this->table = $this->getPrefix()."blog_categories";
 		}
 		
 		/**
@@ -19,17 +23,7 @@
 		 */
 		function getBlogCategory( $id )
 		{
-			$prefix = $this->getPrefix();
-			$query = "SELECT * FROM {$prefix}blog_categories WHERE id = '".Db::qstr( $id )."'";			
-			
-			$result = $this->Execute( $query );
-			
-			if( !$result )
-				return false;
-				
-			$row = $result->FetchRow();
-			
-			return( $this->_mapRow( $row ));
+			return( $this->get( "id", $id, CACHE_BLOGCATEGORIES ));
 		}
 		
 		/**
@@ -41,21 +35,11 @@
 		 */
 		function addBlogCategory( &$category )
 		{
-			$prefix = $this->getPrefix();
-			$query = "INSERT INTO {$prefix}blog_categories (name, description, properties)
-			          VALUES ('".Db::qstr($category->getName())."','".Db::qstr($category->getDescription())."','".
-					  Db::qstr(serialize($category->getProperties()))."')";
-					  
-			$result = $this->Execute( $query );
-			
-			if( !$result )
-				return false;
+			if( ($result = $this->add( $category, Array( CACHE_BLOGCATEGORIES => "getId" )))) {
+				$this->_cache->removeData( "all", CACHE_BLOGCATEGORIES_ALL );
+			}
 				
-			// get and set the id for the last insertion
-			$id = $this->_db->Insert_ID();
-			$category->setId( $id );
-			
-			return( true );
+			return( $result );
 		}
 		
 		/**
@@ -68,10 +52,12 @@
 		 */
 		function deleteBlogCategory( $id )
 		{
-			$prefix = $this->getPrefix();
-			$query = "DELETE FROM {$prefix}blog_categories WHERE id = '".Db::qstr( $id )."'";
+			if( ($result = $this->delete( "id", $id ))) {
+				$this->_cache->removeData( $id, CACHE_BLOGCATEGORIES );
+				$this->_cache->removeData( "all", CACHE_BLOGCATEGORIES_ALL );
+			}
 			
-			return( $this->Execute( $query ));
+			return( $result );
 		}
 		
 		/**
@@ -82,14 +68,7 @@
 		 */
 		function updateBlogCategory( $category )
 		{
-			$prefix = $this->getPrefix();
-			$query = "UPDATE {$prefix}blog_categories SET
-			          name = '".Db::qstr( $category->getName())."',
-					  description = '".Db::qstr( $category->getDescription())."',
-					  properties = '".Db::qstr( $category->getProperties())."'
-					  WHERE id = '".Db::qstr( $category->getId())."'";
-					  
-			return( $this->Execute( $query ));
+			return( $this->update( $category ));
 		}
 		
 		/**
@@ -99,18 +78,7 @@
 		 */
 		function getNumBlogCategories()
 		{
-			$query = "SELECT COUNT(*) AS total FROM ".$this->getPrefix()."blog_categories";
-			
-			$result = $this->Execute( $query );
-			
-			if( !$result )
-				return 0;
-				
-			$row = $result->FetchRow();
-			if( $row["total"] == "" )
-				return( 0 );
-			else
-				return( $row["total"] );
+			return( $this->getNumItems( $this->table ));
 		}
 		
 		/**
@@ -122,21 +90,11 @@
 		 */
 		function getBlogCategories( $page = -1, $itemsPerPage = DEFAULT_ITEMS_PER_PAGE )
 		{
-			$prefix = $this->getPrefix();
-			$query = "SELECT * FROM {$prefix}blog_categories";
-			
-			// execute the paged query if necessary
-			$result = $this->Execute( $query, $page, $itemsPerPage );
-			
-			if( !$result )
-				return( false );
-				
-			// if everything ok, loop through the results
-			$categories = Array();
-			while( $row = $result->FetchRow()) {
-				array_push( $categories, $this->_mapRow( $row ));
-			}
-			
+			$categories = $this->getAll( "all", CACHE_BLOGCATEGORIES_ALL, 
+			                             Array( CACHE_BLOGCATEGORIES => "getId" ),
+			                             $page,
+			                             $itemsPerPage );
+			                             			                             
 			return( $categories );
 		}
 		
@@ -149,35 +107,27 @@
 		 */
 		function getNumBlogsCategory( $categoryId, $status = BLOG_STATUS_ALL )
 		{
-			$prefix = $this->getPrefix();
-			$query = "SELECT COUNT(*) AS total
-			          FROM {$prefix}blogs b
-			          WHERE b.blog_category_id = '".Db::qstr( $categoryId )."'";
+			$cond = "b.blog_category_id = '".Db::qstr( $categoryId )."'";			
 			if( $status != BLOG_STATUS_ALL )
-				$query .= " AND status = '".Db::qstr( $status )."'";
-				
-			$result = $this->Execute( $query );
+				$cond .= " AND status = '".Db::qstr( $status )."'";
 			
-			if( !$result )
-				return 0;
-			
-			$row = $result->FetchRow();
-			$total = $row["total"];
-			if( $total == "" ) $total = 0;
-			
-			return( $total );
+			return( $this->getNumItems( $this->getPrefix()."blogs", $cond ));
 			          
 		}
 		
 		/**
 		 * @private
 		 */
-		function _mapRow( $row )
+		function mapRow( $row )
 		{
-			return( new BlogCategory( $row["name"],
-			                          $row["description"],
-									  unserialize($row["properties"]),
-									  $row["id"] ));									  
+			$category = new BlogCategory( $row["name"],
+			                              $row["description"],
+							    		  unserialize($row["properties"]),
+								    	  $row["id"] );
+			$category->setNumBlogs( $row["num_blogs"] );
+			$category->setNumActiveBlogs( $row["num_active_blogs"] );
+				
+			return( $category );
 		}
 	}
 ?>
\ No newline at end of file

Modified: plog/trunk/class/dao/blogcategory.class.php
===================================================================
--- plog/trunk/class/dao/blogcategory.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/blogcategory.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -24,6 +24,14 @@
 			$this->_name = $name;
 			$this->_description = $description;
 			$this->_properties = $properties;
+			
+			$this->_pk = "id";
+			$this->_fields = Array( "id" => "getId",
+			                        "name" => "getName",
+			                        "description" => "getDescription",
+			                        "properties" => "getProperties",
+			                        "num_blogs" => "getNumBlogs",
+			                        "num_active_blogs" => "getNumActiveBlogs" );
 		}
 
         /**
@@ -80,11 +88,31 @@
          */
         function getNumBlogs( $status = BLOG_STATUS_ACTIVE )        
         {
-        	include_once( PLOG_CLASS_PATH."class/dao/blogcategories.class.php" );
-        	
-        	$categories = new BlogCategories();
-        	return( $categories->getNumBlogsCategory( $this->getId(), $status ));
+        	if( $status == BLOG_STATUS_ALL )
+        		return( $this->_numBlogs );
+        	elseif( $status == BLOG_STATUS_ACTIVE )
+        		return( $this->_numActiveBlogs );
+        	else {
+	        	include_once( PLOG_CLASS_PATH."class/dao/blogcategories.class.php" );        	
+    	    	$categories = new BlogCategories();
+        		return( $categories->getNumBlogsCategory( $this->getId(), $status ));
+        	}
         }
+        
+        function setNumBlogs( $numBlogs )
+        {
+        	$this->_numBlogs = $numBlogs;
+        }
+        
+        function getNumActiveBlogs()
+        {
+        	return( $this->getNumBlogs( BLOG_STATUS_ACTIVE ));
+        }
+        
+        function setNumActiveBlogs( $numActiveBlogs )
+        {
+        	$this->_numActiveBlogs = $numActiveBlogs;
+        }
 		
 		/**
 		 * returns a list with all the blogs that have been categorized under this category

Modified: plog/trunk/class/dao/bloginfo.class.php
===================================================================
--- plog/trunk/class/dao/bloginfo.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/bloginfo.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -25,11 +25,8 @@
         var $_totalPosts;
         var $_totalComments;
         var $_totalTrackbacks;
-        var $_viewedTotal;
         var $_ownerInfo;
         var $_usersInfo;
-        var $_createTimestamp;
-        var $_updateTimestamp;
 
         // the TemplateSet representing the template set used by the blog
         var $_templateSet;
@@ -46,6 +43,10 @@
 
         function BlogInfo( $blog, $owner, $about, $settings, $id = -1 )
         {
+        	include_once( PLOG_CLASS_PATH."class/data/timestamp.class.php" );
+        
+        	$this->DbObject();
+        
             $this->setBlog( $blog );
             $this->_owner = $owner;
             $this->_about = $about;
@@ -58,10 +59,12 @@
             $this->_createDate = "";
             $this->_updateDate = "";
             $this->_totalPosts = 0;
-            $this->_viewedTotal = 0;
+            $this->_totalTrackbacks = 0;
+            $this->_totalComments = 0;
             $this->_usersInfo = array();
-            $this->_createTimestamp = "";
-            $this->_updateTimestamp = "";
+            $t = new Timestamp();
+            $this->_createDate = $t->getTimestamp();
+            $this->_updateDate = $t->getTimestamp();
 
             // no template set loaded
             $this->_templateSet = null;
@@ -70,15 +73,28 @@
             $this->_status = BLOG_STATUS_ACTIVE;
 
             // values that are loaded on demand
-            $this->_updateTimestamp = null;
-            $this->_viewedTotal = null;
-            $this->_totalPosts = null;
-            $this->_createTimestamp = null;
             $this->_ownerInfo = null;
 			
 			// information about the blog category id
 			$this->_category = null;
 			$this->_categoryId = 0;
+			
+			$this->_pk = "id";
+			$this->_fields = Array(
+				"blog" => "getBlog",
+				"owner_id" => "getOwnerId",
+				"about" => "getAbout",
+				"settings" => "getSettings",
+				"mangled_blog" => "getMangledBlogName",
+				"status" => "getStatus",
+				"show_in_summary" => "getShowInSummary",
+				"blog_category_id" => "getBlogCategoryId",
+				"create_date" => "getCreateDate",
+				"last_update_date" => "getUpdateDate",
+				"num_posts" => "getTotalPosts",
+				"num_comments" => "getTotalComments",
+				"num_trackbacks" => "getTotalTrackbacks"
+			);
         }
 
         /**
@@ -91,7 +107,6 @@
             return $this->_blog;
         }
 
-
         /**
          * Returns the identifier of the user who owns this journal.
          *
@@ -189,93 +204,86 @@
             return true;
         }
 
-       /**
-        * :TODO: I'm not sure anyone ever calls this method, maybe we can
-        *        get rid of it
-        *                            (2005-05-31 ork at devel.plogworld.net)
-        *
-        */
-        function getCreateDateObject( )
+		/** 
+		 *
+		 */
+        function getCreateDateObject()
         {
-	        include_once( PLOG_CLASS_PATH."class/dao/blogs.class.php" );
-
-            // if it hasn't been loaded yet...
-            if( $this->_createTimestamp === null ) {
-                $blogs = new Blogs();
-                $this->setCreateDate( $blogs->getBlogCreateDate( $this->getId()));
-            }
-
-            return $this->_createTimestamp;
+        	include_once( PLOG_CLASS_PATH."class/data/timestamp.class.php" );        
+            return( new Timestamp( $this->_createDate ));
         }
+        
+        function getCreateDate()
+        {
+        	return( $this->_createDate );
+        }
+        
+        function setCreateDate( $date )
+        {
+        	$this->_createDate = $date;
+        }        
 
         /**
          */
-        function getUpdateDateObject( )
+        function getUpdateDateObject()
         {
-	        include_once( PLOG_CLASS_PATH."class/dao/blogs.class.php" );
-
-            if( $this->_updateTimestamp === null ) {
-                $blogs = new Blogs();
-                $this->setUpdateDate( $blogs->getBlogUpdateDate( $this->getId()));
-            }
-
-            return $this->_updateTimestamp;
+        	include_once( PLOG_CLASS_PATH."class/data/timestamp.class.php" );
+            return( new Timestamp( $this->_updateTimestamp ));
         }
+        
+        function getUpdateDate()
+        {
+        	return( $this->_updateDate );
+        }
+        
+        function setUpdateDate( $date )
+        {
+        	$this->_updateDate = $date;
+        }
 
         /**
          */
-        function getTotalPosts( )
+        function getTotalPosts()
         {
-	        include_once( PLOG_CLASS_PATH."class/dao/blogs.class.php" );
-
-            if( $this->_totalPosts === null ) {
-                $blogs = new Blogs();
-                $this->_totalPosts = $blogs->getBlogTotalPosts( $this->getId());
-            }
-
             return $this->_totalPosts;
         }
 
         /**
-         */
-        function getTotalComments( )
+         * @private
+         */                
+        function setTotalPosts( $totalPosts )
         {
-	        include_once( PLOG_CLASS_PATH."class/dao/blogs.class.php" );
+        	$this->_totalPosts = $totalPosts;
+        }
 
-            if( $this->_totalComments === null ) {
-                $blogs = new Blogs();
-                $this->_totalComments = $blogs->getBlogTotalComments( $this->getId());
-            }
+        /**
+         * @private
+         */        
+        function setTotalComments( $totalComments )
+        {
+        	$this->_totalComments = $totalComments;
+        }
 
+        /**
+         */
+        function getTotalComments()
+        {
             return $this->_totalComments;
         }
-
+        
         /**
+         * @private
          */
-        function getTotalTrackbacks( )
+        function setTotalTrackbacks( $totalTrackbacks )
         {
-	        include_once( PLOG_CLASS_PATH."class/dao/blogs.class.php" );
-
-            if( $this->_totalTrackbacks === null ) {
-                $blogs = new Blogs();
-                $this->_totalTrackbacks = $blogs->getBlogTotalTrackbacks( $this->getId());
-            }
-
-            return $this->_totalTrackbacks;
+        	$this->_totalTrackbacks = $totalTrackbacks;
         }
 
         /**
          */
-        function getViewedTotal( )
+        function getTotalTrackbacks()
         {
-	        include_once( PLOG_CLASS_PATH."class/dao/blogs.class.php" );
-
-            if( $this->_viewedTotal === null ) {
-                $blogs = new Blogs();
-                $this->_viewedTotal = $blogs->getBlogViewedTotal( $this->getId());
-            }
-
-            return $this->_viewedTotal;
+            return $this->_totalTrackbacks;
         }
 
         /**
@@ -360,44 +368,6 @@
         /**
          * @private
          */
-        function setCreateDate( $newCreateDate )
-        {
-        	include_once( PLOG_CLASS_PATH."class/data/timestamp.class.php" );
-            $this->_createDate = $newCreateDate;
-
-            $this->_createTimestamp = new Timestamp( $newCreateDate );
-        }
-
-        /**
-         * @private
-         */
-        function setUpdateDate( $newUpdateDate )
-        {
-        	include_once( PLOG_CLASS_PATH."class/data/timestamp.class.php" );        
-            $this->_updateDate = $newUpdateDate;           
-
-            $this->_updateTimestamp = new Timestamp( $newUpdateDate );
-        }
-
-        /**
-         * @private
-         */
-        function setTotalPosts( $newTotalPosts )
-        {
-            $this->_totalPosts = $newTotalPosts;
-        }
-
-        /**
-         * @private
-         */
-        function setViewedTotal( $newViewedTotal )
-        {
-            $this->_viewedTotal = $newViewedTotal;
-        }
-
-        /**
-         * @private
-         */
         function setOwnerInfo( $newOwnerInfo )
         {
             $this->_ownerInfo = $newOwnerInfo;
@@ -562,8 +532,8 @@
             // if there is no quota for this blog, then fetch it from the global
             // settings
             if( $quota == "" ) {
-                $config =& Config::getConfig();
-                $quota = $config->getValue( "resources_quota" );
+            	include_once( PLOG_CLASS_PATH."class/gallery/dao/galleryresourcequotas.class.php" );
+            	$quota = GalleryResourceQuotas::getGlobalResourceQuota();
             }
 
             return $quota;
@@ -624,5 +594,16 @@
 			
 			return( $this->_category );
 		}
+		
+		function getMangledBlogName()
+		{
+			include_once( PLOG_CLASS_PATH."class/data/textfilter.class.php" );
+			return( Textfilter::urlize( $this->getBlog()));
+		}
+		
+		function getShowInSummary()
+		{
+			return( $this->_showInSummary );
+		}
     }
 ?>
\ No newline at end of file

Modified: plog/trunk/class/dao/blogs.class.php
===================================================================
--- plog/trunk/class/dao/blogs.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/blogs.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -5,10 +5,15 @@
 
     /**
      * \ingroup DAO
-     * Model for the Blogs
+     * DAO class for BlogInfo objects, which represent a blog.
      */
     class Blogs extends Model
     {
+    	function Blogs()
+    	{
+    		$this->Model();    	
+    		$this->table = $this->getPrefix()."blogs";
+    	}
 
         /**
          * Returns information about a blog.
@@ -20,23 +25,7 @@
         function getBlogInfo( $blogId )
         {
             require_once( PLOG_CLASS_PATH . 'class/dao/bloginfo.class.php' );
-
-            $blogInfo = $this->_cache->getData( $blogId, CACHE_BLOGINFOS );
-
-            if( !$blogInfo ) {
-                require_once( PLOG_CLASS_PATH."class/database/db.class.php" );
-
-                $query = Db::buildSelectQuery( BLOGS_TABLENAME,
-                                               array(),
-                                               'id',
-                                               $blogId );
-                $blogInfo = $this->_getBlogInfoFromQuery( $query, $extendedInfo );
-
-                // save the blogInfo object in the cache.
-                $this->_cache->setData( $blogId, CACHE_BLOGINFOS, $blogInfo );
-            }
-
-            return $blogInfo;
+            return( $this->get( "id", $blogId, CACHE_BLOGINFOS, Array( CACHE_BLOGIDBYNAME => "getMangledBlogName" )));
         }
 
         /**
@@ -47,310 +36,28 @@
          */
         function getBlogInfoByName( $blogName, $extendedInfo = false )
         {
-            $blogId = $this->_cache->getData( $blogName, CACHE_BLOGIDBYNAME );
-
-            if ( !$blogId ) {
-                require_once( PLOG_CLASS_PATH."class/database/db.class.php" );
-
-                $query = Db::buildSelectQuery( BLOGS_TABLENAME,
-                                               array(),
-                                               'mangled_blog',
-                                               $blogName );
-
-                $blogInfo = $this->_getBlogInfoFromQuery( $query, $extendedInfo );
-
-                // and store the blogName-to-blogId relationship in the cache
-                $this->_cache->setData( $blogName, CACHE_BLOGIDBYNAME, $blogInfo->getId() );
-            } else {
-                $blogInfo = $this->getBlogInfo( $blogId );
-            }
-
-            return $blogInfo;
+            require_once( PLOG_CLASS_PATH . 'class/dao/bloginfo.class.php' );        
+        	return( $this->get( "mangled_blog", $blogName, CACHE_BLOGIDBYNAME, Array( CACHE_BLOGINFOS => "getId" )));
         }
 
-
         /**
-         * Retrieves the first article date timestamp
-         * :TODO: I'm not sure anyone ever calls this method, maybe we can
-         *        get rid of it
-         *                            (2005-05-31 ork at devel.plogworld.net)
-         *
-         * @param blogId The identifier of the blog from which we'd like 
-                         to fetch the creation date
-         * @return Returns an Timestamp with the first article date
-         */
-        function getBlogCreateDate( $blogId )
-        {
-            require_once( PLOG_CLASS_PATH . 'class/dao/articles.class.php' );
-
-            $articles     = new Articles();
-            $blogArticles = $articles->getArticles( $blogId );
-            // these are always sorted by date.
-            $allArticles  = $blogArticles->getArticleIds();
-
-            // there might be no article, we return 01.01.1970 then :-)
-            if( empty($allArticles) )
-                return '19700101000000';
-
-            // fetch the first article
-            $article  = $articles->getArticle( $allArticles[0] );
-
-            return $article->getDate();
-        }
-
-        /**
-         * Retrieves the last article date timestamp
-         *
-         * @param blogId The identifier of the blog from which we'd like to fetch the settings
-         * @return Returns an Timestamp with the last article date
-         */
-        function getBlogUpdateDate( $blogId )
-        {
-            require_once( PLOG_CLASS_PATH . 'class/dao/articles.class.php' );
-
-            $articles     = new Articles();
-            $blogArticles = $articles->getArticles( $blogId );
-            // these are always sorted by date.
-            $allArticles  = $blogArticles->getArticleIds();
-
-            // there might be no article, we return 01.01.1970 then :-)
-            if( empty($allArticles) )
-                return '19700101000000';
-
-            // fetch the last article
-            $article  = $articles->getArticle( $allArticles[count($allArticles) - 1] );
-
-            return $article->getDate();
-        }
-
-        /**
-         * Retrieves the total number of reads of all articles in that blog
-         *
-         * @param blogId The identifier of the blog from which we'd like to fetch the settings
-         * @return Returns an Timestamp with the last article date
-         */
-        function getBlogViewedTotal( $blogId )
-        {
-            $query  = "SELECT SUM(num_reads) as total FROM " . $this->getPrefix() .
-                      "articles WHERE blog_id = " . $blogId;
-
-            $result = $this->Execute( $query );
-
-            if (!$result)
-                return false;
-
-            $row = $result->FetchRow();
-
-            if (!isset($row["total"]))
-                return false;
-
-            return $row["total"];
-        }
-
-        /**
-         * Retrieves the total number of posts in a blog
-         *
-         * @param blogId The identifier of the blog from which we'd like to fetch the settings
-         * @return Returns an integer with the number of posts
-         */
-        function getBlogTotalPosts( $blogId )
-        {
-            require_once( PLOG_CLASS_PATH . 'class/dao/articlestatus.class.php' );
-            require_once( PLOG_CLASS_PATH . 'class/dao/articles.class.php' );
-
-            $articles     = new Articles();
-            $blogArticles = $articles->getArticles( $blogId );
-
-            $allArticles  = $blogArticles->getArticleIdsByStatus( POST_STATUS_PUBLISHED );
-
-            return count($allArticles);
-        }
-
-        /**
-         * Retrieves the total number of comments in a blog
-         *
-         * @param blogId The identifier of the blog from which we'd like to fetch the settings
-         * @return Returns an integer with the number of comments
-         */
-        function getBlogTotalComments( $blogId )
-        {
-            $query  = "SELECT COUNT(*) as total FROM ".$this->getPrefix()."articles_comments AS c, ".$this->getPrefix()."articles AS a WHERE ((a.blog_id = $blogId) AND (a.id = c.article_id)) AND c.status = ".COMMENT_STATUS_NONSPAM;
-            $result = $this->Execute( $query );
-
-            if (!$result)
-                return false;
-
-            $row = $result->FetchRow();
-
-            if (!isset($row["total"]))
-                return false;
-
-            return intval($row["total"]);
-        }
-
-        /**
-         * Retrieves the total number of trackbacks in a blog
-         *
-         * @param blogId The identifier of the blog from which we'd like to fetch the settings
-         * @return Returns an integer with the number of trackbacks
-         */
-        function getBlogTotalTrackbacks( $blogId )
-        {
-            $query  = "SELECT COUNT(*) as total FROM ".$this->getPrefix()."trackbacks AS t, ".$this->getPrefix()."articles AS a WHERE ((a.blog_id = $blogId) AND (a.id = t.article_id))";
-            $result = $this->Execute( $query );
-
-            if (!$result)
-                return false;
-
-            $row = $result->FetchRow();
-
-            if (!isset($row["total"]))
-                return false;
-
-            return intval($row["total"]);
-        }
-
-        /**
-         * Retrieves the blog settings
-         *
-         * @param settingsField The contents of the blog_settings field from the database
-         * @return Returns a BlogSettings object with the settings for the blog
-         */
-        function getBlogSettingsFromField( $settingsField )
-        {
-            require_once( PLOG_CLASS_PATH . "class/dao/blogsettings.class.php" );
-
-            if( $settingsField == "" || $settingsField == null ) {
-                $settings = new BlogSettings();
-            }
-            else {
-                $settings = unserialize( $settingsField );
-                if( !is_object($settings) ) {
-                    // if the BlogSettings object is not valid, return a valid one
-                    // with some of the default settings, so that at least
-                    // the blog will keep working!
-                    $settings = new BlogSettings();
-                }
-            }
-
-            return $settings;
-        }
-
-        /**
-         * Retrieves the blog settings given its id
-         *
-         * @param blogId The identifier of the blog from which we'd like to fetch the settings
-         * @return A BlogSettings object containing the settings, or 'false' if error.
-         */
-        function getBlogSettings( $blogId )
-        {
-            $blogInfo = $this->getBlogInfo( $blogId );
-
-            return $blogInfo->getSettings();
-        }
-
-        /**
          * Updates the configuration of a blog
          *
          * @param blogId Blog identifier
          * @param blogInfo A BlogInfo object containing all the information of the blog
          * @param return Returns true if everything's ok or false otherwise
          */
-        function updateBlog( $blogId, $blogInfo )
+        function updateBlog( $blog )
         {
-            require_once( PLOG_CLASS_PATH . 'class/data/textfilter.class.php' );
-            require_once( PLOG_CLASS_PATH . 'class/database/db.class.php' );
+        	$result = $this->update( $blog );
+        
+            $this->_cache->removeData( $blog->getMangledBlogName(), CACHE_BLOGIDBYNAME );
+            $this->_cache->removeData( $blog->getId(), CACHE_BLOGINFOS );
 
-            $blogName = TextFilter::urlize($blogInfo->getBlog());
-
-            // setup an array containing the values we would like to set in the db
-            $keyValuePairs = array();
-            $keyValuePairs['blog']         = $blogInfo->getBlog();
-            $keyValuePairs['about']        = $blogInfo->getAbout();
-            $keyValuePairs['settings']     = serialize( $blogInfo->getSettings() );
-            $keyValuePairs['owner_id']     = $blogInfo->getOwnerId();
-            $keyValuePairs['mangled_blog'] = $blogName;
-            $keyValuePairs['status']       = $blogInfo->getStatus();
-			$keyValuePairs['blog_category_id'] = $blogInfo->getBlogCategoryId();
-
-            $query = Db::buildUpdateQuery( BLOGS_TABLENAME,
-                                           $keyValuePairs,
-                                           'id',
-                                           $blogId );
-            $result = $this->Execute( $query );
-
-            $this->_cache->removeData( $blogName, CACHE_BLOGIDBYNAME );
-            $this->_cache->removeData( $blogId, CACHE_BLOGINFOS );
-
             return $result;
         }
 
-       /**
-        * Updates the settings of a blog
-        *
-        * @param blogId The blog we want to update
-        * @param blogSettings the BlogSettings object that we would like to update
-        * @return 'true' if all correct. 'false' otherwise.
-        */
-        function updateBlogSettings( $blogId, $blogSettings )
-        {
-            require_once( PLOG_CLASS_PATH . 'class/database/db.class.php' );
-
-            $query = Db::buildUpdateQuery( BLOGS_TABLENAME,
-                                           array( 'settings' => serialize($blogSettings) ),
-                                           'id',
-                                           $blogId );
-            $result = $this->Execute( $query );
-
-            $this->_cache->removeData( $blogId, CACHE_BLOGINFOS );
-
-            return $result;
-        }
-
          /**
-          * Sends a weblogsUpdate.ping xmlrpc call to notifiy of changes in this blog
-          *
-          * @param blogInfo The BlogInfo object containing information about the blog
-          * @return Returns true if successful or false otherwise.
-          */
-         function updateNotify( $blogInfo )
-         {
-            // source classes
-            include_once( PLOG_CLASS_PATH."class/net/xmlrpcclient.class.php" );
-            require_once( PLOG_CLASS_PATH . 'class/config/config.class.php' );            
-
-            // if this feature is not enabled, we quit
-            $config =& Config::getConfig();
-            if( !$config->getValue( "xmlrpc_ping_enabled" ))
-                return;
-
-            // get the array which contains the hosts
-            $hosts = $config->getValue( "xmlrpc_ping_hosts" );
-
-            // if it is not an array, quit
-            if( !is_array($hosts))
-                return;
-
-            // if no hosts, we can quit too
-            if( empty($hosts))
-                return;
-
-            // otherwise, we continue
-            $xmlrpcPingResult = Array();
-            $rg =& RequestGenerator::getRequestGenerator( $blogInfo );
-            $blogLink = $rg->blogLink();
-            foreach( $hosts as $host ) {
-                $client = new XmlRpcClient( $host );
-                $result = $client->ping( $blogInfo->getBlog(), $blogLink);
-                //print("result = ".$result. "is Error = ".$client->isError()." message: ".$client->getErrorMessage()."<br/>");
-                //$xmlrpcPingResult[$result["host"]
-                $xmlrpcPingResult=array_merge($xmlrpcPingResult, $result);
-            }
-
-            return $xmlrpcPingResult;
-         }
-
-         /**
           * Adds a new blog to the database.
           *
           * @param blog A BlogInfo object with the necessary information
@@ -368,30 +75,14 @@
             if( !$blogSettings )
                 $blogSettings = new BlogSettings();
 
-            $query = "INSERT INTO ".$this->getPrefix()."blogs (blog,owner_id,about,settings,mangled_blog,status,blog_category_id)
-                     VALUES ('".Db::qstr($blog->getBlog())."',".
-                     $blog->getOwner().",'".
-                     Db::qstr($blog->getAbout())."', '".
-                     Db::qstr(serialize($blogSettings))."', '".
-                     TextFilter::urlize($blog->getBlog())."', '".
-                     Db::qstr($blog->getStatus())."','".
-					 Db::qstr($blog->getBlogCategoryId())."');";
+			$blogId = $this->add( $blog );
 
-            $result = $this->Execute( $query );            
-
-            if( !$result ){
-                // FIXME: throw an exception?
-                return false;
-            }
-
-
-            $blogId = $this->_db->Insert_ID();
-
-            $blog->setId( $blogId );
-
             // create the row for the bayesian filter info
             $bayesianFilterInfo = new BayesianFilterInfos();
             $bayesianFilterInfo->insert( $blogId );
+            
+            $this->_cache->setData( $blogId, CACHE_BLOGINFOS, $blog );
+            $this->_cache->setDate( $blog->getMangledBlogName(), CACHE_BLOGIDBYNAME );
 
             // and return the blog identifier
             return $blogId;
@@ -438,25 +129,14 @@
 
             $blogs = Array();
             while( $row = $result->FetchRow()) {
-                $blog = $this->_fillBlogInformation( $row, true );
+                $blog = $this->mapRow( $row );
                 $blogs[$blog->getId()] = $blog;
             }
 
             return $blogs;
-        }
-        
+        }    
 
         /**
-         * @see Model::buildSearchCondition
-         */
-        function buildSearchCondition( $searchTerms )
-        {
-            $searchCond = "(blog LIKE '%".Db::qstr(trim($searchTerms))."%')";
-            
-            return( $searchCond );
-        }      
-
-        /**
          * returns only an array with all the blog ids
          *
          * @return an array with blog ids
@@ -542,36 +222,6 @@
             return $result;
         }
 
-         /**
-          * disables a blog, this is done by setting the status of the blog
-          * to BLOG_STATUS_DISABLED. The blog an all posts still remain in
-          * the database.
-          *
-          * @param blogId
-          * @see deleteBlog
-          */
-        function disableBlog( $blogId )
-        {
-            require_once( PLOG_CLASS_PATH."class/database/db.class.php" );
-
-            $keyValuePairs = array();
-            $keyValuePairs['status'] = BLOG_STATUS_DISABLED;
-
-            $query = Db::buildUpdateQuery( BLOGS_TABLENAME,
-                                           $keyValuePairs,
-                                           'id',
-                                           $blogId );
-
-            $result = $this->Execute( $query );
-
-            if( !$result || $this->_db->Affected_Rows() == 0 )
-                return false;
-
-            $this->_cache->removeData( $blogId, CACHE_BLOGINFOS );
-
-            return true;
-        }
-
         /**
          * removes all blogs that have 'deleted' status
          *
@@ -579,64 +229,32 @@
          */        
         function purgeBlogs()
         {                                  
-            // delete blogs marked as disabled leave the username intact. 
-            // If the username is disabled, the Purge User featuer will delete them
-            
-            $b_query = "SELECT * FROM ".$this->getPrefix()."blogs WHERE status = ".BLOG_STATUS_DISABLED;
-
-            $b_result = $this->Execute( $b_query );
-            if( !$b_result )
-                return false;
-            
-            while( $b_row = $b_result->FetchRow()) {
-                $this->deleteBlog( $b_row["id"] );
-            }            
-                                   
-            return true;
+        	return( $this->delete( "status", BLOG_STATUS_DISABLED ));
         }
 
-        /**
+		/**
          * @private
          */
-        function _getBlogInfoFromQuery( $query, $extendedInfo = false )
+        function mapRow( $row )
         {
-            $result = $this->Execute( $query );
-
-            if( !$result )
-                return false;
-
-            if( $result->RecordCount() == 0 )
-                return false;
-
-            $row = $result->FetchRow( $result );
-            $blogInfo = $this->_fillBlogInformation( $row, $extendedInfo );
-            $blogSettings = $this->getBlogSettingsFromField( $row["settings"] );
-            $blogInfo->setSettings( $blogSettings );
-
-            return $blogInfo;
-        }
-
-        /**
-         * Private function.
-         *
-         * @private
-         */
-        function _fillBlogInformation( $query_result, $extended = false )
-        {
             // source class
             include_once( PLOG_CLASS_PATH."class/dao/bloginfo.class.php" );
 
             // create new BlogInfo
-            $blogInfo = new BlogInfo( stripslashes($query_result["blog"]),
-                                      $query_result["owner_id"],
-                                      stripslashes($query_result["about"]),
-                                      unserialize($query_result["settings"]),
-                                      $query_result["id"] );
+            $blogInfo = new BlogInfo( stripslashes($row["blog"]),
+                                      $row["owner_id"],
+                                      stripslashes($row["about"]),
+                                      unserialize($row["settings"]),
+                                      $row["id"] );
 
             // load information about the blog status
-            $blogInfo->setStatus( $query_result["status"] );
+            $blogInfo->setStatus( $row["status"] );
 			// load information abotu the blog category id
-			$blogInfo->setBlogCategoryId( $query_result["blog_category_id"] );
+			$blogInfo->setBlogCategoryId( $row["blog_category_id"] );
+			// counters
+			$blogInfo->setTotalPosts( $row['num_posts'] );
+			$blogInfo->setTotalTrackbacks( $row['num_trackbacks'] );
+			$blogInfo->setTotalComments( $row['num_comments'] );
 
             return $blogInfo;
         }

Modified: plog/trunk/class/dao/commentscommon.class.php
===================================================================
--- plog/trunk/class/dao/commentscommon.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/commentscommon.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -16,6 +16,12 @@
 	define( "COMMENT_TYPE_COMMENT", 1 );
 	define( "COMMENT_TYPE_TRACKBACK", 2 );	
 	define( "COMMENT_TYPE_ANY", -1 );
+	
+	/**
+	 * caches used
+	 */
+	define( "CACHE_ARTICLE_COMMENTS", "article_comments" );
+	define( "CACHE_ARTICLE_COMMENTS_BYARTICLE", "article_comments_byarticle" );
 
     /**
 	 * \ingroup DAO
@@ -34,7 +40,6 @@
 	class CommentsCommon extends Model 
 	{
 
-    	var $totalComments;
 		var $_blogSettings;
 		var $blogSettings;
 		var $timeDiff;
@@ -42,13 +47,7 @@
     	function CommentsCommon()
         {
         	$this->Model();
-
-            $this->totalComments = Array();
-
-            $this->_blogSettings = Array();
-			
-			$this->blogSettings = null;
-			$this->timeDiff = 0;			
+			$this->table = $this->getPrefix()."articles_comments";
         }
 
         /**
@@ -60,27 +59,32 @@
          */
 		function addComment( &$comment ) 
         {
-			$filter = new Textfilter();
-        	$query = "INSERT INTO ".$this->getPrefix().
-			          "articles_comments (article_id,topic,text,user_name,user_email,
-					                      user_url,parent_id,client_ip,status, normalized_text,normalized_topic,type) 
-					   VALUES (".$comment->getArticleId().",'".Db::qstr($comment->getTopic())."','".
-					   Db::qstr($comment->getText())."','".$comment->getUserName()."','".$comment->getUserEmail()."','".
-					   $comment->getUserUrl()."',".
-					   $comment->getParentId().", '".$comment->getClientIp()."', ".$comment->getStatus().", '".
-					   Db::qstr($filter->normalizeText($comment->getText()))."', '".
-					   Db::qstr($filter->normalizeText($comment->getTopic()))."',".$comment->getType().");";
-
-
-            $result = $this->Execute( $query );
-			
-			if( !$result )
-				return false;
-			
-			// retrieve the last id and save it in the object
-			$comment->setId( $this->_db->Insert_ID());
-			
-			return( true );
+        	if(( $result = $this->add( $comment ))) {
+        		include_once( PLOG_CLASS_PATH."class/dao/articles.class.php" );
+				$this->_cache->removeData( $comment->getArticleId(), CACHE_ARTICLE_COMMENTS_BYARTICLE );
+				// update the article comments
+				$article = $comment->getArticle();
+				$blog = $article->getBlogInfo();
+				if( $comment->getType() == COMMENT_TYPE_COMMENT ) {
+					$article->setTotalComments( $article->getTotalComments() + 1 );
+					if( $comment->getStatus() == COMMENT_STATUS_ACTIVE ) {
+						$article->setNumComments( $article->getNumComments() +1 );
+					}
+					$blog->setTotalComments( $blog->getTotalComments() + 1 );
+				}
+				else {
+					$article->setTotalTrackbacks( $article->getTotalTrackbacks() + 1 );
+					if( $comment->getStatus() == COMMENT_STATUS_ACTIVE ) {
+						$article->setNumTrackbacks( $article->getNumTrackbacks() +1 );
+					}
+					$blog->setTotalTrackbacks( $blog->getTotalTrackbacks() + 1 );					
+				}
+				$articles = new Articles();
+				$articles->updateArticle( $article );
+				$blogs = new Blogs();
+				$blogs->updateBlog( $blog );
+        	}
+        	return( $result );
         }
 
 		/**
@@ -94,124 +98,46 @@
 		 * @param itemsPerPage
 		 * @return False if error or an array of ArticleComments objects
 		 */
-		function getPostComments( $artid, $order = COMMENT_ORDER_NEWEST_FIRST, $status = COMMENT_STATUS_ALL, $type = COMMENT_TYPE_ANY, $page = -1, $itemsPerPage = DEFAULT_ITEMS_PER_PAGE )
+		function getPostComments( $artid, 
+		                          $order = COMMENT_ORDER_NEWEST_FIRST, 
+		                          $status = COMMENT_STATUS_ALL, 
+		                          $type = COMMENT_TYPE_ANY, 
+		                          $page = -1, 
+		                          $itemsPerPage = DEFAULT_ITEMS_PER_PAGE )
 		{
-			$query = "SELECT * FROM ".$this->getPrefix()."articles_comments WHERE article_id = '".Db::qstr($artid)."'";
-            if( $status != COMMENT_STATUS_ALL )
-            	$query .= " AND status = $status";
-			if( $type != COMMENT_TYPE_ANY )
-				$query .= " AND type = '".Db::qstr($type)."'";
+			$comments = $this->getMany( "article_id",
+			                            $artid,
+			                            CACHE_ARTICLE_COMMENTS_BYARTICLE,
+			                            Array( CACHE_ARTICLE_COMMENTS => "getId" ),
+			                            $page,
+			                            $ItemsPerPage );
+			                            
+			/**
+			 * :TODO:
+			 * - filter by status!!!
+			 * - filter by type!!!
+			 * - use the $order parameter!!!
+			 */
 
-			// check in which order we should display those comments
-			if( $order == COMMENT_ORDER_NEWEST_FIRST )
-				$query .= " ORDER BY date DESC";
-			else
-				$query .= " ORDER BY date ASC";
-			
-            $result = $this->Execute( $query, $page, $itemsPerPage );			
-
-            if( !$result )
-            	return Array();
-
-            $comments = Array();
-            while ($row = $result->FetchRow()) {
-
-				// find out the blogInfo object (after all, all these comments belong to the same
-				// blog so there is no risk of finding different blog_ids anywhere!
-				if( $this->blogSettings === null ) {
-					$prefix = $this->getPrefix();
-					$articleId = $row["article_id"];
-					
-					$query = "SELECT DISTINCT b.settings AS settings FROM {$prefix}blogs b, {$prefix}articles a,
-					         {$prefix}articles_comments c WHERE c.article_id = a.id AND a.blog_id = b.id
-							 AND a.id = $articleId";
-					$result2 = $this->Execute( $query );
-					$tmpRow = $result2->FetchRow();
-					$this->blogSettings = Blogs::getBlogSettingsFromField( $tmpRow["settings"] );
-					
-					$this->timeDiff = $this->blogSettings->getValue( "time_offset" );
+			$result = Array();
+			if( $comments ) {
+				// load the post to get the blog in order to get the time difference
+				$articles = new Articles();
+				$article = $articles->getArticle( $artid );
+				$blog = $article->getBlogInfo();
+				$blogSettings = $blog->getSettings();
+				$timeDiff = $blogSettings->getValue( "time_offset" );
+				include_once( PLOG_CLASS_PATH."class/data/timestamp.class.php" );
+				foreach( $comments as $comment ) {
+					$date = Timestamp::getDateWithOffset( $comment->getDate(), $timeDiff );
+					$comment->setDate( $date );
+					$result[] = $comment;
 				}
-				
-			
-            	$lastArticleId=$row["article_id"];
-				
-				// now that we've got the time difference, we can
-				// calculate what would the "real" date...
-				$date = $row["date"];								
-				$date = Timestamp::getDateWithOffset( $date, $this->timeDiff );
-				$comment = $this->_fillCommentInformation( $row );
-				
-                $comments[] = $comment;
-			}			
-
-			return $comments;
-		}
-		
-		/**
-		 * Retrieves all the comments for subquery of posts
-		 *
-		 * @private
-		 */
-		function getPostCommentsByIds( $ids, $order = COMMENT_ORDER_NEWEST_FIRST, $status = COMMENT_STATUS_ALL, $type = COMMENT_TYPE_ANY )
-		{
-
-			$query = "SELECT * FROM ".$this->getPrefix()."articles_comments WHERE article_id IN (".$ids.")";
-			if( $type != COMMENT_TYPE_ANY )
-				$query .= " AND type = '".Db::qstr($type)."'";			
-            if( $status != COMMENT_STATUS_ALL )
-            	$query .= " AND status = '".Db::qstr($status)."'";
-
-			// check in which order we should display those comments
-			if( $order == COMMENT_ORDER_NEWEST_FIRST )
-				$query .= " ORDER BY date DESC";
+			}
 			else
-				$query .= " ORDER BY date ASC";
-			$result = $this->Execute( $query );
-			if( !$result )
-            	return false;
+				$result = Array();
 				
-			// initialize these two thingies with harmless values
-			$blogSettings = null;
-			$timeDiff = 0;
-
-            while ($row = $result->FetchRow()) {
-			
-				// find out the blogInfo object (after all, all these comments belong to the same
-				// blog so there is no risk of finding different blog_ids anywhere!
-				if( $this->blogSettings === null ) {
-					$prefix = $this->getPrefix();
-					$articleId = $row["article_id"];
-					
-					$query = "SELECT DISTINCT b.settings AS settings FROM {$prefix}blogs b, {$prefix}articles a,
-					         {$prefix}articles_comments c WHERE c.article_id = a.id AND a.blog_id = b.id
-							 AND a.id = $articleId";
-					$result2 = $this->Execute( $query );
-					$tmpRow = $result2->FetchRow();
-					$this->blogSettings = Blogs::getBlogSettingsFromField( $tmpRow["settings"] );
-					
-					$this->timeDiff = $this->blogSettings->getValue( "time_offset" );
-				}
-				
-			
-            	$lastArticleId=$row["article_id"];
-				
-				// now that we've got the time difference, we can
-				// calculate what would the "real" date...
-				$date = $row["date"];				
-				$date = Timestamp::getDateWithOffset( $date, $this->timeDiff );
-
-				/**$comment = new UserComment( $row["article_id"],	$row["parent_id"], $row["topic"],
-											$row["text"], $date, $row["user_name"], $row["user_email"],
-											$row["user_url"], $row["client_ip"], $row["spam_rate"], $row["status"],
-											$row["id"] );**/
-											
-				$comment = $this->_fillCommentInformation( $row );
-				
-				// save the comment in the array
-                $comments[$lastArticleId][]=$comment;
-			}
-
-			return $comments;
+			return( $result );			               
 		}
 		
         /**
@@ -236,82 +162,45 @@
 			// get the number of items and return it to the caller
 			return( $this->getNumItems( $table, $cond ));		
         }
-		
+        
         /**
-         * Returns the total number of comments for a given blog
-		 *
-		 * @param artId the post id
-		 * @param status
-		 * @return The number of comments
+         * returns the number of comments that a blog has
+         *
+         * @param blogId
+         * @param status
+         * @param type
+         * @return The number of comments, or 0 if error or no comments
          */
         function getNumBlogComments( $blogId, $status = COMMENT_STATUS_ALL, $type = COMMENT_TYPE_ANY )
         {
-			// create the table name
-			$prefix = $this->getPrefix();
-			$table = "{$prefix}articles_comments c, {$prefix}articles a";
-			// and the condition if any...
-			$cond = "a.blog_id = '".Db::qstr($blogId)."' AND c.article_id = a.id";
-			if( $status != COMMENT_STATUS_ALL )
-				$cond .= " AND c.status = '".Db::qstr($status)."'";
-			if( $type != COMMENT_TYPE_ANY )
-				$cond .= " AND c.type = '".Db::qstr($type)."'";			
-
-			// get the number of items and return it to the caller
-			return( $this->getNumItems( $table, $cond ));		
-        }		
-
-        /**
-         * Retrieves only one post from a given article
-         */
-        function getPostComment( $artid, $commentid, $type = COMMENT_TYPE_ANY )
-		{
-			$query = "SELECT * FROM ".$this->getPrefix()."articles_comments 
-			          WHERE id = '".Db::qstr($commentid)."' AND article_id = '".Db::qstr($artid)."'";
-			if( $type != COMMENT_TYPE_ANY )
-				$query .= " AND type = '".Db::qstr($type)."'";					  
-
-			$result = $this->Execute( $query );
-
-			if( !$result )
-				return false;
-
-            $row = $result->FetchRow();
-            $comment = $this->_fillCommentInformation( $row );
-
-			return $comment;
-		}
-
-        /**
-         * Returns true if there already is a comment in the database with the same
-         * article_id field, topic, text, replying to the same comment, username and so on
-         * Useful in case we want to check if the user sent the same comment by mistake
-         * by pressing the 'reload' button twice or something...
-         *
-         * @return Returns true if there already is such comment or false otherwise.
-         */
-        function getIdenticalComment( $topic, $text, $articleId, $parentId = 0, $userName = "", $userEmail = "", $userUrl = "", $clientIp = "0.0.0.0", $type = COMMENT_TYPE_ANY )
-        {
-        	$query = "SELECT COUNT(*) AS total FROM ".$this->getPrefix()."articles_comments
-                       WHERE topic = '".Db::qstr($topic)."' AND text = '".Db::qstr($text)."'
-                       AND article_id = $articleId AND parent_id = $parentId AND
-                       client_ip = '$clientIp' AND user_name = '$userName' AND
-                       user_email = '$userEmail' AND user_url = '$userUrl'
-                       AND date <= NOW()";
-			if( $type != COMMENT_TYPE_ANY )
-				$query .= " AND type = '".Db::qstr($type)."'";
-					   
-
-            $result = $this->Execute( $query );
-
-            if( !$result )
-            	return false;
-
-            $row = $result->FetchRow();
-
-            if( $row["total"] >= 1 )
-            	return true;
-            else
-            	return false;
+        	if( $status == COMMENT_STATUS_ALL && $type =! COMMENT_TYPE_ANY ) {
+        		// fast case, we can load the blog and query one of its intrinsic fields
+        		include_once( PLOG_CLASS_PATH."class/dao/blogs.class.php" );
+        		$blogs = new Blogs();
+        		$blogInfo = $blogs->getBlogInfoById( $blogId );
+        		if( !$blogInfo )
+        			$numComments = 0;
+        		else {
+        			if( $type == COMMENT_TYPE_COMMENT )
+	        			$numComments = $blog->getTotalComments();
+	        		else
+	        			$numComments = $blog->getTotalTrackbacks();
+        		}
+        	}
+        	else {
+				// create the table name
+				$prefix = $this->getPrefix();
+				$table = "{$prefix}articles_comments";
+				// and the condition if any...
+				$cond = "blog_id = '".Db::qstr($blogId)."'";
+				if( $status != COMMENT_STATUS_ALL )
+					$cond .= " AND status = '".Db::qstr($status)."'";
+				if( $type != COMMENT_TYPE_ANY )
+					$query .= " AND type = '".Db::qstr($type)."'";				
+				$numComments = $this->getNumItems( $table, $cond );
+        	}
+        	
+        	return( $numComments );
         }
 
 		/**
@@ -321,47 +210,52 @@
          *
          * @param artid The article identifier.
          * @param commentid The comment identifier.
-		 * @param type
 		 */
-		function deletePostComment( $artid, $commentid, $type = COMMENT_TYPE_ANY )
+		function deleteComment( $commentid )
 		{
-			$query = "DELETE FROM ".$this->getPrefix()."articles_comments 
-			          WHERE id = '".Db::qstr($commentid)."' AND article_id = '".Db::qstr($artid)."'";
-			if( $type != COMMENT_TYPE_ANY )
-				$query .= " AND type = '".Db::qstr($type)."'";
+			$comment = $this->getComment( $commentid );
+			if( $comment )  {
+				$this->delete( "id", $commentid );
+	            // update all the other posts
+    	        $query = "UPDATE ".$this->getPrefix()."articles_comments SET parent_id = 0 WHERE parent_id = ".$commentid." AND article_id = ".$artid.";";
+        	    $result = $this->Execute( $query );
+        	    $this->_cache->removeData( $comment->getId(), CACHE_ARTICLE_COMMENTS );
+        	    $this->_cache->removeData( $comment->getArticleId(), CACHE_ARTICLE_COMMENTS_BYARTICLE );
+        	    
+        	    // update the blog and the article counters
+        	    include_once( PLOG_CLASS_PATH."class/dao/blogs.class.php" );
+        	    include_once( PLOG_CLASS_PATH."class/dao/articles.class.php" );
 
-			$result = $this->Execute( $query );
-
-			if( $this->_db->Affected_Rows( $result ) == 0 )
-				return;
-
-            // update all the other posts
-            $query = "UPDATE ".$this->getPrefix()."articles_comments SET parent_id = 0 WHERE parent_id = ".$commentid." AND article_id = ".$artid.";";
-            $result = $this->Execute( $query );
-
-			return $result;
+        	    $article = $comment->getArticle();
+        	    $blog = $article->getBlogInfo();
+        	    $type = $comment->getType();
+        	    if( $type == COMMENT_TYPE_COMMENT ) {
+	        	    $blog->setTotalComments( $blog->getTotalComments() - 1 );
+	        		$article->setTotalComments( $article->getTotalComments() - 1 );	        	    
+		        	if( $comment->getStatus() == COMMENT_STATUS_ACTIVE ) {
+		        		$article->setNumComments( $article->getNumComments() - 1 );		        		
+		        	}
+	        	}
+	        	else {
+	        	    $blog->setTotalTrackbacks( $blog->getTotalTrackbacks() - 1 );	        	
+	        		$article->setTotalTrackbacks( $article->getTotalTrackbacks() - 1 );
+		        	if( $comment->getStatus() == COMMENT_STATUS_ACTIVE ) {
+		        		$article->setNumTrackbacks( $article->getNumTrackbacks() - 1 );		        		
+		        	}
+	        	}
+        	    $blogs = new Blogs();
+	        	$blogs->updateBlog( $blog );
+        	    $articles = new Articles();
+        	    $articles->updateArticle( $article );        	    
+			}
+			else {
+				return false;
+			}
+				
+			return( true );
 		}		
 
         /**
-         * Removes all the comments from a post.
-         *
-         * @param artId The article identifier
-		 * @param type
-         */
-        function deletePostComments( $artId, $type = COMMENT_TYPE_ANY )
-        {
-        	$query = "DELETE FROM ".$this->getPrefix()."articles_comments 
-			          WHERE article_id = '".Db::qstr($artId)."'";
-			if( $type != COMMENT_TYPE_ANY )
-				$query .= " AND type = '".Db::qstr($type)."'";
-					          
-
-			$result = $this->Execute( $query );
-
-            return $result;
-        }
-
-        /**
          * updates the status of a comment, regarding its spam status...
          *
          * @param commentId
@@ -371,15 +265,21 @@
          */
         function updateCommentStatus( $commentId, $status, $type = COMMENT_TYPE_ANY )
         {
-        	$query = "UPDATE ".$this->getPrefix()."articles_comments SET
-                      status = '".Db::qstr($status)."', date = date
-                      WHERE id = '".Db::qstr($commentId)."'";
-			if( $type != COMMENT_TYPE_ANY )
-				$query .= " AND type = '".Db::qstr($type)."'";					  
-
-            $result = $this->Execute( $query );
-
-            return $result;
+        	$comment = $this->getComment( $commentId );
+        	if( !$comment )
+        		return false;
+        	
+        	if( $type != COMMENT_TYPE_ANY )
+        		if( $comment->getType() != $type )
+        			return false;
+        			
+        	$comment->setStatus( $status );
+        	if(($result = $this->update( $comment ))) {
+        		$this->_cache->setData( $comment->getId(), CACHE_ARTICLE_COMMENTS, $comment );
+        		$this->_cache->removeData( $comment->getArticleId(), CACHE_ARTICLE_COMMENTS_BYARTICLE );
+        	}
+        	
+        	return( $result );
         }
 
         /**
@@ -394,6 +294,11 @@
 			if( $type != COMMENT_TYPE_ANY )
 				$query .= " AND type = '".Db::qstr($type)."'";					  
 			          
+			/**
+			 * :TODO:
+			 *
+			 * - clean the whole cache of comments!
+			 */
 
             return $this->Execute( $query );
         }		
@@ -405,22 +310,16 @@
 		 */
 		function getComment( $id, $type = COMMENT_TYPE_ANY )
 		{
-			$query = "SELECT * FROM ".$this->getPrefix()."articles_comments
-					  WHERE id = '".Db::qstr($id)."'";
-			if( $type != COMMENT_TYPE_ANY )
-				$query .= " AND type = '".Db::qstr($type)."'";
-			
-			$result = $this->Execute( $query );
-			
-			if( !$result )
+			$comment = $this->get( "id" , $id, CACHE_ARTICLE_COMMENTS );
+			if( !$comment )
 				return false;
+			if( $type != COMMENT_TYPE_ANY ) {
+				if( $comment->getType() != $type ) {
+					return false;
+				}
+			}
 				
-			if( $result->RowCount() == 0 )
-				return false;
-				
-			$row = $result->FetchRow();
-			
-			return $this->_fillCommentInformation( $row );
+			return( $comment );
 		}
 		
 		/**
@@ -432,10 +331,14 @@
 		 */
 		function getBlogComments( $blogId, $order = COMMENT_ORDER_NEWEST_FIRST, $status = COMMENT_STATUS_ALL, $type = COMMENT_TYPE_ANY, $page = -1, $itemsPerPage = DEFAULT_ITEMS_PER_PAGE )
 		{
+			/**
+			 * :TODO:
+			 * - implement this method in a better way!
+			 */
 			$prefix = $this->getPrefix();
 			$query = "SELECT c.*
-			          FROM {$prefix}articles_comments c, {$prefix}articles a
-			          WHERE a.blog_id = '".Db::qstr($blogId)."' AND a.id = c.article_id";
+			          FROM {$prefix}articles_comments c
+			          WHERE c.blog_id = '".Db::qstr( $blogId )."'";
             if( $status != COMMENT_STATUS_ALL )
             	$query .= " AND status = $status";
 			if( $type != COMMENT_TYPE_ANY )
@@ -458,76 +361,30 @@
 			$comments = Array();
 			$articles = new Articles();
 			while( $row = $result->FetchRow()) {
-				// load the article to which this comment belongs
-				$comment = $this->_fillCommentInformation( $row );
-				$article = $articles->getBlogArticle( $comment->getArticleId(), $blogId );
-				$comment->setArticle( $article );
-				// and store everything in the array
-				$comments[] = $comment;
+				$comments[] = $this->mapRow( $row );
 			}
 			 
 			return $comments;
 		}
 		
-        /**
-         * code factored out and made to be reused through several functions here...
-		 *
-		 * @private
-         */
-        function _fillCommentInformation( $row )
-        {
+		function mapRow( $row )
+		{
             require_once( PLOG_CLASS_PATH."class/dao/usercomment.class.php" );
             require_once( PLOG_CLASS_PATH."class/data/timestamp.class.php" );
-        	// ---
-            // this stuff is another disgusting hack to make comments
-            // be aware of time differences that may have been set by
-            // users in their blogs... actually, it will make the whole
-            // thing run a little bit slower because for every article
-            // that we fetch, we need to know the time difference
-            // and that means, additional accesses to the database :(
-            // But hey, users demand these things and we are not in the position
-            // to deny anything, are we? :P
-            // ---
-            // at the same time, we're going to brake some of our "nicely"
-            // implemented bussiness logic with the query below, bypassing all
-            // our objects and directly fetching info from the database, just for
-            // the sake of being able to do things with a single query rather
-            // than needing at least two to do the same. We would have to first
-            // find to which blog the given article belongs and then use another
-            // query to find its settings... If we do it this way, we can still
-            // do it in one query and get a nice BlogSettings object with the
-            // information that we need. Dirty but works :S
-            // ---
+
             $prefix = $this->getPrefix();
             $date = $row["date"];
             $articleId = $row["article_id"];
-
-            // let's try and keep some kind of cache for this...
-            if( empty($this->_blogSettings[$articlId])) {
-            	$query = "SELECT DISTINCT b.settings AS settings
-                          FROM {$prefix}blogs b, {$prefix}articles a,
-                          {$prefix}articles_comments c
-                          WHERE c.article_id = a.id AND
-                          a.blog_id = b.id
-                          AND a.id = $articleId";
-                $result = $this->Execute( $query );
-				if( !$result ) 
-					return false;
-				
-                $tmpRow = $result->FetchRow();
-                $blogSettings = Blogs::getBlogSettingsFromField( $tmpRow["settings"] );
-                $this->_blogSettings[$articleId] = $blogSettings;
-            }
-            else {
-            	$blogSettings = $this->_blogSettings[$articleId];
-            }
-
+            $blogId = $row["blog_id"];
+            
+            $blogs =  new Blogs();
+            $blogInfo = $blogs->getBlogInfo( $blogId );
+            $blogSettings = $blogInfo->getSettings();
             $timeDiff = $blogSettings->getValue( "time_offset" );
-            // now that we've got the time difference, we can
-            // calculate what would the "real" date...
             $date = Timestamp::getDateWithOffset( $date, $timeDiff );
 
         	$comment = new UserComment( $row["article_id"],
+        	                            $row['blog_id'],
             							$row["parent_id"],
                                         $row["topic"],
                                         $row["text"],
@@ -541,6 +398,6 @@
                                         $row["id"] );
 
             return $comment;
-        }
+		}				
 	}
 ?>
\ No newline at end of file

Modified: plog/trunk/class/dao/customfields/customfield.class.php
===================================================================
--- plog/trunk/class/dao/customfields/customfield.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/customfields/customfield.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -29,6 +29,15 @@
 			$this->_searchable = $searchable;
 			$this->_hidden = $hidden;
 			$this->_defaultValue = "";
+			
+			$this->_fields = Array(
+				"field_name" => "getName",
+				"blog_id" => "getBlogId",
+				"field_description" => "getDescription",
+				"field_type" => "getType",
+				"hidden" => "getHidden",
+				"searchable" => "getSearchable"
+			);
 		}
 		
 		function getBlogId()
@@ -36,6 +45,11 @@
 			return $this->_blogId;
 		}
 		
+		function setBlogId( $blogId )
+		{
+			$this->_blogId = $blogId;
+		}		
+		
 		function getId()
 		{
 			return $this->_id;
@@ -109,6 +123,11 @@
 			$this->_hidden = $hidden;
 		}
 		
+		function setSearchable( $searchable )
+		{
+			$this->searchable = $searchable;
+		}
+		
 		function getDefaultValue()
 		{
 			return $this->_defaultValue;	

Modified: plog/trunk/class/dao/customfields/customfieldcheckboxvalue.class.php
===================================================================
--- plog/trunk/class/dao/customfields/customfieldcheckboxvalue.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/customfields/customfieldcheckboxvalue.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -14,9 +14,9 @@
 		 *
 		 * @see CustomFieldValue
 		 */
-		function CustomFieldCheckboxValue( $fieldId, $fieldValue, $fieldName, $fieldType, $fieldDescription, $articleId, $blogId, $id = -1 )
+		function CustomFieldCheckboxValue( $fieldId, $fieldValue, $articleId, $blogId, $id = -1 )
 		{
-			$this->CustomFieldValue( $fieldId, $fieldValue, $fieldName, $fieldType, $fieldDescription, $articleId, $blogId, $id );
+			$this->CustomFieldValue( $fieldId, $fieldValue, $articleId, $blogId, $id );
 			
 			$this->setValue( $fieldValue );
 		}

Modified: plog/trunk/class/dao/customfields/customfielddatevalue.class.php
===================================================================
--- plog/trunk/class/dao/customfields/customfielddatevalue.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/customfields/customfielddatevalue.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -16,9 +16,9 @@
 		 *
 		 * @see CustomFieldValue
 		 */
-		function CustomFieldDateValue( $fieldId, $fieldValue, $fieldName, $fieldType, $fieldDescription, $articleId, $blogId, $id = -1 )
+		function CustomFieldDateValue( $fieldId, $fieldValue, $articleId, $blogId, $id = -1 )
 		{
-			$this->CustomFieldValue( $fieldId, $fieldValue, $fieldName, $fieldType, $fieldDescription, $articleId, $blogId, $id );
+			$this->CustomFieldValue( $fieldId, $fieldValue, $articleId, $blogId, $id );
 			
 			$this->setValue( $fieldValue );
 		}

Modified: plog/trunk/class/dao/customfields/customfields.class.php
===================================================================
--- plog/trunk/class/dao/customfields/customfields.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/customfields/customfields.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -15,6 +15,10 @@
 	define( "CUSTOM_FIELD_DATE", 4 );
 	define( "CUSTOM_FIELD_LIST", 5 );
 	define( "CUSTOM_FIELD_MULTILIST", 6 );
+	
+	define( "CACHE_CUSTOMFIELDS", "customfields" );
+	define( "CACHE_CUSTOMFIELDS_BLOG", "customfields_blog" );
+	define( "CACHE_CUSTOMFIELDS_BY_NAME", "customfields_name" );	
 
 	/**
      * Model for the custom fields
@@ -25,6 +29,7 @@
 		function CustomFields()
 		{
 			$this->Model();
+			$this->table = $this->getPrefix()."custom_fields_definition";
 		}
 		
 		/**
@@ -35,19 +40,7 @@
 		 */
 		function getCustomField( $id )
 		{
-			$query = "SELECT * FROM ".$this->getPrefix()."custom_fields_definition
-			          WHERE id = $id
-					  ORDER BY date ASC";
-					  
-			$result = $this->Execute( $query );
-			
-			if( !$result )
-				return false;
-				
-			if( $result->RowCount() == 0 )
-				return false;
-			else
-				return $this->_fillCustomFieldInformation( $result->FetchRow());
+			return( $this->get( "id", $id, CACHE_CUSTOMFIELDS ));
 		}
 
 		/**
@@ -59,17 +52,18 @@
 		 */		
 		function getCustomFieldByName( $blogId, $fieldName )
 		{
-			$query = "SELECT * FROM ".$this->getPrefix()."custom_fields_definition
-			          WHERE field_name = '".$fieldName."' AND blog_id = $blogId";
-					  
-			$result = $this->Execute( $query );
-			
-			if( !$result )
+			$blogFields = $this->getMany( "blog_id", 
+			                              $blogId, 
+			                              CACHE_CUSTOMFIELDS_BLOG,
+			                              Array( CACHE_CUSTOMFIELDS => "getId" ));
+			if( !$blogFields )
 				return false;
-			if( $result->RowCount() == 0 )
-				return false;
-				
-			return $this->_fillCustomFieldInformation( $result->FetchRow());					  
+			foreach( $blogFields as $field ) {
+				if( $field->getName() == $fieldName ) {
+					// we can return right away, no need to bother...
+					return( $field );
+				}
+			}
 		}
 		
 		/**
@@ -85,26 +79,29 @@
 		 */
 		function getBlogCustomFields( $blogId, $includeHidden = true, $page = -1, $itemsPerPage = 15 )
 		{
-
-			$query = "SELECT * FROM ".$this->getPrefix()."custom_fields_definition
-			          WHERE blog_id = $blogId";
-			if( !$includeHidden )
-				$query .= " AND hidden = 0 ";
-			$query .= " ORDER BY date ASC $limits";
-					  
-			$result = $this->Execute( $query, $page, $itemsPerPage );
-			
-			$fields = Array();			
-			
-			if( !$result )
-				return $fields;
-			
-			while( $row = $result->FetchRow()) {
-				$field = $this->_fillCustomFieldInformation( $row );
-				$fields[$field->getName()] = $field;
+			$blogFields = $this->getMany( "blog_id",
+			                              $blogId,
+			                              CACHE_CUSTOMFIELDS_BLOG,
+			                              Array( CACHE_CUSTOMFIELDS => "getId" ),
+			                              $page, 
+			                              $itemsPerPage );
+			                              
+			if( !$blogFields )
+				return( Array());
+			                          
+			// if we have to include the hidden fields, we can return the whole array as 
+			// those are already there
+			if( $includeHidden )
+				return( $blogFields );
+			                          
+			// if not, filter out the non-hidden
+			$result = Array();
+			foreach( $blogFields as $field ) {
+				if( !$field->isHidden())
+					$result[] = $field;
 			}
-		
-			return $fields;
+			
+			return( $result );
 		}
 
 		/**
@@ -115,30 +112,10 @@
 		 */
 		function getNumBlogCustomFields( $blogId, $includeHidden = true )
 		{
-			$prefix = $this->getPrefix();
-			$table  = "{$prefix}custom_fields_definition";
-			$cond = "blog_id = '".Db::qstr($blogId)."'";
-			if( !$includeHidden )
-				$cond .=  " AND hidden = 0";			
-			
-			return( $this->getNumItems( $table, $cond ));
+			return( count( $this->getBlogCustomFields( $blogId, $includeHidden )));
 		}
 		
 		/**
-		 * returns true if the given field already exists in the database
-		 *
-		 * @param fieldName
-		 * @param blogId
-		 * @return True if the field already exists or false otherwise
-		 */
-		function fieldExists( $fieldName, $blogId )
-		{
-			$field = $this->getCustomFieldByName( $blogId, $fieldName );
-			
-			return( $field != false );
-		}
-		
-		/**
 		 * adds a custom field to the database
 		 *
 		 * @param field A CustomField object
@@ -146,25 +123,17 @@
 		 */
 		function addCustomField( &$field )
 		{		
-			if( $this->fieldExists( $field->getName(), $field->getBlogId()))
+			// does the field already exist?
+			$existingField = $this->getCustomFieldByName( $field->getBlogId(), $field->getName());
+			if( $existingField ) // it already exists, we cannot add it!
 				return false;
-		
-			$query = "INSERT INTO ".$this->getPrefix()."custom_fields_definition
-			          (field_name, field_description, field_type, blog_id, searchable, hidden) VALUES(
-					  '".Db::qstr($field->getName())."','".Db::qstr($field->getDescription()).
-					  "', ".$field->getType().", ".$field->getBlogId().", ".$field->isSearchable().
-					  ", ".$field->isHidden().");";
-					  
-			$result = $this->Execute( $query );
-			
-			if( !$result ) 
-				return false;
 				
-			$fieldId = $this->_db->Insert_ID();
-			
-			$field->setId( $fieldId );
-			
-			return( $fieldId );
+			if( $result = $this->add( $field )) {
+				// clean the caches
+				$this->_cache->removeData( $field->getId(), CACHE_CUSTOMFIELDS );
+				$this->_cache->removeData( $field->getBlogId(), CACHE_CUSTOMFIELDS_BLOG );
+			}
+			return( $result );
 		}
 		
 		/**
@@ -179,14 +148,18 @@
 		 */
 		function removeCustomField( $id, $deleteValues = true )
 		{
-			$query = "DELETE FROM ".$this->getPrefix()."custom_fields_definition
-			          WHERE id = $id";
+			$field = $this->getCustomField( $id );
 			
-			$result = $this->Execute( $query );
+			if( !$field )
+				return false;
 			
-			if( !$result )
+			if( !$this->delete( "id", $id ));
 				return false;
 				
+			// clean the caches
+			$this->_cache->removeData( $field->getId(), CACHE_CUSTOMFIELDS );
+			$this->_cache->removeData( $field->getBlogId(), CACHE_CUSTOMFIELDS_BLOG );
+				
 			if( !$deleteValues )
 				return true;
 			
@@ -203,23 +176,18 @@
 		 */
 		function updateCustomField( $field )
 		{
-			$query = "UPDATE ".$this->getPrefix()."custom_fields_definition
-			          SET field_name = '".Db::qstr($field->getName())."',
-					  field_description = '".Db::qstr($field->getDescription())."',
-					  field_type = ".Db::qstr($field->getType()).",
-					  date = date,
-					  hidden = ".$field->isHidden()."
-					  WHERE id = ".$field->getId();
-
-			$result = $this->Execute( $query );
-			
-			return $result;
+			if( ($result = $this->update( $field ))) {
+				// clean the caches
+				$this->_cache->removeData( $field->getId(), CACHE_CUSTOMFIELDS );
+				$this->_cache->removeData( $field->getBlogId(), CACHE_CUSTOMFIELDS_BLOG );
+			}
+			return( $result );
 		}
 		
 		/**
 		 * @private
 		 */
-		function _fillCustomFieldInformation( $row )
+		function mapRow( $row )
 		{
 			$field = new CustomField( $row["field_name"],
 			                          $row["field_description"],

Modified: plog/trunk/class/dao/customfields/customfieldsvalues.class.php
===================================================================
--- plog/trunk/class/dao/customfields/customfieldsvalues.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/customfields/customfieldsvalues.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -1,9 +1,11 @@
 <?php
 
     include_once( PLOG_CLASS_PATH."class/dao/model.class.php" );
-    include_once( PLOG_CLASS_PATH."class/data/textfilter.class.php" );
     include_once( PLOG_CLASS_PATH."class/dao/customfields/customfields.class.php" );
     include_once( PLOG_CLASS_PATH."class/dao/customfields/customfieldvaluefactory.class.php" );        
+    
+    define( "CACHE_CUSTOMFIELDVALUES", "customfieldvalues" );    
+    define( "CACHE_CUSTOMFIELDVALUES_ARTICLE", "customfieldvalues_article" );
 
     /**
      * Model for the values given to certain custom fields
@@ -16,30 +18,16 @@
         function CustomFieldsValues()
         {
             $this->Model();
+            $this->table = $this->getPrefix()."custom_fields_values";
         }
         
         /**
-         * gets the value associated to the custom field with the given id
-         *
-         * @param id The id of the custom field value
+         * @param id
          * @return A CustomFieldValue object
          */
         function getCustomFieldValue( $id )
         {
-            require_once( PLOG_CLASS_PATH . 'class/database/db.class.php' );
-
-            $query = Db::buildSelectQuery( CUSTOMFIELD_VALUES,
-                                           array(),
-                                           'id',
-                                           $id,
-                                           'date' );
-                      
-            $result = $this->Execute( $query );
-            
-            if( !$result )
-                return false;
-            else
-                return $this->_fillCustomFieldInformation( $result->FetchRow());
+        	return( $this->get( "id", $id, CACHE_CUSTOMFIELDVALUES ));
         }
         
         /**
@@ -53,23 +41,13 @@
          */
         function getArticleCustomFieldsValues( $articleId, $blogId, $includeHidden = true )
         {                   
-            //
-            // it's quite a big query and has a 'right outer join', but the whole point is that
-            // we want to obtain as many rows as fields we have available. If there is no value
-            // for this article for one of the fields, we still want to get a row with the name
-            // of the field, its type and so on, with 'null' values where there is no value.
-            //
             $prefix = $this->getPrefix();
             $query = "SELECT v.id AS id, d.id AS field_id, v.field_value AS field_value, 
                              d.field_name AS field_name, d.field_type AS field_type, 
                              d.field_description AS field_description 
                              FROM {$prefix}custom_fields_values v 
                              RIGHT OUTER JOIN {$prefix}custom_fields_definition d 
-                             ON v.article_id = $articleId AND v.field_id = d.id
-                             WHERE d.blog_id = '".Db::qstr($blogId)."'";
-            if( !$includeHidden )
-                $query .= " AND d.hidden = 0 ";
-            $query .= " ORDER BY date ASC";
+                             ON v.article_id = $articleId AND v.field_id = d.id";
                       
             $result = $this->Execute( $query );
             
@@ -80,78 +58,14 @@
                 return $fields;
             
             while( $row = $result->FetchRow()) {
-                $field = $this->_fillCustomFieldValueInformation( $row );
+                $field = $this->mapRow( $row );
                 $fields[$field->getName()] = $field;
             }
         
             return $fields;
         }
-        
+
         /**
-         * @private
-         * @see getArticleCustomFieldsValues
-         */
-        function getArticleCustomFieldsValuesByIds( $articleIds, $blogId, $includeHidden = true )
-        {                   
-            //
-            // it's quite a big query and has a 'right outer join', but the whole point is that
-            // we want to obtain as many rows as fields we have available. If there is no value
-            // for this article for one of the fields, we still want to get a row with the name
-            // of the field, its type and so on, with 'null' values where there is no value.
-            //
-            $prefix = $this->getPrefix();
-            $query = "SELECT v.article_id as article_id, v.id AS id, d.id AS field_id, v.field_value AS field_value, 
-                             d.field_name AS field_name, d.field_type AS field_type, 
-                             d.field_description AS field_description 
-                             FROM {$prefix}custom_fields_values v 
-                             RIGHT OUTER JOIN {$prefix}custom_fields_definition d 
-                             ON v.article_id IN (".$articleIds.") AND v.field_id = d.id
-                             WHERE d.blog_id = '".Db::qstr($blogId)."'";
-            if( !$includeHidden )
-                $query .= " AND d.hidden = 0 ";
-            $query .= " ORDER BY date ASC";
-                      
-            $result = $this->Execute( $query );
-            
-            //$fields = Array();
-                        
-            // return empty array if no fields
-            if( !$result )
-                return $fields;
-            
-            while ($row = $result->FetchRow()) {
-                $lastArticleId=$row["article_id"];
-                $field = $this->_fillCustomFieldValueInformation( $row );
-                $fields[$lastArticleId][$field->getName()] = $field;
-            }
-        
-            return $fields;
-        }
-                
-        
-        /**
-         * @param fieldId
-         * @param articleId
-         * @return A CustomFieldValue object
-         */
-        function getArticleCustomFieldValue( $fieldId, $articleId )
-        {
-            $query = "SELECT * FROM ".$this->getPrefix()."custom_fields_values
-                      WHERE field_id = $fieldId AND article_id = $articleId
-                      ORDER BY date ASC";
-                      
-            $result = $this->Execute( $query );
-                        
-            if( !$result )
-                return false;
-            
-            $row = $result->FetchRow();
-            $fieldValue = $this->_fillCustomFieldValueInformation( $row );
-        
-            return $fieldValue;
-        }
-        
-        /**
          * adds a custom field value to the given article
          *
          * @param fieldId
@@ -162,18 +76,20 @@
          */
         function addCustomFieldValue( $fieldId, $fieldValue, $articleId, $blogId )
         {
-            $filter = new Textfilter();
-            $query = "INSERT INTO ".$this->getPrefix()."custom_fields_values
-                      (field_id, field_value, normalized_value, blog_id, article_id)
-                      VALUES (
-                      $fieldId, '".Db::qstr($fieldValue)."','".
-                      $filter->normalizeText(Db::qstr($fieldValue))."',
-                      $blogId, $articleId
-                      )";
-                      
-            $result = $this->Execute( $query );
-            
-            return $result;
+        	// create a bogus object, we don't really need a full CustomFieldValue object
+        	// but it makes it easier for us if we'd like to use Model::add()
+        	$value = new CustomFieldValue( $fieldId, 
+        	                               $fieldValue,
+        	                               '',  // doesn't matter
+        	                               -1,  // doesn't matter
+        	                               '', // doesn't matter
+        	                               $articleId,
+        	                               $blogId );
+			if( $result = $this->add( $value )) {
+				$this->_cache->removeData( $articleId, CACHE_CUSTOMFIELDVALUES_ARTICLE );
+			}
+			
+			return( $result );
         }
         
         
@@ -185,12 +101,15 @@
          */
         function removeCustomFieldValue( $id )
         {
-            $query = "DELETE FROM ".$this->getPrefix()."custom_fields_values
-                      WHERE id = $id";
-                      
-            $result = $this->Execute( $query );
-            
-            return $result;
+        	$field = $this->getCustomFieldValue( $id );
+        	if( !$field )
+        		return false;
+        		
+        	if( $result = $this->delete( "id", $id )) {
+        		$this->_cache->removeData( $id, CACHE_CUSTOMFIELDVALUES );
+        		$this->_cache->removeData( $field->getArticleId(), CACHE_CUSTOMFIELDVALUES_ARTICLE );
+        	}
+        	return( $result );
         }
         
         /**
@@ -201,14 +120,14 @@
          */
         function removeCustomFieldValues( $fieldId )
         {
-            $query = "DELETE FROM ".$this->getPrefix()."custom_fields_values
-                      WHERE field_id = $fieldId";
-                      
-            $result = $this->Execute( $query );
-            
-            return $result;
-        }
+        	$result = $this->delete( "field_id", $fieldId );
 
+        	/**
+        	 * :TODO:
+        	 * clean the caches!!!!!!!
+        	 */        	
+        	return( $result );
+        }
         
         /**
          * Removes all the values associated to an article
@@ -218,23 +137,19 @@
          */
         function removeArticleCustomFields( $articleId )
         {
-            $query = "DELETE FROM ".$this->getPrefix()."custom_fields_values
-                      WHERE article_id = $articleId"; 
-                      
-            $result = $this->Execute( $query );
-            
-            return $result;
+        	$result = $this->delete( "article_id", $articleId );
+        	
+        	/**
+        	 * :TODO:
+        	 * clean the caches!!!!!!!
+        	 */        	
+        	return( $result );
         }
         
-        function updateCustomFieldValue( $fieldValue )
-        {
-        
-        }
-        
         /**
          * @private
          */
-        function _fillCustomFieldValueInformation( $row )
+        function mapRow( $row )
         {
             return CustomFieldValueFactory::getCustomFieldValueObject( $row );
         }

Modified: plog/trunk/class/dao/customfields/customfieldvalue.class.php
===================================================================
--- plog/trunk/class/dao/customfields/customfieldvalue.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/customfields/customfieldvalue.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -1,13 +1,13 @@
 <?php
 
-	include_once( PLOG_CLASS_PATH."class/dao/customfields/customfield.class.php" );
+	include_once( PLOG_CLASS_PATH."class/database/dbobject.class.php" );
 
 	/**
      * Defines a value assigned to a custom field
 	 *
 	 * \ingroup DAO
      */
-	class CustomFieldValue extends CustomField
+	class CustomFieldValue extends DbObject
 	{
 		var $_fieldId;
 		var $_fieldValue;
@@ -16,18 +16,39 @@
 		var $_articleId;
 		var $_field;
 	
-		function CustomFieldValue( $fieldId, $fieldValue, $fieldName, $fieldType, $fieldDescription, $articleId, $blogId, $id = -1 )
+		function CustomFieldValue( $fieldId, $fieldValue, $articleId, $blogId, $id = -1 )
 		{
-			// call the parent constructor
-			$this->CustomField( $fieldName, $fieldDescription, $fieldType, $blogId, false );
+			// constructor
+			$this->DbObject();			
 			// and save some other values
 			$this->_fieldId = $fieldId;
 			if( $fieldValue == null ) $fieldValue = "";
 			$this->_fieldValue = $fieldValue;
 			$this->_articleId = $articleId;
 			$this->_id = $id;
+			$this->_customField = null;
+			
+			$this->_fields = Array(
+			   "field_id" => "getFieldId",
+			   "field_value" => "getValue",
+			   "normalized_value" => "getNormalizedValue",
+			   "blog_id" => "getBlogId",
+			   "article_id" => "getArticleId"
+			);
 		}
 		
+		/**
+		 * @private
+		 */
+		function _loadFieldDefinition()
+		{
+			if( $this->_customField == null ) {
+				include_once( PLOG_CLASS_PATH."class/dao/customfields/customfields.class.php" );
+				$customFields = new CustomFields();
+				$this->_customField = $customFields->getCustomField( $this->_fieldId );
+			}
+		}
+		
 		function getBlogId()
 		{
 			return $this->_blogId;
@@ -38,6 +59,11 @@
 			return $this->_id;
 		}
 		
+		function setId( $id )
+		{
+			$this->_id = $id;
+		}
+		
 		function getFieldId()
 		{
 			return $this->_fieldId;
@@ -57,5 +83,35 @@
 		{
 			$this->_fieldValue = $value;
 		}
+		
+		function getNormalizedValue()
+		{
+			include_once( PLOG_CLASS_PATH."class/data/textfilter.class.php" );
+            $filter = new Textfilter();
+            return( $filter->normalizeText($this->getValue()));
+		}
+		
+		function getType()
+		{
+			$this->_loadFieldDefition();
+			return( $this->_customField->getType());
+		}
+		
+		function getDescription()
+		{
+			$this->_loadFieldDefinition();
+			return( $this->_customField->getDescription());
+		}
+		
+		function getName()
+		{
+			$this->_loadFieldDefinition();
+			return( $this->_customField->getName());			
+		}
+		
+		function getFieldDefinition()
+		{
+			return( $this->_customField );
+		}
 	}
 ?>
\ No newline at end of file

Modified: plog/trunk/class/dao/customfields/customfieldvaluefactory.class.php
===================================================================
--- plog/trunk/class/dao/customfields/customfieldvaluefactory.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/customfields/customfieldvaluefactory.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -55,9 +55,6 @@
 			$constructor = CustomFieldValueFactory::_findConstructorClass( (int)$row["field_type"] );
 			$value = new $constructor( $row["field_id"],
 			                           $row["field_value"],
-									   $row["field_name"],
-									   $row["field_type"],
-									   $row["field_description"],
 									   $row["article_id"],
 					   			       $row["blog_id"],
  									   $row["id"] );

Modified: plog/trunk/class/dao/model.class.php
===================================================================
--- plog/trunk/class/dao/model.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/model.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -155,8 +155,202 @@
         {
             return $this->_db->ErrorMsg();
         }
+        
+        function get( $field, $value, $cacheId, $caches = null )
+        {
+        	$dbObject = $this->_cache->getData( $value, $cacheId );
 
+        	if( !$dbObject ) {
+	        	$this->log->debug("get: $field:$value - cache = $cacheId" );
+	        	$query = "SELECT * FROM ".$this->table." WHERE {$field} = '".Db::qstr( $value )."'";
+	        	
+	        	$result = $this->Execute( $query );
+	        	
+	        	if( !$result )
+	        		return false;
+	        	
+	        	if( $result->RowCount() == 0 )
+	        		return false;
+	        		
+	        	$row = $result->FetchRow();
+	        	
+	        	$dbObject = $this->mapRow( $row );
+	        	
+	        	$this->_cache->setData( $value, $cacheId, $dbObject );
+	        	if( $caches ) {
+	        		foreach( $caches as $cache => $getter ) {
+	        			$this->_cache->setData( $dbObject->$getter(), $cache, $dbObject );
+	        		}
+	        	}
+	        }
+	        
+	        return( $dbObject );
+        	
+        }
+        
         /**
+         * given several conditions, concatenates them with an "AND" operator. If one of the
+         * items of the array is an empty string, the condition will not be used
+         *
+         * @deprecated use Db Class build(Select|Insert|...)Query instead
+         * @param conds
+         * @return a string
+         */
+        function buildWhereCondition( $conds = Array(), $useWhere = true )
+        {
+            $valid = 0;
+            $where = "";
+            
+            foreach( $conds as $cond ) {
+                $this->log->debug( "Processing condition = ".$cond );
+                if( $cond ) {
+                    // only if the condition is not empty...
+                    
+                    if( $valid > 0 )
+                        $where .= " AND ";
+                    
+                    // append the condition
+                    $where .= "$cond";
+                    
+                    // we've got a valid condition
+                    $valid++;
+                }
+            }
+            
+            if( $valid > 0 && $useWhere )
+                $where = "WHERE $where";
+                
+            return( $where );
+        }        
+        
+        function getAll( $key, $cacheId, $itemCaches = null, $page = -1, $itemsPerPage = DEFAULT_ITEMS_PER_PAGE )
+        {
+        	return( $this->getMany( $key, null, $cacheId, $itemCaches, $page, $itemsPerPage ));
+        }      
+        
+        function getMany( $key, $value, $cacheId, $itemCaches = null, $page = -1, $itemsPerPage = DEFAULT_ITEMS_PER_PAGE )
+        {
+        	$dbObjects = $this->_cache->getData( $value, $cacheId );
+        	if( !$dbObjects ) {
+        		$this->log->debug("getMany: $key:$value - cache = $cacheId -- cache miss!");
+        		$query = "SELECT * FROM ".$this->table;	
+        		if( $value )
+        			$query .= " WHERE {$key} = '".Db::qstr($value)."'";
+        		$this->log->debug("query = $query");
+        			
+	        	$result = $this->Execute( $query );
+	        	
+	        	if( !$result )
+	        		return false;
+	        	
+	        	if( $result->RowCount() == 0 )
+	        		return false;
+	        		
+	        	$dbObjects = Array();
+	        	while( $row = $result->FetchRow()) {        	
+		        	$dbObject = $this->mapRow( $row );
+		        	$dbObjects[] = $dbObject;
+		        	if( $itemCaches ) {
+		        		foreach( $itemCaches as $cache => $getter ) {
+	        				$this->_cache->setData( $dbObject->$getter(), $cache, $dbObject );
+	        			}
+	        		}
+		        }
+	        	
+	        	$this->_cache->setData( $value, $cacheId, $dbObjects );
+        	}
+        	
+        	if( $page > -1 ) {
+        		// return only a subset of the items
+				$start = (($page - 1) * $itemsPerPage );
+                $dbObjects = array_slice( $dbObjects, $start, $itemsPerPage );        		
+        	}
+        	
+        	return( $dbObjects );
+        }
+        
+        
+        function add( &$dbObject, $cacheId = null ) 
+        {
+        	$fields = $dbObject->getFieldGetters();
+        	$fieldsString = '';
+        	$fieldsValuesString = '';
+
+            $sql    = "INSERT INTO `".$this->table."` (";
+
+            foreach ($fields as $field => $getter)
+            {
+            	if( $field != "id" ) {
+            		// let's ignore the primary key!
+	            	$fieldsString .= $field.", ";
+            	
+        	    	$value = $dbObject->$getter();
+            		if( is_array( $value )) $value = serialize( $value );            	
+            		elseif( is_object( $value )) $value = serialize( $value );
+            		elseif( strtolower(get_class( $value )) == "timestamp" )
+            			$value = $value->getTimestamp();
+	                $value = Db::qstr($value);
+    	            $fieldValuesString .= "'" . $value . "', ";
+    	        }
+            }
+
+            $sql .= substr($fieldsString, 0, -2) . ") VALUES (".substr($fieldValuesString, 0, -2).")";            
+            
+            $result = $this->Execute( $sql );            
+            if( !$result )
+            	return false;
+            	
+            $dbObject->setId( $this->_db->Insert_ID());            
+            
+            if( $cacheId ) {
+            	foreach( $cacheId as $cache => $getter ) {
+            		$this->_cache->setData( $dbObject->{$getter}(), $cache, $dbObject );
+            	}
+            }           
+
+			return( $dbObject->getId());
+        }
+        
+        function update( &$dbObject )
+        {
+        	include_once( PLOG_CLASS_PATH."class/database/db.class.php" );
+        
+            $fields = $dbObject->getFieldGetters();
+            $sql    = "UPDATE `".$this->table."` SET ";
+
+            foreach ($fields as $field => $getter)
+            {
+            	$value = $dbObject->$getter();
+            	if( is_array( $value )) $value = serialize( $value );            	
+            	elseif( strtolower(get_class( $value )) == "timestamp" )
+            		$value = $value->getTimestamp();
+            	elseif( is_object( $value )) $value = serialize( $value );
+            	
+                $value = Db::qstr($value);
+                $sql  .= "`" . $field . "`='" . $value . "', ";
+            }
+
+            $sql = substr($sql, 0, -2) . " WHERE id = '".Db::qstr($dbObject->getId())."'";            
+            
+            $result = $this->Execute( $sql );            
+            
+            if( !$result )
+            	return false;
+
+            if( $this->_db->Affected_Rows() == 0 )
+            	return false;
+            else
+            	return true;
+        }
+        
+        function delete( $field, $value )
+        {
+			$query = "DELETE FROM ".$this->table." WHERE {$field} = '{$value}'";			
+			$result = $this->Execute( $query );								
+			return( $this->_db->Affected_Rows());
+        }
+
+        /**
          * returns the current database prefix
          *
          * @deprecated the prefix should be set/added by the Db Classes, not by the model
@@ -222,41 +416,6 @@
         function buildSearchCondition( $searchTerms )
         {
             return( "" );
-        }
-        
-        /**
-         * given several conditions, concatenates them with an "AND" operator. If one of the
-         * items of the array is an empty string, the condition will not be used
-         *
-         * @deprecated use Db Class build(Select|Insert|...)Query instead
-         * @param conds
-         * @return a string
-         */
-        function buildWhereCondition( $conds = Array(), $useWhere = true )
-        {
-            $valid = 0;
-            $where = "";
-            
-            foreach( $conds as $cond ) {
-                $this->log->debug( "Processing condition = ".$cond );
-                if( $cond ) {
-                    // only if the condition is not empty...
-                    
-                    if( $valid > 0 )
-                        $where .= " AND ";
-                    
-                    // append the condition
-                    $where .= "$cond";
-                    
-                    // we've got a valid condition
-                    $valid++;
-                }
-            }
-            
-            if( $valid > 0 && $useWhere )
-                $where = "WHERE $where";
-                
-            return( $where );
-        }
+        }        
     }
-?>
+?>
\ No newline at end of file

Modified: plog/trunk/class/dao/mylink.class.php
===================================================================
--- plog/trunk/class/dao/mylink.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/mylink.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -44,6 +44,18 @@
 			$this->_rssFeed = $rssFeed;
             $this->setDate( $date );
 			$this->setProperties( $properties );
+			
+			$this->_pk = "pk";
+			$this->_fields = Array(
+			   "category_id" => "getCategoryId",
+			   "url" => "getUrl",
+			   "name" => "getName",
+			   "description" => "getDescription",
+			   "blog_id" => "getBlogId",
+			   "rss_feed" => "getRssFeed",
+			   "date" => "getDate",
+			   "properties" => "getProperties"
+			);
 		}
 
         /**
@@ -163,6 +175,17 @@
             $this->_timestamp = new Timestamp( $newDate );
         }
         
+        function getMyLinkCategory()
+        {        
+        	if( !$this->_category ) {
+        		include_once( PLOG_CLASS_PATH."class/dao/mylinkscategories.class.php" );
+        		$categories = new MyLinksCategories();
+        		$this->_category = $categories->getMyLinksCategory( $this->getCategoryId());
+        	}        	
+        	
+        	return( $this->_category );
+        }
+        
         function getDate()
         {
             return $this->_date;

Modified: plog/trunk/class/dao/mylinks.class.php
===================================================================
--- plog/trunk/class/dao/mylinks.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/mylinks.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -2,8 +2,10 @@
 
 	include_once( PLOG_CLASS_PATH."class/dao/model.class.php" );
     include_once( PLOG_CLASS_PATH."class/dao/mylink.class.php" );
-    include_once( PLOG_CLASS_PATH."class/dao/bloglinks.class.php" );
 	include_once( PLOG_CLASS_PATH."class/dao/mylinkscategories.class.php" );
+	
+	define( "CACHE_MYLINKS_ALL", "cache_mylinks_all" );
+	define( "CACHE_MYLINKS", "cache_mylinks" );
 
     /**
 	 * \ingroup DAO
@@ -12,6 +14,13 @@
      */
     class MyLinks extends Model 
 	{
+	
+		function MyLinks()
+		{
+			$this->Model();
+		
+			$this->table = $this->getPrefix()."mylinks";
+		}
 
         /**
 		 * Retrieves the links of the given blog.
@@ -23,43 +32,26 @@
 		 */
 		function getLinks( $blogId, $categoryId = 0, $page = -1, $itemsPerPage = 15 )
 		{
-            $blogLinks = $this->getBlogLinks( $blogId );
+			$blogLinks = $this->getMany( "blog_id", 
+			                             $blogId, 
+			                             CACHE_MYLINKS_ALL,
+			                             Array( CACHE_MYLINKS => "getId" ),
+			                             $page,
+			                             $itemsPerPage );			                             
+			    
+			$result = Array();
+			if( $blogLinks && $categoryId > 0 ) {
+				foreach( $blogLinks as $link ) {
+					if( $link->getCategoryId() == $categoryId )
+						$result[] = $link;
+				}
+			}
+			else
+				$result = $blogLinks;			
 
-            $myLinks = $blogLinks->getLinksForCategory( $categoryId );
-
-            // check if we're using any paging
-            if( $page > -1 ) {
-                $start = (($page - 1) * $itemsPerPage);
-                $myLinks = array_slice( $myLinks, $start, $itemsPerPage );
-            }
-
-			return $myLinks;
+			return( $result );
 		}
 
-        function getBlogLinks( $blogId )
-        {
-            $blogLinks = $this->_cache->getData( $blogId, CACHE_BLOGLINKS );
-
-            if( !$blogLinks ) {
-                $query = "SELECT * FROM ".$this->getPrefix()."mylinks WHERE blog_id = '".Db::qstr($blogId)."' ORDER BY id;";
-
-                $result = $this->Execute( $query );
-
-                if( !$result )
-                    return false;
-
-                $links = Array();
-
-                while( $row = $result->FetchRow()) {
-                    $link = $this->_fillMyLinkInformation( $row );
-                    array_push( $links, $link );
-                }
-                $blogLinks = new BlogLinks( $blogId, $links );
-                $this->_cache->setData( $blogId, CACHE_BLOGLINKS, $blogLinks );
-            }
-            return $blogLinks;
-        }
-		
 		/**
 		 * returns how many links a blog has
 		 *
@@ -69,9 +61,7 @@
 		 */
 		function getNumLinks( $blogId, $categoryId = 0 )
 		{
-            $blogLinks = $this->getBlogLinks( $blogId );
-            $categoryLinks = $blogLinks->getLinksForCategory( $categoryId );
-            return count( $categoryLinks );
+			return( count( $this->getLinks( $blogId, $categoryId )));
 		}		
 
         /**
@@ -81,25 +71,24 @@
          * @param blogId The blog id
          * @return True if successful or false otherwise.
          */
-        function addMyLink( $myLink, $blogId )
+        function addMyLink( &$myLink )
         {
-        	$query = "INSERT INTO ".$this->getPrefix()."mylinks (name,url,description,category_id,blog_id,properties,rss_feed) 
-			          VALUES ('".Db::qstr($myLink->getName())."','".
-					  Db::qstr($myLink->getUrl())."','".
-					  Db::qstr($myLink->getDescription())."',".
-					  $myLink->getCategoryId().",".
-					  $blogId.",'".
-					  Db::qstr(serialize($myLink->getProperties()))."','".
-					  Db::qstr($myLink->getRssFeed())."');";
-
-            $result = $this->Execute( $query );
+        	$result = $this->add( $myLink );
 			
 			if( $result ) {
+				// clean the cache
+				/**
+				 * :TODO:
+				 * this doesn't seem to work very well!!!
+				 */
+                $this->_cache->removeData( $myLink->getId(), CACHE_MYLINKS );
+                $this->_cache->removeData( "all", CACHE_MYLINKS_ALL );			
 				// mark the corresponding link categories as modified now
 				$linkCategories = new MyLinksCategories();
-				$linkCategories->updateCategoryModificationDate( $myLink->getCategoryId());
-
-                $this->_cache->removeData( $blogId, CACHE_BLOGLINKS );
+				$category = $myLink->getMyLinkCategory();
+				$category->setLastModification( Timestamp::getNowTimestamp());
+				$category->setNumLinks( $category->getNumLinks() + 1 );
+				$linkCategories->updateMyLinksCategory( $category );
 			}
 
             return $result;
@@ -114,19 +103,20 @@
          */
         function deleteMyLink( $linkId, $blogId )
         {
-        	$query = "DELETE FROM ".$this->getPrefix()."mylinks WHERE id = '".Db::qstr($linkId)."' AND blog_id = ".$blogId.";";
-
-            $result = $this->Execute( $query );
-
-			/*if( $result ) {
-				// mark the corresponding link categories as modified now
+        	$link = $this->getMyLink( $linkId, $blogId );
+        	if( $link ) {
+        		$this->delete( "id", $linkId );
+	            $this->_cache->removeData( $blogId, CACHE_MYLINKS_ALL );
+	            $this->_cache->removeData( $linkId, CACHE_MYLINKS );
 				$linkCategories = new MyLinksCategories();
-				$linkCategories->updateCategoryModificationDate( $myLink->getCategoryId());
-			}*/
-
-            $this->_cache->removeData( $blogId, CACHE_BLOGLINKS );
-
-            return $result;
+				$linkCategory = $link->getMyLinkCategory();
+				$linkCategory->setLastModification( Timestamp::getNowTimestamp());
+				$linkCategory->setNumLinks( $linkCategory->getNumLinks() - 1 );				
+				$linkCategories->updateMyLinksCategory( $linkCategory );
+				return( true );
+        	}
+        	else
+        		return false;
         }
 
         /**
@@ -136,13 +126,11 @@
          */
         function deleteBlogMyLinks( $blogId )
         {
-        	$query = "DELETE FROM ".$this->getPrefix()."mylinks WHERE blog_id = $blogId";
-
-			$result = $this->Execute( $query );
-
-            $this->_cache->removeData( $blogId, CACHE_BLOGLINKS );
-
-            return $result;
+        	if( $this->delete( "blog_id", $blogId )) {
+	        	return( $this->_cache->removeData( $blogId, CACHE_MYLINKS_ALL ));
+        	}
+        	else
+        		return false;
         }        
 
         /**
@@ -154,29 +142,17 @@
          */
         function getMyLink( $linkId, $blogId = -1 )
         {
-            $blogLink = $this->_cache->getData( $linkId, CACHE_MYLINKS );
+        	$blogLink = $this->get( "id", $linkId, CACHE_MYLINKS );
+        	if( !$blogLink )
+        		return false;
 
-            if ( !$blogLink  || ( $blogLink->getBlogId() != $blogId && $blogId != -1 ) ) {
-                $query = "SELECT * FROM ".$this->getPrefix()."mylinks WHERE id = ".Db::qstr($linkId);
-                if( $blogId > 0 )
-                    $query .= " AND blog_id = '".$blogId."';";
-
-                $result = $this->Execute( $query );
-
-                if( !$result )
-                    return false;
-
-                if( $result->RecordCount() == 0 )
-                    return false;
-
-                $row = $result->FetchRow();
-                $blogLink = $this->_fillMyLinkInformation( $row );
-
-                // update the cache
-                $this->_cache->setData( $linkId, CACHE_MYLINKS, $blogLink );
-            }
-
-            return $blogLink;
+			if( $blogId == -1 )
+				return $blogLink;
+				
+			if( $blogLink->getBlogId() == $blogId )
+				return $blogLink;
+			else
+				return false;
         }
 
         /**
@@ -185,38 +161,26 @@
          * @param myLink A MyLink object with the information we'd like to update.
          * @return True if successful or false otherwise.
          */
-        function updateMyLink( $myLink )
+        function updateMyLink( &$myLink )
         {
-        	$query = "UPDATE ".$this->getPrefix()."mylinks SET
-                      name = '".Db::qstr($myLink->getName())."',
-                      description = '".Db::qstr($myLink->getDescription())."',
-                      url = '".Db::qstr($myLink->getUrl())."',
-                      category_id = ".$myLink->getCategoryId().",
-                      date = date,
-					  properties = '".Db::qstr(serialize($myLink->getProperties()))."',
-					  rss_feed = '".Db::qstr($myLink->getRssFeed())."'
-                      WHERE id = ".$myLink->getId()." AND blog_id = ".$myLink->getBlogId().";";
+        	$result = $this->update( $myLink );
 
-            $result = $this->Execute( $query );
-
-            if( !$result )
+            if( !$result ) {
             	return false;
-            else {
-                // mark the corresponding link categories as modified now
-                $linkCategories = new MyLinksCategories();
-                $linkCategories->updateCategoryModificationDate( $myLink->getCategoryId());
+            }
 
-                $this->_cache->removeData( $myLink->getBlogId(), CACHE_BLOGLINKS );
+            // mark the corresponding link categories as modified now
+            $linkCategories = new MyLinksCategories();
+            $linkCategories->updateCategoryModificationDate( $myLink->getCategoryId());
+
+            $this->_cache->removeData( $myLink->getId(), CACHE_MYLINKS );
+            $this->_cache->removeData( "all", CACHE_MYLINKS_ALL );
 			
-            	return true;
-			}
+          	return true;
         }
-		
-		/**
-		 * @private
-		 */
-		function _fillMyLinkInformation( $row )
-		{
+        
+        function mapRow( $row )
+        {
             $blogLink = new MyLink( $row["name"], $row["description"], 
 			                        $row["url"], $row["blog_id"], $row["category_id"], 
 									$row["date"], $row["rss_feed"],
@@ -224,6 +188,7 @@
 									$row["id"] );
 									
 			return $blogLink;
-		}
+
+        }
     }
-?>
+?>
\ No newline at end of file

Modified: plog/trunk/class/dao/mylinkscategories.class.php
===================================================================
--- plog/trunk/class/dao/mylinkscategories.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/mylinkscategories.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -11,6 +11,12 @@
 	define( "MYLINKS_CATEGORIES_LESS_LINKS_FIRST", 4 );
 	define( "MYLINKS_CATEGORIES_LAST_UPDATED_FIRST", 5 );
 	define( "MYLINKS_CATEGORIES_LAST_UPDATED_LAST", 6 );
+	
+	/**
+	 * cache ids
+	 */
+	define( "CACHE_MYLINKCATEGORIES_ALL", "mylinks_categories_all" );
+	define( "CACHE_MYLINKCATEGORIES", "mylinks_categories" );
 
     /**
 	 * \ingroup DAO
@@ -19,6 +25,13 @@
      */
 	class MyLinksCategories extends Model 
 	{
+	
+		function MyLinksCategories()
+		{
+			$this->Model();
+			
+			$this->table = $this->getPrefix()."mylinks_categories";
+		}
 
         /**
          * Returns the categories for my_links for a given blog
@@ -28,22 +41,16 @@
 		 * @param page
 		 * @param itemsPerPage
          */
-        function getMyLinksCategories( $blogId, 
+        function getMyLinksCategories( $blogId,
                                        $order = MYLINKS_CATEGORIES_NO_ORDER, 
                                        $page = -1, 
                                        $itemsPerPage = DEFAULT_ITEMS_PER_PAGE )
         {
-			$prefix = $this->getPrefix();			
-			// basic query
-			$query = "SELECT c.id AS id, c.name AS name, c.blog_id AS blog_id, 
-							c.last_modification AS last_modification, c.properties AS properties, 
-							IF(l.id IS NULL, 0, COUNT(*)) AS num_links
-						FROM {$prefix}mylinks_categories c LEFT JOIN {$prefix}mylinks l
-						ON l.blog_id = c.blog_id AND l.category_id = c.id 
-						WHERE c.blog_id= $blogId
-						GROUP BY c.id";
-			
-			if( $order == MYLINKS_CATEGORIES_ALPHABETICAL_ORDER ) {
+			/*
+			 * :TODO:
+			 * Implement sorting here!!!
+			 */
+			/*if( $order == MYLINKS_CATEGORIES_ALPHABETICAL_ORDER ) {
 				$query .= " ORDER BY c.name ASC";
 			}
 			elseif( $order == MYLINKS_CATEGORIES_REVERSE_ALPHABETICAL_ORDER ) {
@@ -60,35 +67,16 @@
 			}
 			elseif( $order == MYLINKS_CATEGORIES_LAST_UPDATED_LAST ) {
 				$query .= " ORDER BY c.last_modification ASC";			
-			}			
+			}*/			
 			
-			// execute the query
-            $result = $this->Execute( $query, $page, $itemsPerPage );
-
-            if( !$result )
-            	return Array();
-				
-			if( $result->RowCount() == 0 )
-				return Array();
-				
-            $myLinks = new MyLinks();
-            $blogLinks = $myLinks->getLinks( $blogId );
-
-            $myLinksCategories = Array();
-            while( $row = $result->fetchRow($result)) {
-				// configure the data for the category
-			   	$myLinksCategory = new MyLinksCategory( $row["name"], $row["blog_id"], $row["num_links"],
-													        unserialize($row["properties"]), $row["id"] );
-                $myLinksCategories[$myLinksCategory->getId()] = $myLinksCategory;
-            }
-			
-			// now assign the links to the correct category
-			foreach( $blogLinks as $blogLink ) {
-				if( $myLinksCategories[$blogLink->getCategoryId()] )
-					$myLinksCategories[$blogLink->getCategoryId()]->addLink( $blogLink );
-			}
-
-            return $myLinksCategories;
+            $blogCategories = $this->getMany( "blog_id", 
+                                             $blogId,
+                                             CACHE_MYLINKCATEGORIES_ALL, 
+                                             Array( CACHE_MYLINKCATEGORIES => "getId" ),
+                                             $page,
+                                             $itemsPerPage );
+                                             
+            return( $blogCategories );
         }
 
         /**
@@ -97,17 +85,13 @@
          * @param linkCategory A MyLinkCategory object with the information we need.
          * @return Returns true if successful or false otherwise.
          */
-        function addMyLinksCategory( $myLinksCategory )
+        function addMyLinksCategory( &$myLinksCategory )
         {
-        	$query = "INSERT INTO ".$this->getPrefix()."mylinks_categories (name, blog_id, properties) 
-			          VALUES ('".
-			          Db::qstr($myLinksCategory->getName())."', ".
-					  $myLinksCategory->getBlogId().", '".
-					  Db::qstr(serialize($myLinksCategory->getProperties()))."');";
-
-            $result = $this->Execute( $query );
-
-            return $result;
+        	if(( $result = $this->add( $myLinksCategory, Array( CACHE_MYLINKCATEGORIES => "getId" )))) {
+        		$this->_cache->removeData( "all", CACHE_MYLINKCATEGORIES_ALL );
+        	}
+        	
+        	return( $result );
         }
 
         /**
@@ -119,13 +103,15 @@
          */
         function deleteMyLinksCategory( $categoryId, $blogId )
         {
-        	$query = "DELETE FROM ".$this->getPrefix()."mylinks_categories 
-			          WHERE id = '".Db::qstr($categoryId)."' 
-					  AND blog_id = '".Db::qstr($blogId)."';";
-
-            $result = $this->Execute( $query );
-
-            return $result;
+        	$category = $this->getMyLinksCategory( $categoryId, $blogId );
+        	if( $category ) {
+        		if( $this->delete( "id", $categoryId )) {
+        			$this->_cache->removeData( $category->getId(), CACHE_MYLINKSCATEGORIES );
+        			$this->_cache->removeData( "all", CACHE_MYLINKSCATEGORIES_ALL );
+        		}
+        	}
+        	else
+        		return false;
         }
 
         /**
@@ -135,11 +121,12 @@
          */
         function deleteBlogMyLinksCategories( $blogId )
         {
-        	$query = "DELETE FROM ".$this->getPrefix()."mylinks_categories WHERE blog_id = $blogId";
-
-			$result = $this->Execute( $query );
-
-            return $result;
+        	/**
+        	 * :TODO:
+        	 *
+        	 * clean all the caches!
+        	 */
+        	return( $this->delete( "blog_id", $blogId ));
         }        
 
         /**
@@ -151,32 +138,10 @@
          */
         function getMyLinksCategory( $categoryId, $blogId = 0 )
         {
-			$prefix = $this->getPrefix();
-//			$query = "SELECT c.id AS id, c.name AS name, c.blog_id AS blog_id, 
-//							 c.last_modification AS last_modification, c.properties AS properties, 
-//							 COUNT(*) AS num_links 
-//					  FROM {$prefix}mylinks l, {$prefix}mylinks_categories c 
-//					  WHERE c.id = ".Db::qstr($categoryId)." AND l.category_id = c.id ";
-//
-//          if( $blogId > 0 )
-//          	$query .= " AND c.blog_id = ".Db::qstr($blogId)." AND l.blog_id = c.blog_id";
+        	$myLinksCategory = $this->get( "id", $categoryId, CACHE_MYLINKSCATEGORIES );
+        	if( $blogId > 0 && $myLinksCategory->getBlogId() != $blogId )
+        		return false;
 
-            $query = "SELECT c.id AS id, c.name AS name, c.blog_id AS blog_id, 
-                             c.last_modification AS last_modification, c.properties AS properties, 
-                             IF(l.id IS NULL, 0, COUNT(*)) AS num_links 
-                      FROM {$prefix}mylinks_categories c LEFT JOIN {$prefix}mylinks l ON l.blog_id = c.blog_id AND l.category_id = c.id
-                      WHERE c.id = ".Db::qstr($categoryId)." ";
-            
-			$query .= " GROUP BY c.id;";
-
-            $result = $this->Execute( $query );
-
-            if( !$result || $result->RecordCount() == 0 )
-            	return false;
-
-            $row = $result->FetchRow();
-            $myLinksCategory = $this->_fillMyLinksCategoryFromRow( $row );
-
             return $myLinksCategory;
         }
 
@@ -188,14 +153,12 @@
          */
         function updateMyLinksCategory( $category )
         {
-        	$query = "UPDATE ".$this->getPrefix()."mylinks_categories SET
-                      name = '".Db::qstr($category->getName())."',
-					  properties = '".Db::qstr(serialize($category->getProperties()))."'
-                      WHERE id = ".$category->getId()." AND blog_id = ".$category->getBlogId().";";
-
-            $result = $this->Execute( $query );
-
-            return $result;
+        	if( ($result = $this->update( $category ))) {
+        		$this->_cache->setData( $category->getId(), CACHE_MYLINKSCATEGORIES, $category );
+        		$this->_cache->removeData( "all", CACHE_MYLINKSCATEGORIES_ALL );
+        	}
+        	
+        	return( $result );
         }
 
 		/**
@@ -213,21 +176,6 @@
 			return( $this->getNumItems( $table, $cond ));		
 		}
 
-        /**
-         * Returns how many links are under the given category.
-         *
-         * @param categoryId the category identifier.
-         * @return The number of links under this category or 0 if none.
-         */
-        function getNumMyLinksCategory( $categoryId )
-        {
-			$prefix = $this->getPrefix();
-			$table = "{$prefix}mylinks";
-			$cond = "category_id = '".Db::qstr($categoryId)."';";
-			
-			return( $this->getNumItems( $table, $cond ));
-        }
-		
 		/**
 		 * marks a category as updated now, changing the last_modfication field to
 		 * NOW()
@@ -237,12 +185,14 @@
 		 */
 		function updateCategoryModificationDate( $categoryId )
 		{
-			$query = "UPDATE ".$this->getPrefix()."mylinks_categories
-					  SET last_modification = NOW()
-					  WHERE id = '".Db::qstr( $categoryId )."'";
-			$result = $this->Execute( $query );
-			
-			return $result;
+			include_once( PLOG_CLASS_PATH."class/data/timestamp.class.php" );
+			$category = $this->getMyLinksCategory( $categoryId );
+			if( $category ) {
+				$category->setModificationDate( Timestamp::getNowTimestamp());
+				return( $this->update( $category ));
+			}
+			else
+				return false;
 		}
 
         /**
@@ -250,19 +200,18 @@
          */
 		function updateLastModification( $categoryId , $lastModification)
 		{
-			$query = "UPDATE ".$this->getPrefix()."mylinks_categories
-					  SET last_modification = '".Db::qstr( $lastModification )."' 
-					  WHERE id = '".Db::qstr( $categoryId )."'";
-			$result = $this->Execute( $query );
-			
-			return $result;
+			include_once( PLOG_CLASS_PATH."class/data/timestamp.class.php" );
+			$category = $this->getMyLinksCategory( $categoryId );
+			if( $category ) {
+				$category->setLastModification( Timestamp::getNowTimestamp());
+				return( $this->update( $category ));
+			}
+			else
+				return false;
 		}
-
-		/**
-		 * @private
-		 */
-        function _fillMyLinksCategoryFromRow( $row )
-        {
+		
+		function mapRow( $row )
+		{
         	$myLinksCategory = new MyLinksCategory( $row["name"],
                                                     $row["blog_id"],
                                                     $row["num_links"],
@@ -270,8 +219,9 @@
                                                     $row["id"] );
 
 			$myLinksCategory->setLastModification( new Timestamp( $row["last_modification"] ));
+			$myLinksCategory->setNumLinks( $row["num_links"] );
 
             return $myLinksCategory;
-        }
+		}
     }
-?>
+?>
\ No newline at end of file

Modified: plog/trunk/class/dao/mylinkscategory.class.php
===================================================================
--- plog/trunk/class/dao/mylinkscategory.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/mylinkscategory.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -38,6 +38,16 @@
 			$this->setProperties( $properties );
 			$this->_lastModification = new Timestamp();
 			$this->_links = null;
+			$this->_numLinks = 0;
+			
+			$this->_pk = "id";
+			$this->_fields = Array(
+			   "name" => "getName",
+			   "blog_id" => "getBlogId",
+			   "last_modification" => "getLastModification",
+			   "properties" => "getProperties",
+			   "num_links" => "getNumLinks"
+			);
         }
 
         /**
@@ -162,5 +172,10 @@
 		{
 			return $this->_lastModification;
 		}
+		
+		function setNumLinks( $numLinks )
+		{
+			$this->_numLinks = $numLinks;
+		}		
     }
 ?>

Modified: plog/trunk/class/dao/trackback.class.php
===================================================================
--- plog/trunk/class/dao/trackback.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/trackback.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -25,10 +25,11 @@
 		 * @param clientIp the IP address where the trackback is coming from
          * @param id Identifier of this item.
          */
-        function TrackBack( $url, $title, $articleId, $excerpt, $blogName, $date, $clientIp, $spamRate = 0, $status = COMMENT_STATUS_NONSPAM, $id = -1 )
+        function TrackBack( $url, $title, $articleId, $blogId, $excerpt, $blogName, $date, $clientIp, $spamRate = 0, $status = COMMENT_STATUS_NONSPAM, $id = -1 )
         {
 			// initialize the UserComment object
 			$this->UserComment( $articleId,
+			                    $blogId,
 			                    0,
 								$title,
 								$excerpt,

Modified: plog/trunk/class/dao/trackbacks.class.php
===================================================================
--- plog/trunk/class/dao/trackbacks.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/trackbacks.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -99,23 +99,10 @@
             $date = $row["date"];
             $articleId = $row["article_id"];
 
-            // let's try and keep some kind of cache for this...
-            if( empty($this->_blogSettings[$articleId])) {
-            	$query = "SELECT DISTINCT b.settings AS settings
-                          FROM {$prefix}blogs b, {$prefix}articles a,
-                          {$prefix}trackbacks t
-                          WHERE t.article_id = a.id AND
-                          a.blog_id = b.id
-                          AND a.id = $articleId";
-                $result = $this->Execute( $query );
-                $tmpRow = $result->FetchRow();
-                $blogSettings = Blogs::getBlogSettingsFromField( $tmpRow["settings"] );
-                $this->_blogSettings[$articleId] = $blogSettings;
-            }
-            else {
-            	$blogSettings = $this->_blogSettings[$articleId];
-            }
-
+            $blogId = $row["blog_id"];            
+            $blogs =  new Blogs();
+            $blogInfo = $blogs->getBlogInfo( $blogId );
+            $blogSettings = $blogInfo->getSettings();
             $timeDiff = $blogSettings->getValue( "time_offset" );
             // now that we've got the time difference, we can
             // calculate what would the "real" date...
@@ -146,40 +133,17 @@
         {
 			return( CommentsCommon::getNumPostComments( $artId, $status, COMMENT_TYPE_TRACKBACK ));
         }
-
-        /**
-         * Removes all the trackbacks from a post
-         *
-         * @param artId The article identifier
-         */
-        function deletePostTrackbacks( $artId )
-        {
-			return( CommentsCommon::deletePostComments( $artId, COMMENT_TYPE_TRACKBACK ));
-        }
 		
 		/**
-		 * gets a single trackback from the db
-         * only used by the admin panel, no caching enabled
-		 *
-		 * @param trackbackId
-		 * @param postId
-		 * @return A Tracback object
-		 */
-		function getArticleTrackback( $trackbackId, $articleId = -1 )
-		{	
-			return( CommentsCommon::getPostComment( $articleId, $trackbackId, COMMENT_TYPE_TRACKBACK ));
-		}
-		
-		/**
 		 * removes a trackback from the database
 		 *
 		 * @param trackbackId
 		 * @param articleId
 		 * @return True if successful or false otherwise
 		 */
-		function deletePostTrackback( $trackbackId, $articleId )
+		function deleteTrackback( $trackbackId )
 		{
-			return( CommentsCommon::deletePostComment( $articleId, $trackbackId, COMMENT_TYPE_TRACKBACK ));
+			return( CommentsCommon::deleteComment( $trackbackId, COMMENT_TYPE_TRACKBACK ));
 
             // clear the cache
             $this->_cache->removeData( $articleId, CACHE_TRACKBACKS );
@@ -203,4 +167,4 @@
 														 COMMENT_TYPE_TRACKBACK ));
         }		
     }
-?>
+?>
\ No newline at end of file

Modified: plog/trunk/class/dao/usercomment.class.php
===================================================================
--- plog/trunk/class/dao/usercomment.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/usercomment.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -15,84 +15,26 @@
 	class UserComment extends DbObject 
 	{
 
-    	/**
-         * @private
-         */
 		var $_id;
-
-       /**
-         * @private
-         */
 		var $_artid;
-
-    	/**
-         * @private
-         */
 		var $_userName;
-
-    	/**
-         * @private
-         */
 		var $_userEmail;
-
-    	/**
-         * @private
-         */
 		var $_userUrl;
-
-    	/**
-         * @private
-         */
 		var $_topic;
-
-    	/**
-         * @private
-         */
 		var $_text;
-
-    	/**
-         * @private
-         */
 		var $_date;
-
-    	/**
-         * @private
-         */
         var $_parentid;
-
-    	/**
-         * @private
-         */
         var $_clientIp;
-
-    	/**
-         * @private
-         */
 		var $_timeStamp;
-    	/**
-         * @private
-         */
 		var $_postInfo;
-
-        /**
-         * @private
-         */
         var $_spamRate;
-
-        /**
-         * @private
-         */
         var $_status;
-		
-		/**
-		 * @private
-		 */
 		var $_type;
 
         /**
          * Creates a new user comment.
          */
-		function UserComment( $artid, $parentid, $topic, $text, $date = null, $userName = "", $userEmail = "", $userUrl = "", $clientIp = "0.0.0.0", $spamRate = 0, $status = COMMENT_STATUS_NONSPAM, $id = -1 )
+		function UserComment( $artid, $blogId, $parentid, $topic, $text, $date = null, $userName = "", $userEmail = "", $userUrl = "", $clientIp = "0.0.0.0", $spamRate = 0, $status = COMMENT_STATUS_NONSPAM, $id = -1 )
 		{
 			$this->Object();
 
@@ -124,6 +66,27 @@
 						
 			// by default, we've got a user comment instead of a trackback
 			$this->_type = COMMENT_TYPE_COMMENT;
+			
+			$this->_blogId = $blogId;
+			$this->_sendNotification = false;
+			
+			$this->_fields = Array(
+			   "article_id" => "getArticleId",
+			   "blog_id" => "getBlogId",
+			   "topic" => "getTopic",
+			   "text" => "getText",
+			   "date" => "getDate",
+			   "user_email" => "getUserEmail",
+			   "user_url" => "getUserUrl",
+			   "user_name" => "getUserName",
+			   "parent_id" => "getParentId",
+			   "client_ip" => "getClientIp",
+			   "send_notification" => "getSendNotification",
+			   "status" => "getStatus",
+			   "spam_rate" => "getSpamRate",
+			   "properties" => "getProperties",
+			   "type" => "getType"
+			);
 		}
 
         /**
@@ -439,5 +402,25 @@
 		{
 			$this->_type = $type;
 		}
+		
+		function getSendNotification()
+		{
+			return( $this->_sendNotification );
+		}
+		
+		function setSendNotification( $sendNotification )
+		{
+			$this->_sendNotification = $sendNotification;
+		}
+		
+		function getBlogId()
+		{
+			return( $this->_blogId );
+		}
+		
+		function setBlogId( $blogId )
+		{
+			$this->_blogId = $blogId;
+		}
 	}
 ?>

Modified: plog/trunk/class/dao/userdata/baseuserdataprovider.class.php
===================================================================
--- plog/trunk/class/dao/userdata/baseuserdataprovider.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/userdata/baseuserdataprovider.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -104,7 +104,7 @@
 			$result = $this->Execute( $owner );
 
             while( $row = $result->FetchRow($result)) {
-                $usersBlogs[] = $blogs->_fillBlogInformation( $row );
+                $usersBlogs[] = $blogs->mapRow( $row );
                 $ids[] = $row["id"];
             }
 
@@ -122,12 +122,17 @@
             // now we know to which he or she belongs, so we only have
             // to load the information about those blogs
             while( $row = $result->FetchRow($result)) {
-                $usersBlogs[] = $blogs->_fillBlogInformation( $row );
+                $usersBlogs[] = $blogs->mapRow( $row );
             }
 
             return $usersBlogs;
         }
         
+        function mapRow( $row )
+        {
+        	return( $this->_mapUserInfoObject( $row ));
+        }
+        
         /**
          * @private
          */

Modified: plog/trunk/class/dao/userdata/ploguserdataprovider.class.php
===================================================================
--- plog/trunk/class/dao/userdata/ploguserdataprovider.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/userdata/ploguserdataprovider.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -20,6 +20,8 @@
         function PlogUserDataProvider( $providerConfig )
         {
             $this->BaseUserDataProvider( $providerConfig, true );
+            
+            $this->table = $this->getPrefix()."users";
         }
 
         /**
@@ -32,19 +34,15 @@
          */
         function authenticateUser( $user, $pass )
         {
-            $query = "SELECT * FROM ".$this->getPrefix()."users 
-                      WHERE user = '".Db::qstr($user)."' AND password = '".md5($pass)."'
-                            AND status = '".USER_STATUS_ACTIVE."'";
-
-            $result = $this->Execute( $query );
-
-            if( $result == false )
-                return false;
-
-            if( $result->RecordCount() == 1 )
-                return true;
-            else
-                return false;
+        	$user = $this->getUserInfoFromUsername( $user );
+        	if( $user ) {
+	        	return( $user->getPassword() == md5($pass));
+	        		print("now?");
+	        }
+	        else {
+	        	print("why not??");
+	        	return( false );
+	        }
         }
 
         /**
@@ -72,28 +70,7 @@
          */
         function getUserInfoFromUsername( $username )
         {
-            $userId = $this->_cache->getData( $username, CACHE_USERIDBYNAME );
-
-            if ( !$userId ) {
-                $prefix = $this->getPrefix();
-                $query = "SELECT u.id AS id, u.user AS user, u.password AS password, u.email AS email,
-                                 u.about AS about, u.full_name AS full_name, u.properties AS properties,
-                                 u.resource_picture_id AS resource_picture_id,
-                                 IF(p.permission_id = 1, 1, 0 ) AS site_admin,
-                                 u.status AS status
-                          FROM {$prefix}users u LEFT JOIN {$prefix}users_permissions p ON u.id = p.user_id
-                          WHERE u.user = '".Db::qstr($username)."'";
-                 $userInfo = $this->_getUserInfoFromQuery( $query );
-
-                 if ( $userInfo ) {
-                     $this->_cache->setData( $userInfo->getUsername(), CACHE_USERIDBYNAME, $userInfo->getId() );
-                     $this->_cache->setData( $userInfo->getId(), CACHE_USERINFO, $userInfo );
-                 }
-
-                 return $userInfo;
-            }
-
-            return $this->getUserInfoFromId( $userId );
+        	return( $this->get( "user", $username, CACHE_USERIDBYNAME, Array( CACHE_USERINFO => "getId" )));        	
         }
 
         /**
@@ -102,49 +79,12 @@
          * @param userId User ID of the user from whom we'd like to get the information
          * @return Returns a UserInfo object with the requested information, or false otherwise.
          */
-        function getUserInfoFromId( $userid, $extendedInfo = false )
+        function getUserInfoFromId( $userid )
         {
-                $userInfo = $this->_cache->getData( $userid, CACHE_USERINFO );
-                if ( !$userInfo ) {
-                    $prefix = $this->getPrefix();
-                    $query = "SELECT u.id AS id, u.user AS user, u.password AS password, u.email AS email,
-                                     u.about AS about, u.full_name AS full_name, u.properties AS properties,
-                                     u.resource_picture_id AS resource_picture_id,
-                                     IF(p.permission_id = 1, 1, 0 ) AS site_admin,
-                                     u.status AS status
-                              FROM {$prefix}users u LEFT JOIN {$prefix}users_permissions p ON u.id = p.user_id
-                              WHERE u.id = $userid";
-
-                    $userInfo = $this->_getUserInfoFromQuery( $query, $extendedInfo );
-                    $this->_cache->setData( $userid, CACHE_USERINFO, $userInfo );
-                }
-
-            return $userInfo;
+        	return( $this->get( "id", $userid, CACHE_USERINFO, Array( CACHE_USERIDBYNAME => "getUsername" )));
         }
-
+        
         /**
-         * More common code used by several functions
-         *
-         * Private function used to fill in all the fields of UserInfo objects given
-         * a row of the database.
-         */
-        function _getUserInfoFromQuery( $sql_query, $extendedInfo = false )
-        {
-            $result = $this->Execute( $sql_query );
-            if( !$result )
-                return false;
-
-            if( $result->RowCount() == 0 )
-                return false;
-
-            $info = $result->FetchRow( $result );
-
-            $userInfo = $this->_fillUserInformation( $info, $extendedInfo );
-
-            return $userInfo;
-        }
-
-        /**
          * Given a result record from a Execute call, it will fill in the
          * fields of the object, so that we don't have to repeat the same
          * code too many times
@@ -171,7 +111,7 @@
 	    	if( $searchTerms != "" )
 	    	    $whereSearch = $this->buildSearchCondition( $searchTerms );
 	    	    
-	    	$where = $this->buildWhereCondition( Array( $whereStatus, $whereSearch ));
+	    	$where = Db::buildWhereCondition( Array( $whereStatus, $whereSearch ));
 	        
             $query = "SELECT * FROM ".$this->getPrefix()."users $where ORDER BY id ASC";
 
@@ -205,25 +145,20 @@
          * user we would like to update.
          * @return Returns true if ok or false otherwise.
          */
-        function updateUser( $userInfo )
+        function updateUser( $user )
         {
-            $query = "UPDATE ".$this->getPrefix().
-                     "users SET email = '".$userInfo->getEmail().
-                     "', about = '".Db::qstr($userInfo->getAboutMyself()).
-                     "', password = '".$userInfo->getPassword().
-                     "', full_name = '".Db::qstr($userInfo->getFullName()).
-                     "', resource_picture_id = '".Db::qstr($userInfo->getPictureId()).
-                     "', properties = '".Db::qstr(serialize($userInfo->getProperties())).
-                     "', status = '".Db::qstr($userInfo->getStatus()).
-                     "' WHERE id = ".$userInfo->getId().";";
+        	$result = $this->update( $user );
 
-            // update the users table
-            $result = $this->Execute( $query );
-
-            $this->_cache->removeData( $userInfo->getId(), CACHE_USERINFO );
-            $this->_cache->removeData( $userInfo->getUsername(), CACHE_USERIDBYNAME );
+			if( $userId ) {
+				// remove the old data
+	            $this->_cache->removeData( $user->getId(), CACHE_USERINFO );
+    	        $this->_cache->removeData( $user->getUsername(), CACHE_USERIDBYNAME );
+    	        // and add the new one
+	        	$this->_cache->setData( $user->getId(), CACHE_USERINFO, $user );
+    	    	$this->_cache->setData( $user->getUsername(), CACHE_USERIDBYNAME, $user->getId());    	        
+    	    }
             
-            BaseUserDataProvider::updateUser( $userInfo );
+            BaseUserDataProvider::updateUser( $user );
 
             return $result;
         }
@@ -237,25 +172,14 @@
          */
         function addUser( &$user )
         {
-            $query = "INSERT INTO ".$this->getPrefix()."users(user,password,email,about,full_name,
-                      resource_picture_id,properties,status)
-                      VALUES ('".Db::qstr($user->getUserName())."','".md5($user->getPassword())."','".
-                      Db::qstr($user->getEmail())."','".Db::qstr($user->getAboutMyself())."','".
-                      Db::qstr($user->getFullName())."', '".
-                      Db::qstr($user->getPictureId())."', '".
-                      Db::qstr(serialize($user->getProperties()))."', '".
-                      Db::qstr($user->getStatus())."');";
+        	$userId = $this->add( $user );
 
-            $result = $this->Execute( $query );
-
-            if( !$result )
-                return false;
-
-            $userId = $this->_db->Insert_ID();
-			
-			$user->setId( $userId );
-
-            return $userId;
+			if( $userId ) {        	
+	        	$this->_cache->setData( $user->getId(), CACHE_USERINFO, $user );
+    	    	$this->_cache->setData( $user->getUsername(), CACHE_USERIDBYNAME, $user->getId());
+    	    }
+        	
+        	return( $userId );
         }
 
         /**
@@ -309,19 +233,13 @@
          */
         function disableUser( $userId )
         {
-            $query = "UPDATE ".$this->getPrefix()."users 
-                      SET status = '".USER_STATUS_DISABLED."'
-                      WHERE id = '".Db::qstr($userId)."'";
-
-            $result = $this->Execute( $query );
-
-            if( !$result )
-                return false;
-
-            if( $this->_db->Affected_Rows() == 0 )
-                return false;
-
-            return true;
+        	$user = $this->getUserInfoFromId( $userId );
+        	if( $user ) {
+        		$user->setStatus( USER_STATUS_DISABLED );
+        		return( $this->updateUser( $user ));
+        	}
+        	else
+        		return( false );
         }
         
         /**
@@ -332,23 +250,14 @@
         function deleteUser( $userId )
         {
             // first, delete all of his/her permissions
-    		include_once( PLOG_CLASS_PATH."class/dao/userpermissions.class.php" );            
-            $perms = new UserPermissions();
-            $perms->revokeUserPermissions( $userId );
-
-            $query = "DELETE FROM ".$this->getPrefix()."users WHERE id = $userId;";
-
-            $result = $this->Execute( $query );
-
-            if( !$result )
-                return false;
-
-            if( $this->_db->Affected_Rows() == 0 )
-                return false;
-
-            $this->_cache->removeData( $userId, CACHE_USERINFO );
-
-            return true;
+            if( $this->delete( $userId )) {            
+	    		include_once( PLOG_CLASS_PATH."class/dao/userpermissions.class.php" );
+    	        $perms = new UserPermissions();
+        	    $perms->revokeUserPermissions( $userId );
+        	    $this->_cache->removeData( $userId, CACHE_USERINFO );                        
+            }
+            else
+            	return( false );
         }  
         
         /**

Modified: plog/trunk/class/dao/userinfo.class.php
===================================================================
--- plog/trunk/class/dao/userinfo.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/dao/userinfo.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -40,6 +40,18 @@
 			
 			// by defaults, users are in status "active"
 			$this->setStatus( USER_STATUS_ACTIVE );
+			
+			$this->_pk = "id";
+			$this->_fields = Array( 
+			   "user" => "getUsername",
+			   "password" => "getMD5Password",
+			   "email" => "getEmail",
+			   "full_name" => "getFullName",
+			   "about" => "getAboutMyself",
+			   "properties" => "getProperties",
+			   "status" => "getStatus",
+			   "resource_picture_id" => "getPictureId" 
+		    );
 		}
 
 		/**
@@ -54,6 +66,11 @@
 		{
 			return $this->_password;
 		}
+		
+		function getMD5Password()
+		{
+			return( md5( $this->getPassword()));
+		}
 
 		function getId()
 		{

Modified: plog/trunk/class/data/timestamp.class.php
===================================================================
--- plog/trunk/class/data/timestamp.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/data/timestamp.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -358,6 +358,17 @@
     	}
     	
     	/**
+    	 * returns the current time as a mysql timestamp
+    	 *
+    	 * @static
+    	 */
+    	function getNowTimestamp()
+    	{
+    		$t = new Timestamp();
+    		return( $t->getTimestamp());
+    	}
+    	
+    	/**
     	 * returns an array with a range of years
     	 *
     	 * @param an array

Modified: plog/trunk/class/database/db.class.php
===================================================================
--- plog/trunk/class/database/db.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/database/db.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -8,7 +8,6 @@
 
 	include_once( PLOG_CLASS_PATH."class/object/object.class.php" );
     include_once( PLOG_CLASS_PATH."class/config/configfilestorage.class.php" );
-    //include_once( PLOG_CLASS_PATH."class/database/adodb/adodb.inc.php" );
     include_once( PLOG_CLASS_PATH."class/database/pdb/pdb.class.php" );
 
     /**

Modified: plog/trunk/class/database/dbobject.class.php
===================================================================
--- plog/trunk/class/database/dbobject.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/database/dbobject.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -11,83 +11,61 @@
      */
     class DbObject extends Object
     {
+    	var $_table;
+    	var $_pk;
+    	var $_class;
+    	var $_fields;
+    	var $_properties;
     
-        var $_properties;
-        
-        function DbObject()
-        {
-            $this->Object();
-            $this->_properties = Array();
-        }
-        
-        /**
-         * assigns a generic value
-         *
-         * @param key
-         * @param value
-         * @return true
-         */
-        function setValue( $key, $value )
-        {
-            // make sure that we're dealing with an array here...
-            if( !is_array($this->_properties))
-                $this->_properties = Array();
-                
-            $this->_properties["$key"] = $value;
-            
-            return true;
-        }
-        
-        /**
-         * fetches a generic value
-         *
-         * @param key
-         * @return the value associated to the key
-         */
-        function getValue( $key )
-        {
-            if( !is_array($this->_properties))
-                return "";
-                
-            return $this->_properties["$key"];
-        }
-        
-        /**
-         * returns all the properties
-         *
-         * @return An array with the properties
-         */
-        function getProperties()
-        {
-            return $this->_properties;
-        }
-        
-        /**
-         * assigns all the properties at once
-         *
-         * @param properties An associative array
-         * @return true
-         */
-         function setProperties( $properties )
-         {
-            $this->_properties = $properties;
-         }
-         
-         /**
-          * merges the current properties with the ones given
-          * in the array passed as a parameter
-          *
-          * @param properties
-          * @return True
-          */
-          function addProperties( $properties )
-          {
-            // simply loop through the array and see what we can find...
-            foreach( $propertites as $key => $value ) {
-                $this->setValue( $key, $value );
-            }
-            
-            return true;
-          }
+    	function DbObject()
+    	{
+    		$this->Object();
+    	
+    		$this->_table = null;
+    		$this->_pk = null;
+    		$this->_class = "DbObject";
+    		$this->_fields = Array();
+    		$this->_properties = Array();
+    	}
+    	
+    	function setValue( $key, $value )
+    	{
+    		$this->_properties["$key"] = $value;
+    	}
+    	
+    	function getValue( $key )
+    	{
+    		return( $this->_properties["$key"] );
+    	}
+    	
+    	function setProperties( $properties )
+    	{
+    		$this->_properties = $properties;
+    	}
+    	
+    	function getProperties()
+    	{
+    		return( $properties );
+    	}
+    	
+    	function getClass()
+    	{
+    		return( $this->_class );
+    	}
+    	
+    	function getPK()
+    	{
+    		return( $this->_pk );
+    	}
+    	
+    	function getFields()
+    	{
+    		return( array_keys( $this->_fields ));
+    	}
+    	
+    	function getFieldGetters()
+    	{
+    		return( $this->_fields );
+    	}
     }
 ?>
\ No newline at end of file

Modified: plog/trunk/class/database/pdb/drivers/pdbdriverbase.class.php
===================================================================
--- plog/trunk/class/database/pdb/drivers/pdbdriverbase.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/database/pdb/drivers/pdbdriverbase.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -11,13 +11,12 @@
      * whether we're going to use paging or not.
      */
     define( "DEFAULT_PAGING_ENABLED", -1 );	
-
-    /**
-     * \ingroup PDb
-     *
-     * This class provides the base methods that all database drivers are expected to implement. Some methods
-     * provide some common functionality that should be called even when the method is overwritten, so please make sure
-     * to call the method of the parent class for those that need it.
+    /**
+     * \ingroup PDb
+     *
+     * This class provides the base methods that all database drivers are expected to implement. Some methods
+     * provide some common functionality that should be called even when the method is overwritten, so please make sure
+     * to call the method of the parent class for those that need it.
      */
 	class PDbDriverBase extends Object
 	{
@@ -25,16 +24,16 @@
 		var $_dbname;
 		var $_host;
 		var $_user;
-		var $_password;
-		var $_type = 'generic';
-		var $nameQuote = '`';
-		var $_debug = false;
+		var $_password;
+		var $_type = 'generic';
+		var $nameQuote = '`';
+		var $_debug = false;
 		var $_connected = false;
-	
-	    /**
-	     * Generates a new instance of the driver. Please use PDb::getDriver() instead
-	     *
-	     * @see PDb::getDriver()
+	
+	    /**
+	     * Generates a new instance of the driver. Please use PDb::getDriver() instead
+	     *
+	     * @see PDb::getDriver()
 	     */
 		function PDbDriverBase()
 		{
@@ -51,131 +50,129 @@
 		{
 			// to be implemented by child classes	
 		}
-		
-		/**
-		 * Executes a query and returns a PDbResultSet as a result, or false if the query wasn't
-		 * successfully executed.
-		 *
-		 * This method must be implemented by database drivers.
-		 *
-		 * @param query A string with the query to execute
-		 * @param page Page of records, when using pagination. Leave empty if pagination is not needed.
-		 * @param itemsPerPage Amount of record per page, when using pagination.
-		 * @return A PDbResultSet object if successful or false otherwise
+		
+		/**
+		 * Executes a query and returns a PDbResultSet as a result, or false if the query wasn't
+		 * successfully executed.
+		 *
+		 * This method must be implemented by database drivers.
+		 *
+		 * @param query A string with the query to execute
+		 * @param page Page of records, when using pagination. Leave empty if pagination is not needed.
+		 * @param itemsPerPage Amount of record per page, when using pagination.
+		 * @return A PDbResultSet object if successful or false otherwise
 		 */
 		function Execute( $query, $page = DEFAULT_PAGING_ENABLED, $itemsPerPage = DEFAULT_ITEMS_PER_PAGE )
 		{
 			// to be implemented by child classes
 		}
-		
-		/**
-		 * Starts a new connection to a databse
-		 *
-		 * Database drivers should call this method after providing their own implementation.
-		 *
-		 * @param host The host to which we're initiating the connection
-		 * @param username The username used to connecto the database
-		 * @param password Password assigned to the user above
-		 * @param dbname The name of the database to which we're connecting
-		 * @return Returns true if successful or false otherwise
+		
+		/**
+		 * Starts a new connection to a databse
+		 *
+		 * Database drivers should call this method after providing their own implementation.
+		 *
+		 * @param host The host to which we're initiating the connection
+		 * @param username The username used to connecto the database
+		 * @param password Password assigned to the user above
+		 * @param dbname The name of the database to which we're connecting
+		 * @return Returns true if successful or false otherwise
 		 */
 		function Connect( $host, $username, $password, $dbname = null )
 		{
 			$this->_host = $host;
 			$this->_username = $username;
 			$this->_password = $password;
-			$this->_dbname = $dbname;
+			$this->_dbname = $dbname;
 			$this->_connected = true;
 			
 			// extra functionality to be implemented by child classes...
 		}
-
-		/**
-		 * Starts a new persistent connection to the database
-		 *
-		 * Database drivers should call this method after providing their own implementation.
-		 *		 
-		 * @param host The host to which we're initiating the connection
-		 * @param username The username used to connecto the database
-		 * @param password Password assigned to the user above
-		 * @param dbname The name of the database to which we're connecting
-		 * @return Returns true if successful or false otherwise
+		/**
+		 * Starts a new persistent connection to the database
+		 *
+		 * Database drivers should call this method after providing their own implementation.
+		 *		 
+		 * @param host The host to which we're initiating the connection
+		 * @param username The username used to connecto the database
+		 * @param password Password assigned to the user above
+		 * @param dbname The name of the database to which we're connecting
+		 * @return Returns true if successful or false otherwise
 		 */		
 		function PConnect( $host, $username, $password, $dbname )
 		{
 			$this->_host = $host;
 			$this->_username = $username;
 			$this->_password = $password;
-			$this->_dbname = $dbname;
+			$this->_dbname = $dbname;
 			$this->_connected = true;
 			
 			// extra functionality to be implemented by child classes...
 		}
-
-        /**
-         * Closes the current connection to the database
-         *
-		 * This method must be implemented by database drivers.
-         *
-         * @return nothing
+        /**
+         * Closes the current connection to the database
+         *
+		 * This method must be implemented by database drivers.
+         *
+         * @return nothing
          */
 		function Close()
 		{
 		    // to be implemented by child classes
 		}		
-		
-		/**
-		 * Returns the last error message that was generated by the driver
-		 *
-		 * This method must be implemented by database drivers.
-		 *		 
-		 * @return A string representing an error message, if any.		 
+		
+		/**
+		 * Returns the last error message that was generated by the driver
+		 *
+		 * This method must be implemented by database drivers.
+		 *		 
+		 * @return A string representing an error message, if any.		 
 		 */
 		function ErrorMsg()
 		{
 			// to be implemented by child classes
 		}
-		
-		/**
-		 * The row id as generated by the last INSERT operation.
-		 *
-		 * This method must be implemented by database drivers.		 
-		 *
-		 * @return A row id
+		
+		/**
+		 * The row id as generated by the last INSERT operation.
+		 *
+		 * This method must be implemented by database drivers.		 
+		 *
+		 * @return A row id
 		 */
 		function Insert_ID()
 		{
 			// to be implemented by child classes
 		}
-		
-		/**
-		 * Returns the number of rows affected by the last UPDATE, INSERT or DELETE operation.
-		 * Use PDbRecordSet::Row_Count() to retrieve the number of rows in a SELECT operation.
-		 *
-		 * This method must be implemented by database drivers.		 
-		 * 
-		 * @return the number of affected rows
-		 * @see PDbRecordSet::Row_Count()
+		
+		/**
+		 * Returns the number of rows affected by the last UPDATE, INSERT or DELETE operation.
+		 * Use PDbRecordSet::Row_Count() to retrieve the number of rows in a SELECT operation.
+		 *
+		 * This method must be implemented by database drivers.		 
+		 * 
+		 * @return the number of affected rows
+		 * @see PDbRecordSet::Row_Count()
 		 */
 		function Affected_Rows()
 		{
 			// to be implemented by child classes
-		}
-		
-		/**
-		 * Returns true if the driver is currently connected to a database. Connections usually happen
-		 * after Connect or PConnect are called
-		 *
-		 * @return true if the driver is currently conneced or false otherwise
-		 * @see PDbDriverBase::PConnect()
-		 * @see PDbDriverBase::Connect()
-		 */
-		function IsConnected()
-		{
-		   return( $this->_connected );
 		}
 		
 		/**
+		 * Returns true if the driver is currently connected to a database. Connections usually happen
+		 * after Connect or PConnect are called
+		 *
+		 * @return true if the driver is currently conneced or false otherwise
+		 * @see PDbDriverBase::PConnect()
+		 * @see PDbDriverBase::Connect()
+		 */
+		function IsConnected()
+		{
+		   return( $this->_connected );
+		}
+		
+		/**
 		 * @private
 		 */
 		function _debugQuery( $query )
@@ -186,11 +183,11 @@
 		    
 		    return( true );
 		}
-		
-		/**
-		 * Activates the debug stuff.
-		 *
-		 * @param debug Whether debug should be enabled or not
+		
+		/**
+		 * Activates the debug stuff.
+		 *
+		 * @param debug Whether debug should be enabled or not
 		 */
 		function setDebug( $debug )
 		{
@@ -275,47 +272,47 @@
             $queryPart  = $columnName . ' ' . $operator . ' ';
             $queryPart .= Db::quoteValue( $columnValue );
             return $queryPart;
-        }
-        
-        /**
-         * for compatibility with ADOdb. Use Db::qstr() instead
-         *
-         * @private
-         */
-        function qstr( $string )         
-        {
-            return( Db::qstr( $string ));
-        }
-        
-        /**
-         * Load the correct data dictionary driver. Child classes should overwrite this method
-         * and provide the right driver name so that this method can be called without parameters.
-         *
-         * @param driverName the driver name.
-         * @param A reference to the driver-specific PDbBaseDataDict object
-         */
-        function &getDriverDataDictionary( $driverName ) 
-        {            
-            $dataDictPath = PLOG_CLASS_PATH."class/database/pdb/datadict/pdb{$driverName}datadict.class.php";
-            
-            // check if the driver exists at all
-            if( !is_readable( $dataDictPath )) {
-                throw( new Exception( "Cannot load data dictionary for driver $driverName!" ));
-                die();
-            }
-            
-            //print( "Loading datadict driver $dataDictPath...<br/>" );
-            
-            include_once( strtolower($dataDictPath));
-            
-            $className = "PDb{$driverName}DataDict";
-            $class =& new $className();
-            
-            $class->dataProvider = $this;
-            $class->connection = &$this;
-            
-            return( $class );
         }
+        
+        /**
+         * for compatibility with ADOdb. Use Db::qstr() instead
+         *
+         * @private
+         */
+        function qstr( $string )         
+        {
+            return( Db::qstr( $string ));
+        }
+        
+        /**
+         * Load the correct data dictionary driver. Child classes should overwrite this method
+         * and provide the right driver name so that this method can be called without parameters.
+         *
+         * @param driverName the driver name.
+         * @param A reference to the driver-specific PDbBaseDataDict object
+         */
+        function &getDriverDataDictionary( $driverName ) 
+        {            
+            $dataDictPath = PLOG_CLASS_PATH."class/database/pdb/datadict/pdb{$driverName}datadict.class.php";
+            
+            // check if the driver exists at all
+            if( !is_readable( $dataDictPath )) {
+                throw( new Exception( "Cannot load data dictionary for driver $driverName!" ));
+                die();
+            }
+            
+            //print( "Loading datadict driver $dataDictPath...<br/>" );
+            
+            include_once( strtolower($dataDictPath));
+            
+            $className = "PDb{$driverName}DataDict";
+            $class =& new $className();
+            
+            $class->dataProvider = $this;
+            $class->connection = &$this;
+            
+            return( $class );
+        }
     
         /**
          * @param ttype can either be 'VIEW' or 'TABLE' or false.
@@ -365,9 +362,9 @@
         }
     
         /**
-         * @returns an array with the primary key columns in it.
-         *
-         * @param table
+         * @returns an array with the primary key columns in it.
+         *
+         * @param table
          * @param owner
          */
         function MetaPrimaryKeys($table, $owner=false)
@@ -381,7 +378,7 @@
                         $p[] = $v->name;
                 }
             }
-            if (sizeof($p)) return $p;
+            if (sizeof($p)) return $p;
             return false;
         }
     
@@ -398,20 +395,19 @@
         function &MetaColumns($table)
         {
             $rs = $this->Execute(sprintf("SHOW COLUMNS FROM %s",$table));
-
             if (!is_object($rs))
-                return false;
-                
+                return false;
+                
                 include_once( PLOG_CLASS_PATH."class/database/pdb/datadict/pdbfielddescobject.class.php" );
                 
-                $retarr = array();
-                while( $row = $rs->FetchRow()) {
-                    $fld = new PDbFieldDescObject();
-                    
-                    //
-                    // :TODO:
-                    // Is this mysql-specific stuff?? If so, it should be moved to the Mysql driver!!
+                $retarr = array();
+                while( $row = $rs->FetchRow()) {
+                    $fld = new PDbFieldDescObject();
+                    
                     //
+                    // :TODO:
+                    // Is this mysql-specific stuff?? If so, it should be moved to the Mysql driver!!
+                    //
                     $fld->name = $row["Field"];
                     $type = $row["Type"];
                     
@@ -444,7 +440,7 @@
                         }
                     }                
                 
-                    $retarr[strtoupper($fld->name)] = $fld;
+                    $retarr[strtoupper($fld->name)] = $fld;
                 }
             
                 $rs->Close();
@@ -472,4 +468,4 @@
             return $arr;
         }        
 	}
-?>
+?>

Modified: plog/trunk/class/database/pdb/pdb.class.php
===================================================================
--- plog/trunk/class/database/pdb/pdb.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/database/pdb/pdb.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -1,82 +1,96 @@
 <?php
     /**
-	 * \defgroup PDb
-	 */
-	 
-	include_once( PLOG_CLASS_PATH."class/object/object.class.php" );
-	
-	define( "PDB_DRIVER_FOLDER", PLOG_CLASS_PATH."class/database/pdb/drivers/" );
-	
-    /**
-     * how many items per page by default, when paging is enabled
-     */
-    define( "DEFAULT_ITEMS_PER_PAGE", 15 );
-    
-    /**
-     * whether we're going to use paging or not.
-     */
-    define( "DEFAULT_PAGING_ENABLED", -1 );	
-
-	/**
-	 * PDb
-	 *
-	 * Plog's own lightweight database abstraction layer
-	 *
-	 * \ingroup PDb
-	 */
-	class PDb extends Object
-	{
-		var $_drivers;
-	
-		function PDb()
-		{
-			$this->Object();
-		}
-		
-		/**
-		 * return the right driver type
-		 *
-		 * @param driver the driver name. Supported types are
-		 *
-		 * - mysql
-		 *
-		 * @return An object of a class extending the PDbDriverBase class that implements the requested
-		 * database access.
-		 * @see PDbDriverBase
-		 */
-		function getDriver( $driver )
-		{
-			$drivers = Array( 
-			   "mysql" => "PDbMySQLDriver",
-			   "dbx" => "PDbDbxDriver" );			
-			
-			// load the driver class
-			$driverPath = PDB_DRIVER_FOLDER.strtolower( $drivers[$driver] ).".class.php";
-			include_once( $driverPath );
-			
-			// create an instance of it
-			$driverClass = new $drivers[$driver]();
-			
-			return( $driverClass );
-		}
-	}
-	
-	/**
-	 * ADOdb compatibility
-	 *
-	 * @param driver A driver class whose data dictionary class we'd like to get. This method is obsolete
-	 * and you should call PDbDriverBase::getDriverDataDictionary(). This method is only here for compatibility
-	 * reasons.
-	 *
-	 * @see PDbDriverBase::getDriverDataDictionary()	 
-	 * @deprecated
-	 */
+     * \defgroup PDb
+     */
+     
+    include_once( PLOG_CLASS_PATH."class/object/object.class.php" );
+    
+    define( "PDB_DRIVER_FOLDER", PLOG_CLASS_PATH."class/database/pdb/drivers/" );
+    
+    /**
+     * how many items per page by default, when paging is enabled
+     */
+    define( "DEFAULT_ITEMS_PER_PAGE", 15 );
+    
+    /**
+     * whether we're going to use paging or not.
+     */
+    define( "DEFAULT_PAGING_ENABLED", -1 ); 
+
+    /**
+     * PDb
+     *
+     * Plog's own lightweight database abstraction layer
+     *
+     * \ingroup PDb
+     */
+    class PDb extends Object
+    {
+        function PDb()
+        {
+            $this->Object();
+        }
+        
+        /**
+         * return the right driver type
+         *
+         * @param driver the driver name. Supported types are
+         *
+         * - mysql
+         *
+         * @return An object of a class extending the PDbDriverBase class that implements the requested
+         * database access.
+         * @see PDbDriverBase
+         */
+        function getDriver( $driver )
+        {
+            $validDrivers = PDb::getValidDrivers();
+
+            print_r($validDrivers);
+
+            if( array_key_exists($driver, $validDrivers) ) {
+                // load the driver class
+                $driverPath = PDB_DRIVER_FOLDER.strtolower( $validDrivers[$driver] ).".class.php";
+                include_once( $driverPath );
+                
+                // create an instance of it
+                $driverClass = new $validDrivers[$driver]();
+                
+                return( $driverClass );
+            } else {
+                return false;
+            }
+        }
+
+        function getValidDrivers() {
+            $_drivers = Array( "mysql"    => "PDbMySQLDriver",
+                               "postgres" => "PDbPostgresDriver",
+                               "dbx"      => "PDbDbxDriver" );           
+    
+            return $_drivers;
+        }
+
+        function listDrivers() {
+            return array_keys( PDb::getValidDrivers() );
+        }
+    }
+    
+    /**
+     * ADOdb compatibility
+     *
+     * @param driver A driver class whose data dictionary class we'd like to get. This method is obsolete
+     * and you should call PDbDriverBase::getDriverDataDictionary(). This method is only here for compatibility
+     * reasons.
+     *
+     * @see PDbDriverBase::getDriverDataDictionary()     
+     * @deprecated
+     */
     function NewDataDictionary( $driver )
     {
-		$false = false;
+        $false = false;
 
-		//include_once(ADODB_DIR.'/adodb-datadict.inc.php');
-		//include_once( PLOG_CLASS_PATH."class/database/pdb/datadict/pdbdatadict.class.php" );
-		return( $driver->getDriverDataDictionary());
-    }
-?>
\ No newline at end of file
+        //include_once(ADODB_DIR.'/adodb-datadict.inc.php');
+        //include_once( PLOG_CLASS_PATH."class/database/pdb/datadict/pdbdatadict.class.php" );
+        return( $driver->getDriverDataDictionary());
+    }
+?>

Modified: plog/trunk/class/gallery/dao/galleryalbum.class.php
===================================================================
--- plog/trunk/class/gallery/dao/galleryalbum.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/gallery/dao/galleryalbum.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -1,7 +1,6 @@
 <?php
 
 	include_once( PLOG_CLASS_PATH."class/database/dbobject.class.php" );
-    include_once( PLOG_CLASS_PATH."class/data/timestamp.class.php" );
 
     /**
 	 * \ingroup Gallery
@@ -54,11 +53,33 @@
             $this->_parentId = $parentId;
             $this->_date = $date;
             $this->_id = $id;
-            $this->_numResources = -1;
-            $this->_numChildren  = -1;
+            $this->_numResources = 0;
+            $this->_numChildren  = 0;
             $this->_showAlbum = $showAlbum;
             $this->_properties = $properties;
+            $this->_children = null;
+            $this->_resources = null;
+            
+            $this->_pk = "id";
+            $this->_fields = Array(
+                "owner_id" => "getOwnerId",
+                "description" => "getDescription",
+                "name" => "getName",
+                "flags" => "getFlags",
+                "parent_id" => "getParentId",
+                "date" => "getDate",
+                "properties" => "getProperties",
+                "show_album" => "getShowAlbum",
+                "mangled_name" => "getMangledName",
+                "num_resources" => "getNumResources",
+                "num_children" => "getNumChildren"
+            );
         }
+        
+        function setId( $id )
+        {
+        	$this->_id = $id;
+        }
 
 		/**
 		 * Returns the owner id
@@ -125,6 +146,23 @@
         {
         	return $this->_parentId;
         }
+        
+		/**
+		 * Returns the parent album, or null if there is no parent album
+		 *
+		 * @return A GalleryAlbum object or null if there is no parent
+		 */
+        function getParent()
+        {
+        	if( $this->_parent == null ) {
+        		include_once( PLOG_CLASS_PATH."class/gallery/dao/galleryalbums.class.php" );
+        		$albums = new GalleryAlbums();
+        		$this->_parent = $albums->getAlbum( $this->getParentId(), $this->getOwnerId());
+        	}
+        	
+        	return( $this->_parent );
+        }
+        
 
 		/**
 		 * Sets the parent id of the album. It is important that it is a valid 
@@ -148,6 +186,7 @@
 		 */
         function getTimestamp()
         {
+		    include_once( PLOG_CLASS_PATH."class/data/timestamp.class.php" );        
         	return new Timestamp($this->_date);
         }
 
@@ -183,22 +222,6 @@
         }
 
 		/**
-		 * Returns how many child albums this album has.
-		 *
-		 * @return An integer, or '0' if the album has no children.
-		 */
-        function getNumChildren()
-        {
-			// breaking the rules here again...
-			if( $this->_numChildren == -1 ) {
-				$albums = new GalleryAlbums();
-				$this->_numChildren = $albums->getNumChildren( $this->getId());
-			}
-			
-			return $this->_numChildren;
-        }
-
-		/**
 		 * Returns an array of GalleryAlbum objects representing all the child
 		 * albums that this album has. 
 		 *
@@ -206,6 +229,11 @@
 		 */
         function getChildren()
         {
+        	if( $this->_children == null ) {
+        		$albums = new GalleryAlbums();
+        		$this->_children = $albums->getChildAlbums( $this->getId(), $this->getOwnerId());
+        	}
+        	
 			return $this->_children;
         }
 
@@ -232,6 +260,16 @@
         {
         	return $this->_numResources;
         }
+        
+		/**
+		 * Returns the number of children that this album has.
+		 *
+		 * @return An integer value, or '0' if it has none.
+		 */
+        function getNumChildren()
+        {
+        	return $this->_numChildren;
+        }        
 
 		/**
 		 * Sets number of children of this album.
@@ -266,7 +304,6 @@
 		 */
         function getResources()
         {
-        	//return $this->_resources;
 			if( $this->_resources == null ) {
 				$res = new GalleryResources();
 				$this->_resources = $res->getUserResources( $this->getOwnerId(), $this->getId());
@@ -335,5 +372,11 @@
 			
 			return true;
         }
+        
+        function getMangledName()
+        {
+        	include_once( PLOG_CLASS_PATH."class/data/textfilter.class.php" );
+        	return( Textfilter::urlize( $this->getName()));        	
+        }
     }
-?>
+?>
\ No newline at end of file

Modified: plog/trunk/class/gallery/dao/galleryalbums.class.php
===================================================================
--- plog/trunk/class/gallery/dao/galleryalbums.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/gallery/dao/galleryalbums.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -2,7 +2,10 @@
 
 	include_once( PLOG_CLASS_PATH."class/dao/model.class.php" );
     include_once( PLOG_CLASS_PATH."class/gallery/dao/galleryalbum.class.php" );
-    include_once( PLOG_CLASS_PATH."class/gallery/dao/galleryresources.class.php" );
+    include_once( PLOG_CLASS_PATH."class/gallery/dao/galleryresources.class.php" );    
+    
+    define( "CACHE_USERALBUMS_NESTED", "useralbums_nested" );
+	define( "CACHE_USERALBUMS", "useralbums" );    
 
     /**
 	 * \ingroup Gallery
@@ -23,7 +26,6 @@
 
     	var $_childAlbums;
         var $resources;
-		var $_counts;
 
 		/**
 		 * Constructor. Calls the Model constructor and does nothing more.
@@ -32,8 +34,8 @@
         {
         	$this->Model();
             $this->_childAlbums = Array();
-			// to speed up things a bit...
-			$this->_counts = null;
+			
+			$this->table = $this->getPrefix()."gallery_albums";
         }
 
         /**
@@ -50,16 +52,28 @@
          */
         function getUserAlbums( $ownerId, $onlyShownAlbums = false, $page = DEFAULT_PAGING_ENABLED, $itemsPerPage = DEFAULT_ITEMS_PER_PAGE )
         {
-        	$query = "SELECT id, owner_id, description,
-        	                 name, flags, parent_id,
-        	                 date, properties, show_album
-        	          FROM ".$this->getPrefix()."gallery_albums WHERE owner_id = $ownerId";
-            if( $onlyShownAlbums )
-            	$query .=" AND show_album = 1";
+        	$albums = $this->getMany( "owner_id",
+        	                          $ownerId,
+        	                          CACHE_USERALBUMS,
+        	                          Array( CACHE_GALLERYALBUM => "getId" ),
+        	                          $page,
+        	                          $itemsPerPage );
+        	if( !$albums )
+        		return false;
+        		
+        	$result = Array();
+			if( $onlyShownAlbums ) {
+				foreach( $albums as $album ) {
+					if( $album->getShowAlbum())
+						$result[] = $album;
+				}
+			}
+			else
+				$result = $albums;
+				
+			return( $result );
+        }       
 
-            return $this->_getAlbumsFromQuery( $query, $page, $itemsPerPage );
-        }
-
 		/**
 		 * Returns a specific album from the database.
 		 *
@@ -79,25 +93,15 @@
 		 */
         function getAlbum( $id, $ownerId = -1, $fetchResources = true, $onlyShownAlbums = false )
         {
-        	// we might have this album in the memory cache already..
-            if( isset($this->cache[$id])) {
-            	return $this->cache[$id];
-            }
-
-            // or in the global file cache..
-            $album = $this->_cache->getData( $id, CACHE_GALLERYALBUM );
-
-            if ( !$album || ($onlyShownAlbums && !$album->getShowAlbum()) ) {
-                // otherwise, continue the normal process...
-                $query = "SELECT * FROM ".$this->getPrefix()."gallery_albums WHERE id = $id";
-                if( $ownerId != -1 )
-                    $query .= " AND owner_id = $ownerId";
-                if( $onlyShownAlbums )
-                    $query .= " AND show_album = 1";
-                $album = $this->_getAlbumFromQuery( $query );
-                $this->_cache->setData( $id, CACHE_GALLERYALBUM, $album );
-            }
-            return $album;
+        	$album = $this->get( "id", $id, CACHE_GALLERYALBUM, Array( CACHE_GALLERYALBUMBYNAME => "getMangledName" ));
+        	if( !$album )
+        		return false;
+        	if( $ownerId > -1 && $album->getOwnerId() != $ownerId )
+        		return false;
+        	if( $onlyShownAlbums && !$album->getShowAlbum())
+        		return false;
+        		
+        	return( $album );
         }
 		
 		/**
@@ -119,43 +123,17 @@
 		 */
 		function getAlbumByName( $id, $ownerId = -1, $fetchResources = true, $onlyShownAlbums = false )
 		{
-            // otherwise, continue the normal process...
-        	$query = "SELECT id, owner_id, description,
-        	                 name, flags, parent_id,
-        	                 date, properties, show_album 
-        	          FROM ".$this->getPrefix()."gallery_albums 
-        	          WHERE mangled_name = '".Db::qstr($id)."'";
-            if( $ownerId != -1 )
-            	$query .= " AND owner_id = $ownerId";
-            if( $onlyShownAlbums )
-            	$query .= " AND show_album = 1";
-				
-			return $this->_getAlbumFromQuery( $query );
+        	$album = $this->get( "mangled_name", $id, CACHE_GALLERYALBUMBYNAME, Array( CACHE_GALLERYALBUM => "getId" ));
+        	if( !$album )
+        		return false;
+        	if( $ownerId > -1 && $album->getOwnerId() != $ownerId )
+        		return false;
+        	if( $onlyShownAlbums && !$album->getShowAlbum())
+        		return false;
+        		
+        	return( $album );		
 		}
 		
-		/**
-		 * @private
-		 */
-		function _getAlbumFromQuery( $query )
-		{
-            $result = $this->Execute( $query );
-
-            if( !$result )
-            	return false;
-				
-			if( $result->RowCount() == 0 )
-				return false;
-
-            $row = $result->FetchRow();
-            $album = $this->_fetchAlbumInformation( $row, $fetchResources, $onlyShownAlbums );
-
-            // ...and keep a copy of the object we just fetched
-            // just in case, one  never knows :)
-            $this->cache[$id] = $album;
-
-            return $album;
-		}
-
         /**
          * Returns an array with all the child albums of the given album, but only
          * the ones at the first level (it is not recursive!)
@@ -167,92 +145,45 @@
          * @return An array of GalleryAlbum objects
          */
         function getChildAlbums( $albumId, $ownerId, $onlyShownAlbums = false )
-        {		
-        	$query = "SELECT id, owner_id, description,
-        	                 name, flags, parent_id,
-        	                 date, properties, show_album 
-        	          FROM ".$this->getPrefix()."gallery_albums
-                      WHERE parent_id = $albumId AND
-					  owner_id = $ownerId";
-            if( $onlyShownAlbums )
-            	$query .= " AND show_album = 1";
-
-            return $this->_getAlbumsFromQuery( $query );
+        {
+        	$albums = $this->getUserAlbums( $ownerId, $onlyShownAlbums );
+        	if( !$albums )
+        		return false;
+        	$result = Array();
+        	foreach( $albums as $album ) {
+        		if( $album->getParentId() == $albumId )
+        			$result[] = $album;
+        	}
+        	
+        	return( $result );
         }
 		
         /**
-         * @private
-	     * @see getUserAlbums
-         */
-        function _getAlbumsFromQuery( $query, $page = DEFAULT_PAGING_ENABLED, $itemsPerPage = DEFAULT_ITEMS_PER_PAGE )
-        {
-            $result = $this->Execute( $query, $page, $itemsPerPage );
-
-            // return empty array if the query didn't succeed
-            if( !$result )
-            	return Array();
-
-            $albums = Array();
-            while( $row = $result->FetchRow()) {
-            	array_push( $albums, $this->_fetchAlbumInformation( $row ));
-            }
-
-            return $albums;
-        }
-
-        /**
          * Adds an album to the database
          *
 		 * @param album A GalleryAlbum object, with all its data filled in
 		 * @return Returns true if successful or false otherwise.
 		 * @see GAlleryAlbum
          */
-		function addAlbum( $album )
-        {
-		    include_once( PLOG_CLASS_PATH."class/data/textfilter.class.php" );        
-            $tf = new Textfilter();
-        	$query = "INSERT INTO ".$this->getPrefix()."gallery_albums (
-                      owner_id, description, name, flags, parent_id, properties, 
-                      show_album, normalized_name, normalized_description, mangled_name )
-                      VALUES (".
-                      $album->getOwnerId().", '".Db::qstr($album->getDescription())."', '".
-					  Db::qstr($album->getName())."', 0, ".$album->getParentId().", '".
-                      serialize($album->getProperties())."', 1,'".
-                      Db::qstr($tf->normalizeText($album->getName()))."','".
-                      Db::qstr($tf->normalizeText($album->getDescription()))."', '".
-					  $tf->urlize($album->getName())."');";
-					  
-            $result = $this->Execute( $query );
+		function addAlbum( &$album )
+        {        	
+        	if(( $result = $this->add( $album ))) {
+    	        $this->_cache->removeData( $album->getOwnerId(), CACHE_USERALBUMS );
+    	        $this->_cache->removeData( $album->getOwnerId(), CACHE_USERALBUMS_NESTED );    	        
+    	        if( $album->getParentId() > 0 ) {
+	    	        // update the counters of the parent if there's any
+    	        	$parent = $album->getParent();
+    	        	if( $parent ) {
+	    	        	$parent->setNumChildren( $parent->getNumChildren() + 1 );
+    		        	$this->updateAlbum( $parent );
+    		        }
+    	        }
+    	    }
             
-            if( !$result )
-                return false;
-                
-            // return the id of the last row we inserted, which will be the id of the album
-            $result = $this->_db->Insert_ID();
-
-            // remove the cached album hierarchy array
-            $this->_cache->removeData( $album->getOwnerId(), CACHE_USERALBUMS );
-            
             return $result;
         }
 
         /**
-         * @private
-         */
-        function getNumChildren( $albumId )
-        {
-        	$query = "SELECT COUNT(*) AS num_children FROM ".$this->getPrefix()."gallery_albums
-                      WHERE parent_id = $albumId";
-            $result = $this->Execute( $query );
-            if( !$result )
-            	return 0;
-
-            $row = $result->FetchRow();
-
-            return $row["num_children"];
-        }
-
-        /**
          * updates an album in the db
          *
          * @param album A GalleryAlbum object that already exists in the db.
@@ -264,26 +195,15 @@
 				return false;
 			}
 			
-		    include_once( PLOG_CLASS_PATH."class/data/textfilter.class.php" );			
-            $tf = new TextFilter();
-            $query = "UPDATE ".$this->getPrefix()."gallery_albums SET
-                      description = '".Db::qstr($album->getDescription())."',
-                      name = '".Db::qstr($album->getName())."',
-                      parent_id = ".$album->getParentId().",
-                      properties = '".serialize($album->getProperties())."',
-                      show_album = ".$album->getShowAlbum().",
-                      normalized_name = '".Db::qstr($tf->normalizeText($album->getName()))."',
-                      normalized_description = '".Db::qstr($tf->normalizeText($album->getDescription()))."',
-					  mangled_name = '".$tf->urlize($album->getName())."'
-                      WHERE id = ".$album->getId().";";
+			$result = $this->update( $album );
+			if( $result ) {
+	            // remove the album from the cache
+    	        $this->_cache->removeData( $album->getId(), CACHE_GALLERYALBUM );
+        	    // and remove the cached album hierarchy array
+            	$this->_cache->removeData( $album->getOwnerId(), CACHE_USERALBUMS );			
+			}			
 
-            // remove the album from the cache
-            $this->_cache->removeData( $album->getId(), CACHE_GALLERYALBUM );
-
-            // and remove the cached album hierarchy array
-            $this->_cache->removeData( $album->getOwnerId(), CACHE_USERALBUMS );
-
-            return $this->Execute( $query );
+            return( $result );
         }
 
         /**
@@ -299,85 +219,29 @@
             // too bad we need to load the album before deleting it, but this method
             // won't get called all to often anyway :)
             $album = $this->getAlbum( $albumId );
+            if( $album )
+            	return false;
+            	
+            if( $userId > -1 )
+            	if( $album->getOwnerId() != $userId )
+            		return false;
+            		
+            $this->delete( "id", $albumId );
             $this->_cache->removeData( $album->getOwnerId(), CACHE_USERALBUMS );
-
-        	$query = "DELETE FROM ".$this->getPrefix()."gallery_albums
-                      WHERE id = $albumId";
-            if( $userId != -1 )
-            	$query .= " AND owner_id = $userId";
-
-            // remove the album from the cache
-            $this->_cache->removeData( $albumId, CACHE_GALLERYALBUM );
-
-            return $this->Execute( $query );
+            $this->_cache->removeData( $album->getOwnerId(), CACHE_USERALBUMS_NESTED );            
+            //$this->delete( "parent_id", $album->getId());
+            
+            // update the counters
+            $parent = $album->getParent();
+            if( $parent ) {
+	            $parent->setNumChildren( $parent->getNumChildren() - 1 );
+	            $this->updateAlbum( $parent );
+	        }
+            
+            return( true );
         }
-
-		/**
-		 * @private
-		 */
-        function _getNumResourcesOld( $albumId )
-        {
-        	$query = "SELECT COUNT(*) AS total FROM ".$this->getPrefix()."gallery_resources
-                      WHERE album_id = $albumId";
-
-            $result = $this->Execute( $query );
-
-            if( !$result )
-            	return 0;
-
-            $row = $result->FetchRow();
-
-            if( $row["total"] == "" )
-            	return 0;
-            else
-            	return $row["total"];
-        }
 		
 		/**
-		 * @private 
-		 * Alternative version as the above, faster when loading lots of albums
-		 */
-		function _getNumResources( $albumId )
-		{
-			// if we haven't loaded them all yet...
-			$prefix = $this->getPrefix();
-			if( $this->_counters == null ) {
-				$query = "SELECT album_id, COUNT(*) AS total FROM {$prefix}gallery_resources GROUP BY album_id";
-			
-				$result = $this->Execute( $query );
-				
-				if( !$result )
-					return 0;
-					
-				while( $row = $result->FetchRow()) {
-					$id = $row["album_id"];
-					$this->_counters[$id] = $row["total"];
-				}
-			}
-			
-			$total = $this->_counters[$albumId];
-			
-			if( $total == "" ) $total = 0;
-			
-			return $total;
-		}
-		
-		/**
-		 * returns how many albums this user has
-		 *
-		 * @param userId The number of albums that this user has
-		 * @return The number of albums, or 0 if none or error
-		 */
-		function getNumUserAlbums( $userId )
-		{
-			$prefix = $this->getPrefix();
-			$table = "{$prefix}gallery_albums";
-			$cond = "owner_id = '".Db::qstr($userId)."'";
-				
-			return( $this->getNumItems( $table, $cond ));
-		}
-		
-		/**
 		 * returns all the albums of the blog in an array. The key of the array is the
 		 * parent id of all the albums in the position, and each position is either an
 		 * array with all the albums that share the same parent id or empty if none
@@ -388,41 +252,18 @@
 		 */
 		function getUserAlbumsGroupedByParentId( $userId, $albumId = 0 )
 		{
-            $albums = $this->_cache->getData( $userId, CACHE_USERALBUMS );
-
-            if ( !$albums ) {
-                $prefix = $this->getPrefix();
-                $query = "SELECT * FROM {$prefix}gallery_albums 
-                          WHERE owner_id = '".Db::qstr($userId)."'
-                          ORDER BY name ASC";
-
-                $result = $this->Execute( $query );
-                
-                if( !$result )
-                    return Array();
-                    
-                $albums = Array();
-                $ids = Array();
-                $ids[] = 0;
-                while( $row = $result->FetchRow()) {
-                    $album = new GalleryAlbum( $row["owner_id"],
-                                            $row["name"],
-                                            $row["description"],
-                                            $row["flags"],
-                                            $row["parent_id"],
-                                            $row["date"],
-                                            unserialize($row["properties"]),
-                                            $row["show_album"],
-                                            $row["id"] );
+            $userAlbums = $this->getUserAlbums( $userId );                        
+            $albums = Array();
+ 
+            if( $userAlbums ) {
+                foreach( $userAlbums as $album ) {
                     $key = $album->getParentId();
                     if( $albums["$key"] == "" )
                         $albums["$key"] = Array();
-                    $albums["$key"][] = $album;
-                    
+                    $albums["$key"][] = $album;                 
                     $ids[] = $album->getId();
                 }
-                $this->_cache->setData( $userId, CACHE_USERALBUMS, $albums );
-            }
+            }           
 			
 			return $albums;
 		}
@@ -435,8 +276,14 @@
 		 */
 		function getNestedAlbumList( $userId )
 		{
-			$albums = $this->getUserAlbumsGroupedByParentId( $userId );
-			$nestedAlbums = $this->_getNestedAlbumList( $albums );
+			$nestedAlbums = $this->_cache->getData( $userId, CACHE_USERALBUMS_NESTED );
+			if( !$nestedAlbums ) {
+				// cache the data for later use... this is quite a costly operation so 
+				// it's probably worth caching it!
+				$albums = $this->getUserAlbumsGroupedByParentId( $userId );
+				$nestedAlbums = $this->_getNestedAlbumList( $albums );
+				$this->_cache->setData( $userId, CACHE_USERALBUMS_NESTED, $nestedAlbums );
+			}
 			
 			return $nestedAlbums;
 		}
@@ -450,7 +297,7 @@
 		{
 			$level++;
 			if( $albums["$start"] == "" )
-				return Array();
+				return Array();				
 				
 			foreach( $albums["$start"] as $album ) {
 				// do the replacing
@@ -464,13 +311,10 @@
 			}
 			
 			return $results;
-		}			
-
-        /**
-         * @private
-         */
-        function _fetchAlbumInformation( $row, $fetchResources = true, $onlyShownAlbums = false )
-        {
+		}
+		
+		function mapRow( $row )
+		{
         	$album = new GalleryAlbum( $row["owner_id"],
                                        $row["name"],
                                        $row["description"],
@@ -480,20 +324,10 @@
                                        unserialize($row["properties"]),
                                        $row["show_album"],
                                        $row["id"] );
-
-            // fetch the number of children and the GalleryAlbum child
-            // objects that "hang" from this one
-            //$album->setNumChildren( $this->getNumChildren($row["id"]));
-			$id = $row["id"];
-			$ownerId = $row["owner_id"];
-			if( !isset($this->_childAlbums[$id])) {
-				$this->_childAlbums[$id] = $this->getChildAlbums( $id, $ownerId );
-			}
-            $album->setChildren( $this->_childAlbums[$id] );
-
-            $album->setNumResources( $this->_getNumResources( $id ));
-
+            $album->setNumResources( $row['num_resources'] );
+            $album->setNumChildren( $row['num_children'] );
+            
             return $album;
-        }
+		}
     }
-?>
+?>
\ No newline at end of file

Modified: plog/trunk/class/gallery/dao/galleryresource.class.php
===================================================================
--- plog/trunk/class/gallery/dao/galleryresource.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/gallery/dao/galleryresource.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -73,6 +73,23 @@
             $this->_date = $date;
 			$this->_thumbnailFormat = $thumbnailFormat;
             $this->_id = $id;
+            $this->_album = null;
+            
+            $this->_fields = Array(
+                "owner_id" => "getOwnerId",
+                "album_id" => "getAlbumId",
+                "description" => "getDescription",
+                "date" => "getDate",
+                "flags" => "getFlags",
+                "resource_type" => "getResourceType",
+                "file_path" => "getFilePath",
+                "file_name" => "getFileName",
+                "file_size" => "getFileSize", 
+                "thumbnail_format" => "getThumbnailFormat",
+                "normalized_description" => "getNormalizedDescription",
+                "properties" => "getProperties",
+                "metadata" => "getMetadata"
+            );
         }
 
 		/**
@@ -236,6 +253,12 @@
 		 */		
 		function getAlbum()
 		{
+			if( $this->_album == null ) {
+				include_once( PLOG_CLASS_PATH."class/gallery/dao/galleryalbums.class.php" );
+				$albums = new GalleryAlbums();
+				$this->_album = $albums->getAlbum( $this->getAlbumId());
+			}
+			
 			return $this->_album;
 		}
 
@@ -435,6 +458,13 @@
 			}
 		}
 		
+		function getNormalizedDescription()
+		{
+			include_once( PLOG_CLASS_PATH."class/data/textfilter.class.php" );
+			$tf = new Textfilter();
+			return( $tf->normalizeText( $this->getDescription()));
+		}
+		
 		/**
 		 * @return true if the resource is an image
 		 */

Modified: plog/trunk/class/gallery/dao/galleryresourcequotas.class.php
===================================================================
--- plog/trunk/class/gallery/dao/galleryresourcequotas.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/gallery/dao/galleryresourcequotas.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -1,9 +1,6 @@
 <?php
 
 	include_once( PLOG_CLASS_PATH."class/object/object.class.php" );
-	include_once( PLOG_CLASS_PATH."class/config/config.class.php" );
-	include_once( PLOG_CLASS_PATH."class/dao/blogs.class.php" );
-	include_once( PLOG_CLASS_PATH."class/gallery/dao/galleryresources.class.php" );	
 	
 	define( "GLOBAL_QUOTA_DEFAULT", 5000000 );
 
@@ -23,6 +20,7 @@
 		 */
 		function getGlobalResourceQuota()
 		{
+			include_once( PLOG_CLASS_PATH."class/config/config.class.php" );		
 			$config =& Config::getConfig();
 			$quota = $config->getValue( "resources_quota", GLOBAL_QUOTA_DEFAULT );
 			
@@ -33,26 +31,33 @@
 		 * Returns the quota usage of a user
 		 *
 		 * @param userId The user whose quota usage we would like to know
-		 * @param albumId The album identifier, optional
 		 * @return The number of bytes used
 		 * @static
 		 */
-		function getBlogResourceQuotaUsage( $userId, $albumId = -1 )
+		function getBlogResourceQuotaUsage( $userId )
 		{
-			// get the user resources
-			$resources = new GalleryResources();
-			$blogResources = $resources->getUserResources( $userId, $albumId );
+			//
+			// :HACK:
+			// this is done so that we can keep this method static while still easily
+			// executing an sql query!
+			//
+			$model = new Model();
+			$prefix = $model->getPrefix();
+		
+			// we can use one query to calculate this...
+			$query = "SELECT SUM(file_size) AS total_size FROM {$prefix}gallery_resources
+			          WHERE owner_id = '".Db::qstr( $userId )."'";
+			$result = $model->Execute( $query );
 			
-			if( !$blogResources )
+			if( !$result ) 
 				return 0;
-			
-			// and now go one by one calculating the sizes
-			$total = 0;
-			foreach( $blogResources as $resource ) {
-				$total += $resource->getFileSize();
-			}
-			
-			return $total;
+			$row = $result->FetchRow();
+			if( isset( $row["total_size"] ))
+				$quota = $row["total_size"];
+			else
+				$quota = 0;
+				
+			return( $quota );
 		}
 		
 		/**
@@ -67,7 +72,13 @@
 		function isBlogOverResourceQuota( $blogId, $fileSize )
 		{
 			// current allocated quota
-			$blogQuota = GalleryResourceQuotas::getBlogResourceQuota( $blogId );
+			include_once( PLOG_CLASS_PATH."class/dao/blogs.class.php" );
+			$blogs = new Blogs();
+			$blog = $blogs->getBlogInfo( $blogId );
+			if( !$blog )
+				return false;
+				
+			$blogQuota = $blog->getResourcesQuota();
 			
 			// but if the quota is 0, then for sure we won't be over the quota :)
 			if( $blogQuota == 0 )
@@ -80,25 +91,6 @@
 				return true;
 			else
 				return false;
-		}
-	
-		/**
-		 * returns the current quota allocated for a blog
-		 *
-		 * @param blogId
-		 * @return
-		 * @static
-		 */
-		function getBlogResourceQuota( $blogId )
-		{
-			$blogs = new Blogs();
-			$blogSettings = $blogs->getBlogSettings( $blogId );
-			
-			$blogQuota = $blogSettings->getValue( "resources_quota" );
-			if( $blogQuota == "" )
-				$blogQuota = GalleryResourceQuotas::getGlobalResourceQuota();
-				
-			return $blogQuota;
-		}
+        }
 	}
 ?>
\ No newline at end of file

Modified: plog/trunk/class/gallery/dao/galleryresources.class.php
===================================================================
--- plog/trunk/class/gallery/dao/galleryresources.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/gallery/dao/galleryresources.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -15,9 +15,10 @@
 	include_once( PLOG_CLASS_PATH."class/dao/model.class.php" );
     include_once( PLOG_CLASS_PATH."class/gallery/dao/galleryresource.class.php" );
     include_once( PLOG_CLASS_PATH."class/gallery/galleryconstants.php" );
-    include_once( PLOG_CLASS_PATH."class/gallery/dao/galleryalbums.class.php" );
-	include_once( PLOG_CLASS_PATH."class/config/config.class.php" );
-	include_once( PLOG_CLASS_PATH."class/database/db.class.php" );
+	
+	define( "CACHE_RESOURCES", "galleryresources" );
+	define( "CACHE_RESOURCES_BY_NAME", "galleryresources_name" );	
+	define( "CACHE_RESOURCES_USER", "galleryresources_user" );	
 
     /**
 	 * \ingroup Gallery
@@ -68,11 +69,8 @@
 
     	function GalleryResources()
         {
-        	$this->Model();
-
-            $this->albums = new GalleryAlbums();
-			
-			//$this->_db->debug=true;
+        	$this->Model();            
+            $this->table = $this->getPrefix()."gallery_resources";
         }
 
         /**
@@ -85,29 +83,13 @@
          */
         function getResource( $resourceId, $ownerId = -1, $albumId = -1 )
         {
-            $resource = $this->_cache->getData( $resourceId, CACHE_RESOURCES );
+        	$resource = $this->get( "id", $resourceId, CACHE_RESOURCES );
 
-            if( !$resource ) {
-                $query = "SELECT * FROM ".$this->getPrefix()."gallery_resources
-                          WHERE id = $resourceId";
-                if( $ownerId > 0 )
-                    $query .= " AND owner_id = $ownerId";
-                if( $albumId > 0 )
-                    $query .=" AND album_id = $albumId";
+            if( !$resource )            
+            	return false;
+            if( !$this->check( $resource, $ownerId, $albumId ))
+            	return false;
 
-                $result = $this->Execute( $query );
-
-                if( !$result )
-                    return false;
-
-                if( $result->RecordCount() == 0 )
-                    return false;
-
-                $row = $result->FetchRow();
-                $resource = $this->_fillResourceInformation( $row );
-                $this->_cache->setData( $resourceId, CACHE_RESOURCES, $resource );
-            }
-			
 			return $resource;
         }
 		
@@ -120,7 +102,7 @@
 		 * if there was no next resource
          */		 
 		function getNextResource( $resource )
-		{
+		{		
 			$prefix = $this->getPrefix();
 			$albumId = $resource->getAlbumId();
 			$date = $resource->getDate();
@@ -140,8 +122,11 @@
 				return false;
 				
 			$row = $result->FetchRow();
-			$resource = $this->_fillResourceInformation( $row );
+			$resource = $this->mapRow( $row );
 			
+			$this->_cache->setData( $resource->getId(), CACHE_RESOURCES, $resource );
+			$this->_cache->setData( $resource->getFileName(), CACHE_RESOURCES_BY_NAME, $resource );			
+			
 			return $resource;
 		}
 
@@ -174,8 +159,11 @@
 				return false;
 				
 			$row = $result->FetchRow();
-			$resource = $this->_fillResourceInformation( $row );
+			$resource = $this->mapRow( $row );
 			
+			$this->_cache->setData( $resource->getId(), CACHE_RESOURCES, $resource );
+			$this->_cache->setData( $resource->getFileName(), CACHE_RESOURCES_BY_NAME, $resource );			
+			
 			return $resource;		
 		}
 
@@ -190,61 +178,52 @@
          * the resources that match the given conditions, or empty
          * if none could be found.
          */
-        function getUserResources( $ownerId, $albumId = GALLERY_NO_ALBUM, $resourceType = GALLEY_RESOURCE_ANY, $page = DEFAULT_PAGING_ENABLED, $itemsPerPage = DEFAULT_ITEMS_PER_PAGE )
+        function getUserResources( $ownerId, 
+                                   $albumId = GALLERY_NO_ALBUM, 
+                                   $resourceType = GALLERY_RESOURCE_ANY, 
+                                   $page = DEFAULT_PAGING_ENABLED, 
+                                   $itemsPerPage = DEFAULT_ITEMS_PER_PAGE )
         {
-        	$query = "SELECT id, owner_id, album_id, description,
-        	                 date, flags, resource_type, file_path, file_name,
-        	                 metadata, thumbnail_format 
-        	          FROM ".$this->getPrefix()."gallery_resources
-                      WHERE owner_id = '".Db::qstr($ownerId)."'";
-            if( $albumId > GALLERY_NO_ALBUM )
-            	$query .= " AND album_id = '".Db::qstr($albumId)."'";
-			if( $resourceType > GALLEY_RESOURCE_ANY )
-				$query .= " AND resource_type = '".Db::qstr($resourceType)."'";
+        	$resources = $this->getMany( "owner_id", 
+        								 $ownerId, 
+        	                             CACHE_RESOURCES_USER,
+        	                             null,
+        	                             $page,
+        	                             $itemsPerPage );
+            if( !$resources )
+            	return Array();            	
+            	
+           	$result = Array();
+           	foreach( $resources as $resource ) {
+				if( $this->check( $resource, $ownerId, $albumId, $resourceType ))
+					$result[] = $resource;
+           	}
 
-
-			$query .= " ORDER BY album_id, date ASC";
-
-            $result = $this->Execute( $query, $page, $itemsPerPage );
-
-            if( !$result )
-            	return Array();
-
-            $resources = Array();
-            while( $row = $result->FetchRow()) {
-				$res = new GalleryResource( $row["owner_id"],
-											$row["album_id"],
-											$row["description"],
-											$row["flags"],
-											$row["resource_type"],
-											$row["file_path"],
-											$row["file_name"],
-											unserialize($row["metadata"]),
-											$row["date"],
-											$row["thumbnail_format"],
-											$row["id"] );
-
-				// we should also try to get some information about
-				// to which album this resource belongs
-				if( $albumId != GALLERY_NO_ALBUM ) {
-					// since we're loading all the resources of the same album, it makes no sense
-					// to load the same album every time... so let's load the album only on the first
-					// try and then use the "cached" version
-					if( $album == null ) {
-						$album = $this->albums->getAlbum( $row["album_id"], $row["owner_id"], false );
-					}
-					$res->setAlbum( $album );
-				}
-				else {
-					$resAlbum = $this->albums->getAlbum( $row["album_id"], $row["owner_id"], false );
-					$res->setAlbum( $resAlbum );
-				}
-				
-				array_push( $resources, $res );
-            }
-
-            return $resources;
+            return $result;
         }
+        
+        /**
+         * @private
+         */
+        function check( $resource, 
+                        $ownerId = -1, 
+                        $albumId = GALLERY_NO_ALBUM, 
+                        $resourceType = GALLERY_RESOURCE_ANY )
+        {
+        	if( $ownerId != -1 ) {
+        		if( $resource->getOwnerId() != $ownerId )
+        			return false;
+        	}
+        	if( $albumId != GALLERY_NO_ALBUM ) {
+           		if( $resource->getAlbumId() != $albumId )
+           			return false;
+           	}
+           	if( $resourceType != GALLERY_RESOURCE_ANY ) {
+           		if( $resource->getResourceType() != $resourceType )
+           			return false;
+           	}
+           	return( true );
+        }
 		
 		/**
 		 * returns the number of items given certain conditions
@@ -259,15 +238,7 @@
 		 */
 		function getNumUserResources( $ownerId, $albumId = GALLERY_NO_ALBUM, $resourceType = GALLEY_RESOURCE_ANY )
 		{
-			$prefix = $this->getPrefix();
-			$table  = "{$prefix}gallery_resources";
-            if( $albumId > GALLERY_NO_ALBUM )
-            	$cond .= "album_id = '".Db::qstr($albumId)."'";
-			if( $resourceType > GALLEY_RESOURCE_ANY )
-				$cond .= " AND resource_type = '".Db::qstr($resourceType)."'";
-				
-			// return the number of items
-			return( $this->getNumItems( $table, $cond ));
+			return( count( $this->getUserResources( $ownerId, $albumId, $resourceType )));
 		}
 
 		/**
@@ -307,8 +278,10 @@
 											$filePath, $fileName, $metadata )
 		{
 			// prepare the metadata to be stored in the db
+			$fileSize = $metadata["filesize"];
 			$serMetadata = Db::qstr( serialize($metadata));
 			// get the correct thumbnail format
+			include_once( PLOG_CLASS_PATH."class/config/config.class.php" );
 			$config =& Config::getConfig();
 			$thumbnailFormat = $config->getValue( "thumbnail_format" );
 			// prepare some other stuff
@@ -319,10 +292,11 @@
 			// finally put the query together and execute it
 			$query = "INSERT INTO ".$this->getPrefix()."gallery_resources(
 						  owner_id, album_id, description, flags, resource_type,
-						  file_path, file_name, metadata, thumbnail_format, normalized_description) VALUES (
+						  file_path, file_name, file_size, metadata, thumbnail_format, normalized_description) 
+						  VALUES (
 						  $ownerId, $albumId, '".Db::qstr($description)."', $flags, $resourceType,
-						  '$filePath', '$fileName', '$serMetadata', '$thumbnailFormat',
-				  '".Db::qstr($normalizedDescription)."');";	
+						  '$filePath', '$fileName', '$fileSize', '$serMetadata', '$thumbnailFormat',
+				  '".Db::qstr($normalizedDescription)."');";
 						  
 			$result = $this->Execute( $query );
 
@@ -347,78 +321,21 @@
 				$this->Execute( $query );
 
 			}
+			
+			include_once( PLOG_CLASS_PATH."class/gallery/dao/galleryalbums.class.php" );			
+			$albums = new GalleryAlbums();
+			$album = $albums->getAlbum( $albumId );
+			$album->setNumResources( $album->getNumResources() + 1 );
+			$albums->updateAlbum( $album );			
+			
+			// clear our own caches
+            $this->_cache->removeData( $resourceId, CACHE_RESOURCES );
+			$this->_cache->removeData( $ownerId, CACHE_RESOURCES_USER );
+			$this->_cache->removeData( $fileName, CACHE_RESOURCES_BY_NAME );			
 		
 			return $resourceId;	
 		}
 
-		/**
-		 * generates the thumbnail of a file that we have just added.
-		 *
-		 * @param resFile the resource file from which we're trying to generate the
-		 * thubmail.
-		 * @param fileName The name and path of the new thumbnail we're going to create
-		 */
-		function generateResourceThumbnail( $resFile, $resourceId, $ownerId )
-		{
-			// get some configuration settings regarding the size of the
-			// thumbnails, and also the default format for thumbnails
-			$config =& Config::getConfig();
-			$previewHeight = $config->getValue( "thumbnail_height", GALLERY_DEFAULT_THUMBNAIL_HEIGHT );
-			$previewWidth  = $config->getValue( "thumbnail_width", GALLERY_DEFAULT_THUMBNAIL_WIDTH );
-			$previewKeepAspectRatio = $config->getValue( "thumbnails_keep_aspect_ratio" );
-			
-			// get the file extension
-			$fileParts = explode( ".", $resFile );
-			$fileExt = strtolower($fileParts[count($fileParts)-1]);
-			$fileName = $ownerId."-".$resourceId.".".$fileExt;
-			
-			// and start the resizing process
-			include_once( PLOG_CLASS_PATH."class/gallery/resizers/galleryresizer.class.php" );			
-			$resizer = new GalleryResizer( $resFile );
-			include_once( PLOG_CLASS_PATH."class/gallery/dao/galleryresourcestorage.class.php" );			
-			GalleryResourceStorage::checkPreviewsStorageFolder( $ownerId );
-			$outFile = GalleryResourceStorage::getPreviewsFolder( $ownerId ).$fileName;
-			
-			// and finally, we can generate the preview!
-			$result = $resizer->generate( $outFile, $previewHeight, $previewWidth, $previewKeepAspectRatio );
-			
-			return $result;
-		}
-		
-		/**
-		 * generates the medium-sized thumbnail of a file that we have just added
-		 *
-		 * @param resFile the resource file from which we're trying to generate the
-		 * thubmail.
-		 * @param fileName The name and path of the new thumbnail we're going to create
-		 */
-		function generateResourceMediumSizeThumbnail( $resFile, $resourceId, $ownerId )
-		{
-			// get some configuration settings regarding the size of the
-			// thumbnails, and also the default format for thumbnails
-			$config =& Config::getConfig();
-			$previewHeight = $config->getValue( "medium_size_thumbnail_height", GALLERY_DEFAULT_MEDIUM_SIZE_THUMBNAIL_HEIGHT );
-			$previewWidth  = $config->getValue( "medium_size_thumbnail_width", GALLERY_DEFAULT_MEDIUM_SIZE_THUMBNAIL_WIDTH );
-			$previewKeepAspectRatio = $config->getValue( "thumbnails_keep_aspect_ratio" );
-			
-			// get the file extension
-			$fileParts = explode( ".", $resFile );
-			$fileExt = strtolower($fileParts[count($fileParts)-1]);
-			$fileName = $ownerId."-".$resourceId.".".$fileExt;
-			
-			// and start the resizing process
-		    include_once( PLOG_CLASS_PATH."class/gallery/resizers/galleryresizer.class.php" );			
-			$resizer = new GalleryResizer( $resFile );
-		    include_once( PLOG_CLASS_PATH."class/gallery/dao/galleryresourcestorage.class.php" );			
-			GalleryResourceStorage::checkMediumSizePreviewsStorageFolder( $ownerId );
-			$outFile = GalleryResourceStorage::getMediumSizePreviewsFolder( $ownerId ).$fileName;
-			
-			// and finally, we can generate the preview!
-			$result = $resizer->generate( $outFile, $previewWidth, $previewHeight, $previewKeepAspectRatio );
-			
-			return $result;
-		}		
-
         /**
          * adds a resource to the database. This method requires a FileUpload parameter and it
 		 * will take care of processing the upload file and so on. If the file is already in disk and we'd
@@ -499,8 +416,9 @@
 			
             // and finally, we can generate the thumbnail only if the file is an image, of course :)
             if( $resourceType == GALLERY_RESOURCE_IMAGE ) {
-                $this->generateResourceThumbnail( $resFile, $resourceId, $ownerId );
-				$this->generateResourceMediumSizeThumbnail( $resFile, $resourceId, $ownerId );
+            	include_once( PLOG_CLASS_PATH."class/gallery/resizers/gallerythumbnailgenerator.class.php" );            
+                GalleryThumbnailGenerator::generateResourceThumbnail( $resFile, $resourceId, $ownerId );
+				GalleryThumbnailGenerator::generateResourceMediumSizeThumbnail( $resFile, $resourceId, $ownerId );
             }
 			
             // return the id of the resource we just added
@@ -579,7 +497,8 @@
     
             // and finally, we can generate the thumbnail only if the file is an image, of course :)
             if( $resourceType == GALLERY_RESOURCE_IMAGE ) {
-                $this->generateResourceThumbnail( $resFile, $resourceId, $ownerId );
+            	include_once( PLOG_CLASS_PATH."class/gallery/resizers/gallerythumbnailgenerator.class.php" );
+                GalleryThumbnailGenerator::generateResourceThumbnail( $resFile, $resourceId, $ownerId );
             }
             
             // return the id of the resource we just added
@@ -596,26 +515,14 @@
          */
         function getResourceFile( $ownerId, $fileName, $albumId = -1 )
         {
-        	$query = "SELECT id, owner_id, album_id, description,
-        	          date, flags, resource_type, file_path, file_name,
-        	          metadata, thumbnail_format 
-        	          FROM ".$this->getPrefix()."gallery_resources
-                      WHERE owner_id = $ownerId AND
-                      file_name = '$fileName'";
-					  
-			if( $albumId > 0 )
-				$query .= " AND album_id = $albumId";
-
-            $result = $this->Execute( $query );
-            if( !$result )
-            	return false;
-
-            if( $result->RecordCount() == 0 )
-            	return false;
-
-            $row = $result->FetchRow();
-
-            return $this->_fillResourceInformation( $row );
+        	$resource = $this->get( "file_name", $fileName, CACHE_RESOURCES_BY_NAME );
+        	if( $resource->getOwnerId() != $ownerId )
+        		return false;
+        	if( $albumId != -1 )
+        		if( $resource->getAlbumId() != $albumId )
+        			return false;
+        			
+            return( $resource );
         }
 
         /**
@@ -627,30 +534,14 @@
          */
         function updateResource( $resource ) 
         {
-        	include_once( PLOG_CLASS_PATH."class/data/textfilter.class.php" );        
-            $tf = new TextFilter();
-        	$query = "UPDATE ".$this->getPrefix()."gallery_resources
-                      SET album_id = ".$resource->getAlbumId().",
-                      description = '".Db::qstr($resource->getDescription())."',
-                      flags = ".$resource->getFlags().",
-                      resource_type = ".$resource->getResourceType().",
-                      file_path = '".$resource->getFilePath()."',
-                      file_name = '".$resource->getFileName()."',
-                      metadata = '".Db::qstr(serialize($resource->getMetadata()))."',
-					  thumbnail_format ='".$resource->getThumbnailFormat()."',
-                      date = '".$resource->getDate()."',
-                      normalized_description = '".Db::qstr($tf->normalizeText( $resource->getDescription()))."'
-                      WHERE id = ".$resource->getId();
-
-            $result = $this->Execute( $query );
-
-            // clear the cache
-            $this->_cache->removeData( $resource->getId(), CACHE_RESOURCES );
-
-            if( !$result )
-            	return false;
-            else
-            	return true;
+        	if( $result = $this->update( $resource )) {
+        		// if update ok, reset the caches
+				$this->_cache->removeData( $resource->getId(), CACHE_RESOURCES );
+				$this->_cache->removeData( $resource->getOwnerId(), CACHE_RESOURCES_USER );
+				$this->_cache->removeData( $resource->getOwnerId()."_".$resource->getFileName(), CACHE_RESOURCES_BY_NAME );
+        	}
+        	
+        	return( $result );
         }
 
         /**
@@ -664,26 +555,25 @@
         {
         	// first, get informaiton abotu the resource
             $resource = $this->getResource( $resourceId, $ownerId );
-
-            // now, remove it from the db
-            $query = "DELETE FROM ".$this->getPrefix()."gallery_resources
-                      WHERE id = $resourceId";
-            if( $ownerId > 0 )
-            	$query .= " AND owner_id = $ownerId";
-
-            $result = $this->Execute( $query );
-            
-            // clear the cache
-            $this->_cache->removeData( $resourceId, CACHE_RESOURCES );
-
-            // if there was an error, we quit here
-            if( !$result )
+            if( $resource ) {
+            	$this->delete( "id", $resourceId );
+	            $this->_cache->removeData( $resource->getId(), CACHE_RESOURCES );
+				$this->_cache->removeData( $resource->getOwnerId(), CACHE_RESOURCES_USER );
+				$this->_cache->removeData( $resource->getFileName(), CACHE_RESOURCES_BY_NAME );
+				// update the counters
+				include_once( PLOG_CLASS_PATH."class/gallery/dao/galleryalbums.class.php" );
+				$albums = new GalleryAlbums();
+				$album = $resource->getAlbum();
+				$album->setNumResources( $album->getNumResources() - 1 );
+				$albums->updateAlbum( $album );		
+	            // proceed and remove the file from disk
+			    include_once( PLOG_CLASS_PATH."class/gallery/dao/galleryresourcestorage.class.php" );
+        	    $storage = new GalleryResourceStorage();
+            	return $storage->remove( $resource );            	
+            }
+            else {
             	return false;
-
-            // otherwise, proceed and remove the file from disk
-		    include_once( PLOG_CLASS_PATH."class/gallery/dao/galleryresourcestorage.class.php" );            
-            $storage = new GalleryResourceStorage();
-            return $storage->remove( $resource );
+            }
         }
 
 		/**
@@ -706,33 +596,10 @@
             	return true;
         }
 		
-		/**
-		 * Returns the total number of resources of the given blog
-		 *
-		 * @param userId
-		 * @param albumId
-		 * @return The number of total resources
-		 */
-		function getNumResources( $userId, $albumId = -1 )
-		{
-			$query = "SELECT COUNT(*) AS total FROM ".$this->getPrefix()."gallery_resources
-			          WHERE owner_id = $userId";
-			if( $albumId > 0 )
-				$query .= " AND album_id = $albumId";
-				
-			$result = $this->Execute( $query );
-			
-			if( !$result )
-				return 0;
-				
-			$row = $result->FetchRow();
-			return $row["total"];
-		}
-		
         /**
          * @private
          */
-        function _fillResourceInformation( $row )
+        function mapRow( $row )
         {
         	$res = new GalleryResource( $row["owner_id"],
                                         $row["album_id"],
@@ -745,13 +612,7 @@
                                         $row["date"],
 										$row["thumbnail_format"],
                                         $row["id"] );
-
-             // we should also try to get some information about
-             // to which album this resource belongs
-             $album = $this->albums->getAlbum( $row["album_id"], $row["owner_id"], false );
-             $res->setAlbum( $album );
-
              return $res;
         }
     }
-?>
+?>
\ No newline at end of file

Copied: plog/trunk/class/gallery/resizers/gallerythumbnailgenerator.class.php (from rev 2421, plog/branches/plog-1.1-daochanges/class/gallery/resizers/gallerythumbnailgenerator.class.php)

Modified: plog/trunk/class/locale/locales.class.php
===================================================================
--- plog/trunk/class/locale/locales.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/locale/locales.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -200,11 +200,11 @@
          */
         function getLocales()
         {
-        	$localeCodes = Locales::getAvailableLocales();
+        	$localeCodes = Locales::getAvailableLocales();        	
 
             $locales = Array();
             foreach( $localeCodes as $code ) {
-            	array_push( $locales, new Locale( $code ));
+            	array_push( $locales, Locales::getLocale( $code ));
             }
 
             return $locales;

Modified: plog/trunk/class/logger/LogUtil.php
===================================================================
--- plog/trunk/class/logger/LogUtil.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/logger/LogUtil.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -105,6 +105,7 @@
 		$dumpedvariable = ob_get_contents();
 		ob_end_clean();
 		return $dumpedvariable;
-	}	
+	}
+	
 }
 ?>

Modified: plog/trunk/class/logger/layout/patternlayout.class.php
===================================================================
--- plog/trunk/class/logger/layout/patternlayout.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/logger/layout/patternlayout.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -1,7 +1,8 @@
 <?php
 
-    include_once(PLOG_CLASS_PATH."class/logger/layout/layout.class.php");
+    include_once( PLOG_CLASS_PATH."class/logger/layout/layout.class.php" );
 
+
     /**
      * PatternLayout allows a completely customizable layout that uses a conversion
      * pattern for formatting.
@@ -47,6 +48,44 @@
 			
 			return( $value );
 		}
+		
+		/**
+		 * @static
+		 * @returns returns an array containing information about the stack, or an empty array
+		 * if such information is not available.
+		 * per line
+		 */	
+		function getStackTrace()
+		{
+			if( function_exists("debug_backtrace"))
+				return( debug_backtrace());
+			else
+				return( Array());
+		}
+		
+		/**
+		 * @static
+		 * @returns returns an string containing a full stack trace, one step of the stack
+		 * per line
+		 */
+		function printableStackTrace()
+		{
+			$info = PatternLayout::getStackTrace();
+			$result = "";
+			foreach( $info as $trace ) {
+				if( ($trace["function"] != "printStackTrace") && ($trace["file"] != __FILE__ )) {
+					$result .= $trace["file"];
+					$result .= "(".$trace["line"]."): ";
+					if( isset( $trace["class"] )) {
+						if( $trace["class"] != "" )
+							$result .= $trace["class"].".";
+					}
+					$result .= $trace["function"];
+					$result .= "\n";
+				}
+			}			
+			return( $result );
+		}
 
         /**
          * Format a log message.
@@ -69,6 +108,7 @@
          *     <li><b>%t</b>               - a horizontal tab</li>
          *     <li><b>%T</b>               - a unix timestamp (seconds since January
          *                                   1st, 1970)</li>
+         *     <li><b>%S</b>               - the full stack trace, if available</li>
          * </ul>
          *
          * @param Message A Message instance.
@@ -89,9 +129,9 @@
 			$pattern = str_replace( "%r", "\r", $pattern );
 			$pattern = str_replace( "%t", "\t", $pattern );
 			$pattern = str_replace( "%T", time(), $pattern );
+			$pattern = str_replace( "%S", PatternLayout::printableStackTrace(), $pattern );
 			
 			return( $pattern );
         }
     }
-
 ?>
\ No newline at end of file

Modified: plog/trunk/class/net/http/httpvars.class.php
===================================================================
--- plog/trunk/class/net/http/httpvars.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/net/http/httpvars.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -272,10 +272,16 @@
             } else {
                 $protocol = 'https://';
             }
-            $host      = $serverVars["HTTP_HOST"];
+            //$host      = $serverVars["HTTP_HOST"];
+            $host = $serverVars["SERVER_NAME"];
             $scriptUrl = $serverVars["PHP_SELF"];
-
-            return $protocol . $host . $scriptUrl;
+            $port = $serverVars["SERVER_PORT"];
+            if( $port == 80 || $post == 443 )
+				$baseUrl = $protocol . $host . $scriptUrl;
+			else
+				$baseUrl = $protocol . $host . ":" . $port . $scriptUrl;
+				
+            return( $baseUrl );
         }
     }
 ?>

Modified: plog/trunk/class/net/http/session/sessionmanager.class.php
===================================================================
--- plog/trunk/class/net/http/session/sessionmanager.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/net/http/session/sessionmanager.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -195,4 +195,4 @@
 		    return true;
 		}
 	}
-?>
+?>
\ No newline at end of file

Modified: plog/trunk/class/plugin/pluginbase.class.php
===================================================================
--- plog/trunk/class/plugin/pluginbase.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/plugin/pluginbase.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -154,24 +154,6 @@
 			$this->userInfo = $userInfo;
         }
 
-        /**
-         * Saves the blog settings back to the database so that they are permanent. This function
-         * can be called anytime but it is specially useful from inside the config() method,
-         * when the user has just configured something in the admin interface
-         *
-         * @return Returns true if the settings were saved ok or false otherwise.
-         */
-        function updateBlogSettings()
-        {
-            include_once( PLOG_CLASS_PATH."class/dao/blogs.class.php" );
-
-        	$blogs = new Blogs();
-
-            $result = $blogs->updateBlogSettings( $this->blogInfo->getId(), $this->blogSettings);
-
-            return $result;
-        }
-        
 		/**
 		 * Changes the folder where plugins are loaded from
 		 *

Modified: plog/trunk/class/summary/action/activeaccountaction.class.php
===================================================================
--- plog/trunk/class/summary/action/activeaccountaction.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/summary/action/activeaccountaction.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -49,7 +49,7 @@
         $blogs = new Blogs();
         $blog = $blogs->getBlogInfo($blogId);
         $blog->setStatus(BLOG_STATUS_ACTIVE);
-        $blogs->updateBlog($blogId,$blog);
+        $blogs->updateBlog($blog);
         $blogUrl = $blog->getBlogRequestGenerator();
 		
 		// create the message that we're going to show

Modified: plog/trunk/class/template/templatesets/templatesets.class.php
===================================================================
--- plog/trunk/class/template/templatesets/templatesets.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/template/templatesets/templatesets.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -103,7 +103,8 @@
         function getBlogTemplates( $blogId )
         {
         	$blogs = new Blogs();
-            $blogSettings = $blogs->getBlogSettings( $blogId );
+            $blogInfo = $blogs->getBlogInfo( $blogId );
+            $blogSettings = $blogInfo->getSettings();
 
             $templates = $blogSettings->getValue( "blog_templates" );
 

Modified: plog/trunk/class/template/templatesets/templatesetstorage.class.php
===================================================================
--- plog/trunk/class/template/templatesets/templatesetstorage.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/template/templatesets/templatesetstorage.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -158,6 +158,8 @@
          */
         function removeBlogTemplate( $templateName, $blogId )
         {
+            die("removeBlogTemplate: FIXME!!!");
+        
         	$config =& Config::getConfig();
 
             // get the settings of this blog
@@ -279,8 +281,11 @@
          */
         function addLocalTemplate( $templateName, $blogId )
         {
+            die("addLocaleTemplatemplate: FIXME!!!");
+        
         	$blogs = new Blogs();
-            $blogSettings = $blogs->getBlogSettings( $blogId );
+            $blog = $blogs->getBlogInfo( $blogId );
+            $blogSettings = $blog->getBlogSettings();
             if( $blogSettings == "" || $blogSettings == false )
             	return false;
 

Modified: plog/trunk/class/view/admin/adminarticlecategorieslistview.class.php
===================================================================
--- plog/trunk/class/view/admin/adminarticlecategorieslistview.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/view/admin/adminarticlecategorieslistview.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -40,12 +40,12 @@
 			
 			// retrieve the categories in an paged fashion
 			$totalCategories = $categories->getBlogNumCategories( $this->_blogInfo->getId(), true, $this->_searchTerms );
-            $blogCategories = $categories->getBlogCategoriesAdmin( $this->_blogInfo->getId(), 
-			                                                       false, 
-																   $categoriesOrder,
-																   $this->_searchTerms,
-																   $this->_page,
-																   DEFAULT_ITEMS_PER_PAGE );
+            $blogCategories = $categories->getBlogCategories( $this->_blogInfo->getId(), 
+			                                                  false, 
+															  $categoriesOrder,
+															  $this->_searchTerms,
+															  $this->_page,
+															  DEFAULT_ITEMS_PER_PAGE );
 			if( !$blogCategories ) {
 				$blogCategories = Array();
 			}

Modified: plog/trunk/class/view/admin/adminblogcategorieslistview.class.php
===================================================================
--- plog/trunk/class/view/admin/adminblogcategorieslistview.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/view/admin/adminblogcategorieslistview.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -41,11 +41,11 @@
             $blogCategories = $categories->getBlogCategories( $this->_page, DEFAULT_ITEMS_PER_PAGE );
 			if( !$blogCategories ) {
 				$blogCategories = Array();
-			}
+			}					
 			
 			// throw the even in case somebody's waiting for it!
-			$this->notifyEvent( EVENT_BLOG_CATEGORIES_LOADED, Array( "categories" => &$blogCategories ));
-            $this->setValue( "categories", $blogCategories );
+			$this->notifyEvent( EVENT_BLOG_CATEGORIES_LOADED, Array( "blogcategories" => &$blogCategories ));
+            $this->setValue( "blogcategories", $blogCategories );
 			
 			// the pager that will be used
 			$pager = new Pager( "?op=editBlogCategories&amp;page=",
@@ -54,6 +54,8 @@
 								DEFAULT_ITEMS_PER_PAGE );
 			$this->setValue( "pager", $pager );
 			
+
+			
 			parent::render();
         }
     }

Modified: plog/trunk/class/view/admin/adminblogsettingsview.class.php
===================================================================
--- plog/trunk/class/view/admin/adminblogsettingsview.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/view/admin/adminblogsettingsview.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -18,8 +18,7 @@
 		{
 			$this->AdminTemplatedView( $blogInfo, "blogsettings" );
 			
-			$blogs = new Blogs();
-            $blogSettings = $blogs->getBlogSettings( $this->_blogInfo->getId());
+            $blogSettings = $blogInfo->getSettings();
 			$this->setValue( "blogAbout", $this->_blogInfo->getAbout());
 			$this->setValue( "blogName", $this->_blogInfo->getBlog());
             $this->setValue( "blogLocale", $blogSettings->getValue( "locale" ));

Modified: plog/trunk/class/view/admin/admineditpostview.class.php
===================================================================
--- plog/trunk/class/view/admin/admineditpostview.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/view/admin/admineditpostview.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -64,7 +64,8 @@
 	            
 	            // we need to play a bit with the values of the fields, as the editpost.template page is
 	            // expecting them in a bit different way than if we just do an $article->getFields()
-	            $customFieldValues = $this->_article->getFields();
+	            $customFieldValues = $this->_article->getCustomFields();
+	            print_r($customFieldValues);
 	            $customField = Array();
 	            foreach( $customFieldValues as $fieldValue )
 	            	$customField[$fieldValue->getFieldId()] = $fieldValue->getValue();

Modified: plog/trunk/class/view/admin/adminnewpostview.class.php
===================================================================
--- plog/trunk/class/view/admin/adminnewpostview.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/view/admin/adminnewpostview.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -5,6 +5,7 @@
     include_once( PLOG_CLASS_PATH."class/dao/articlecategories.class.php" );
     include_once( PLOG_CLASS_PATH."class/dao/customfields/customfields.class.php" );
     include_once( PLOG_CLASS_PATH."class/config/config.class.php" );
+    include_once( PLOG_CLASS_PATH."class/data/timestamp.class.php" );
     
     /**
      * \ingroup View

Modified: plog/trunk/class/view/admin/adminresourceslistview.class.php
===================================================================
--- plog/trunk/class/view/admin/adminresourceslistview.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/view/admin/adminresourceslistview.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -49,23 +49,30 @@
 			// get the page from the request
 			$this->_page = $this->getCurrentPageFromRequest();
 
-	        	// and the current album
-        		$galleryAlbums = new GalleryAlbums();
+	        // and the current album
+        	$galleryAlbums = new GalleryAlbums();
 			$galleryResources = new GalleryResources();
 
 			if( $this->_albumId > ROOT_ALBUM_ID && $this->_page > 0 ) {
-        	    		$album = $galleryAlbums->getAlbum( $this->_albumId, $this->_blogInfo->getId());
+        	    $album = $galleryAlbums->getAlbum( $this->_albumId, $this->_blogInfo->getId());
 				if( !$album || $album == "") {
 					$this->_albumId = ROOT_ALBUM_ID;
 				}
 				else {
-					//$resources = $album->getResources();
-					$resources = $galleryResources->getUserResources( $this->_blogInfo->getId(), $this->_albumId, $this->_resourceType, $this->_page, DEFAULT_ITEMS_PER_PAGE );
-					$numResources = $galleryResources->getNumUserResources( $this->_blogInfo->getId(), $this->_albumId, $this->_resourceType );
+					// resources for this page
+					$resources = $galleryResources->getUserResources( $this->_blogInfo->getId(),
+					                                                  $this->_albumId,
+					                                                  $this->_resourceType,
+					                                                  $this->_page,
+					                                                  DEFAULT_ITEMS_PER_PAGE );
+					// total number of resources, used by the pager
+					$numResources = $galleryResources->getNumUserResources( $this->_blogInfo->getId(),
+					                                                        $this->_albumId,
+					                                                        $this->_resourceType );
 				}
 			}
 			else {
-				$albums = $galleryAlbums->getChildAlbums( $this->_albumId, $this->_blogInfo->getId());
+				$albums = $galleryAlbums->getChildAlbums( $this->_albumId, $this->_blogInfo->getId());			
 				$resources = Array();
 			}
 			
@@ -79,19 +86,19 @@
 
 			// fetch some statistics and continue
 			$quotaUsage = GalleryResourceQuotas::getBlogResourceQuotaUsage( $this->_blogInfo->getId());
-			$totalResources = $galleryResources->getNumResources( $this->_blogInfo->getId());
-			$currentQuota = GalleryResourceQuotas::getBlogResourceQuota( $this->_blogInfo->getId());
+			$totalResources = $galleryResources->getNumUserResources( $this->_blogInfo->getId());
 			$this->setValue( "quotausage", $quotaUsage );
 			$this->setValue( "totalresources", $totalResources );
-			$this->setValue( "quota", $currentQuota );
 
 			// and now export info about the albums and so on but only 
 			// if we're browsing the first page only (albums do not appear anymore after the first page)
             $this->setValue( "album", $album );
-			if( $this->_albumId > ROOT_ALBUM_ID && $this->_page < 2 )
+			if( $this->_albumId > ROOT_ALBUM_ID && $this->_page < 2 ) {
 				$this->setValue( "albums", $album->getChildren());
-			else
+			}
+			else {
 				$this->setValue( "albums", $albums );
+			}
 	        
 			// event about the resources
 			$this->notifyEvent( EVENT_RESOURCES_LOADED, Array ( "resources" => &$resources ));

Modified: plog/trunk/class/view/blogview.class.php
===================================================================
--- plog/trunk/class/view/blogview.class.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/class/view/blogview.class.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -149,7 +149,7 @@
             $month = $this->getValue( 'Month' );
             $year = $this->getValue( 'Year' );
 
-            return( $this->articles->getNumberPostsPerDay( $this->_blogInfo->getId(), $year, $month ));
+            return( $this->articles->getDaysWithPosts( $this->_blogInfo->getId(), $year, $month ));
     	}
 
         /**

Modified: plog/trunk/config/config.properties.php
===================================================================
--- plog/trunk/config/config.properties.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/config/config.properties.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -2,16 +2,9 @@
 #
 # database settings
 #
-$config["db_host"] = "";
-$config["db_username"] = "";
-$config["db_password"] = "";
-$config["db_database"] = "";
-#
-# the database prefix will be prefixed to the name of each database tables in case you want
-# to have more than one version of plog running at the same time, such as the stable and
-# unstable one for testing. Each one could use a different prefix and therefore they could
-# coexist in the same unique database. If you change this after the initial configuration done
-# with the installation wizard, please make sure that you also rename the tables.
-#
-$config["db_prefix"] = "";
+$config["db_host"] = "localhost";
+$config["db_username"] = "root";
+$config["db_password"] = "1796sz";
+$config["db_database"] = "plog_11_test";
+$config["db_prefix"] = "plog_";
 ?>
\ No newline at end of file

Modified: plog/trunk/config/logging.properties.php
===================================================================
--- plog/trunk/config/logging.properties.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/config/logging.properties.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -14,10 +14,10 @@
 // debug output sent to debug.log by default. 
   
 $config["debug"] = Array( 
-    "layout"   => "%d %N - [%f:%l (%c:%F)] %m%n", 
+    "layout"   => "%S %d %N - [%f:%l (%c:%F)] %m%n", 
     "appender" => "file",
 	"file"     => "tmp/debug.log",
-    "prio"     => "info"
+    "prio"     => "info"  
   );
 #
 # this logger is the only one enabled by default
@@ -42,4 +42,4 @@
     "prio" => "debug"
   );
 
-?>
+?>
\ No newline at end of file

Modified: plog/trunk/index.php
===================================================================
--- plog/trunk/index.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/index.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -1,7 +1,7 @@
 <?php
 
-//xdebug_start_profiling();
-//xdebug_start_trace('/tmp/trace');
+xdebug_start_profiling();
+//xdebug_start_trace('/Users/oscar/plog-devel/tmp/trace');
 
     // please enable the line below if you are having memory problems
     //ini_set('memory_limit', "16M");
@@ -41,12 +41,9 @@
     // add new actions to the controller
     $pluginManager =& PluginManager::getPluginManager();
     $pluginManager->loadPlugins();
-
-	// initialize the session
-	SessionManager::init();
 	
     // give control to the, ehem, controller :)
-    $controller->process( HttpVars::getRequest(), "op");
+    $controller->process( HttpVars::getRequest(), "op");	
 
-//xdebug_dump_function_profile(4);
+xdebug_dump_function_profile(4);
 ?>

Modified: plog/trunk/templates/admin/blogcategories.template
===================================================================
--- plog/trunk/templates/admin/blogcategories.template	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/templates/admin/blogcategories.template	2005-08-27 19:09:07 UTC (rev 2423)
@@ -18,21 +18,21 @@
    </tr>
   </thead>
   <tbody> 
-  {foreach from=$categories item=category}
+  {foreach from=$blogcategories item=blogcategory}
   <tr class="{cycle values="odd, even"}">
    <td>
-      <input class="checkbox" type="checkbox" name="categoryIds[{counter}]" id="checks_{$category->getId()}" value="{$category->getId()}" />
+      <input class="checkbox" type="checkbox" name="categoryIds[{counter}]" id="checks_{$blogcategory->getId()}" value="{$blogcategory->getId()}" />
    </td>  
    <td class="col_highlighted">
-    <a href="admin.php?op=editBlogCategory&amp;categoryId={$category->getId()}">{$category->getName()}</a>
+    <a href="admin.php?op=editBlogCategory&amp;categoryId={$blogcategory->getId()}">{$blogcategory->getName()}</a>
    </td>
    <td>
-    {$category->getNumBlogs()}
+    {$blogcategory->getNumBlogs()}
    </td>	
    <td>
      <div class="list_action_button">
-       <a href="?op=editBlogCategory&amp;categoryId={$category->getId()}"><img src="imgs/admin/icon_edit-16.png" alt="{$locale->tr("edit")}" /></a>
-       <a href="?op=deleteBlogCategory&amp;categoryId={$category->getId()}"><img src="imgs/admin/icon_delete-16.png" alt="{$locale->tr("delete")}" /></a>
+       <a href="?op=editBlogCategory&amp;categoryId={$blogcategory->getId()}"><img src="imgs/admin/icon_edit-16.png" alt="{$locale->tr("edit")}" /></a>
+       <a href="?op=deleteBlogCategory&amp;categoryId={$blogcategory->getId()}"><img src="imgs/admin/icon_delete-16.png" alt="{$locale->tr("delete")}" /></a>
      </div>
    </td>
   </tr>

Modified: plog/trunk/templates/admin/dashboard.template
===================================================================
--- plog/trunk/templates/admin/dashboard.template	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/templates/admin/dashboard.template	2005-08-27 19:09:07 UTC (rev 2423)
@@ -162,14 +162,6 @@
                                 {$blog->getTotalTrackbacks()}
                             </td>
                         </tr>
-                        <tr style="background-color: {cycle values="#FFFFFF,#F7F7F7"};">
-                            <th>
-                                {$locale->tr("total_viewed")}:
-                            </th>
-                            <td>
-                                {$blog->getViewedTotal()}
-                            </td>
-                        </tr>
                     </table>
                 </td>
             </tr>

Modified: plog/trunk/templates/admin/editlinks.template
===================================================================
--- plog/trunk/templates/admin/editlinks.template	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/templates/admin/editlinks.template	2005-08-27 19:09:07 UTC (rev 2423)
@@ -49,8 +49,9 @@
    <td><a href="{$link->getUrl()}">{$link->getUrl()}</a></td>
    {assign var=linkcategory value=$link->getCategoryId()}
    <td>
-    <a href="admin.php?op=editLinks&amp;showCategory={$linkscategories[$linkcategory]->getId()}">
-      {$linkscategories[$linkcategory]->getName()}
+    {assign var=linkcategory value=$link->getMyLinkCategory()}
+    <a href="admin.php?op=editLinks&amp;showCategory={$linkcategory->getId()}">
+      {$linkcategory->getName()}
     </a>
    </td>
    <td>

Modified: plog/trunk/templates/admin/resources.template
===================================================================
--- plog/trunk/templates/admin/resources.template	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/templates/admin/resources.template	2005-08-27 19:09:07 UTC (rev 2423)
@@ -104,6 +104,7 @@
 </table>
 </div>
 <div id="list_action_bar">
+  {assign var=quota value=$blog->getResourcesQuota()}
   {include file="$admintemplatepath/adminpager.template" style=list}
   {$locale->tr("num_resources")}: <strong>{$totalresources}</strong>, {$locale->tr("total_size")}: <strong>{$quotausage|round}</strong>
   {if $quota > 0 }, {$locale->tr("quota")}: <strong>{$quota|round}</strong>{/if}

Modified: plog/trunk/wizard.php
===================================================================
--- plog/trunk/wizard.php	2005-08-27 15:36:35 UTC (rev 2422)
+++ plog/trunk/wizard.php	2005-08-27 19:09:07 UTC (rev 2423)
@@ -1,1739 +1,1746 @@
-<?php
-
-    if (!defined( "PLOG_CLASS_PATH" )) {
-        define( "PLOG_CLASS_PATH", dirname(__FILE__)."/");
-    }
-
-    set_time_limit (5 * 3600);
-
-    //
-    // enable this for debugging purposes
-    //
-    define( "DB_WIZARD_DEBUG", false );
-
-    //
-    // in case you're having problems with time outs while upgrading (probably too
-    // many records) lower this figure
-    //
-    define( "WIZARD_MAX_RECORDS_PER_STEP", 50 );
-
-    //
-    // threshold that defines up to how many records we should not divide the
-    // transformations in more than one step
-    //
-    define( "WIZARD_MAX_RECORDS_THRESHOLD", 100 );
-
-    // many hosts don't have this enabled and we, for the time being, need it...
-    ini_set("arg_seperator.output", "&amp;");
-
-    include_once( PLOG_CLASS_PATH."class/controller/controller.class.php" );
-    include_once( PLOG_CLASS_PATH."class/template/templateservice.class.php" );
-    include_once( PLOG_CLASS_PATH."class/action/action.class.php" );
-    include_once( PLOG_CLASS_PATH."class/database/db.class.php" );
-    include_once( PLOG_CLASS_PATH."class/template/template.class.php" );
-    include_once( PLOG_CLASS_PATH."class/view/view.class.php" );
-    include_once( PLOG_CLASS_PATH."class/data/validator/stringvalidator.class.php" );
-    include_once( PLOG_CLASS_PATH."class/data/validator/integervalidator.class.php" );
-    include_once( PLOG_CLASS_PATH."class/data/validator/emailvalidator.class.php" );
-    include_once( PLOG_CLASS_PATH."class/data/validator/passwordvalidator.class.php" );
-    include_once( PLOG_CLASS_PATH."class/dao/users.class.php" );
-    include_once( PLOG_CLASS_PATH."class/dao/blogs.class.php" );
-    include_once( PLOG_CLASS_PATH."class/dao/articlecategories.class.php" );
-    include_once( PLOG_CLASS_PATH."class/dao/articles.class.php" );
-    include_once( PLOG_CLASS_PATH."class/net/http/httpvars.class.php" );
-    include_once( PLOG_CLASS_PATH."class/dao/userpermissions.class.php" );
-    include_once( PLOG_CLASS_PATH."class/misc/version.class.php" );
-    include_once( PLOG_CLASS_PATH."class/file/file.class.php" );
-    include_once( PLOG_CLASS_PATH."class/file/finder/filefinder.class.php" );
-    include_once( PLOG_CLASS_PATH."class/gallery/resizers/gddetector.class.php" );
-    include_once( PLOG_CLASS_PATH."class/config/configfilestorage.class.php" );
-    include_once( PLOG_CLASS_PATH."class/data/textfilter.class.php" );
-    include_once( PLOG_CLASS_PATH."class/locale/locales.class.php" );
-    include_once( PLOG_CLASS_PATH."class/locale/localefinder.class.php" );
-    include_once( PLOG_CLASS_PATH."class/template/templatesets/templatesets.class.php" );
-    include_once( PLOG_CLASS_PATH."class/dao/bloginfo.class.php" );
-    include_once( PLOG_CLASS_PATH."class/dao/article.class.php" );
-
-    define( "TEMP_FOLDER", "./tmp" );
-
-    // sql querys used to create the tables
-
-    // maps used to map requests with actions
-    $_actionMap["Default"] = "WizardIntro";
-    $_actionMap["Intro"] = "WizardIntro";
-    $_actionMap["Step1"] = "WizardStepOne";
-    $_actionMap["Step2"] = "WizardStepTwo";
-    $_actionMap["Step3"] = "WizardStepThree";
-    $_actionMap["Step4"] = "WizardStepFour";
-    $_actionMap["Step5"] = "WizardStepFive";
-    $_actionMap["Update1"] = "UpdateStepOne";
-    $_actionMap["Update2"] = "UpdateStepTwo";
-    $_actionMap["Update3"] = "UpdateStepThree";
-    $_actionMap["Update4"] = "UpdateStepFour";
-
-
-
-    $Tables[0]["desc"] = "Articles";
-    $Tables[0]["code"] = "CREATE TABLE {dbprefix}articles (
-  id int(10) unsigned NOT NULL auto_increment,
-  category_id int(10) unsigned NOT NULL default '0',
-  date timestamp(14) NOT NULL,
-  modification_date timestamp(14) NOT NULL,
-  user_id int(10) unsigned NOT NULL default '0',
-  blog_id int(10) unsigned NOT NULL default '0',
-  status INTEGER(5) NOT NULL default 1,
-  num_reads int(10) default '0',
-  properties TEXT NOT NULL default '',
-  slug varchar(255) NOT NULL,
-  num_comments int(10) NOT NULL default '0', 
-  num_nospam_comments int(10) NOT NULL default '0', 
-  PRIMARY KEY (id),
-  KEY num_reads (num_reads),
-  KEY category_id (category_id),
-  KEY blog_id (blog_id),
-  KEY user_id (user_id),
-  KEY slug (slug),
-  KEY blog_id_slug (blog_id,slug),
-  KEY blog_id_slug_category_id (blog_id,slug,category_id)
-) TYPE=MyISAM;";
-
-    $Tables[1]["desc"] = "Article categories";
-    $Tables[1]["code"] = "CREATE TABLE {dbprefix}articles_categories (
-  id int(10) unsigned NOT NULL auto_increment,
-  name varchar(255) NOT NULL default '',
-  url varchar(255) NOT NULL default '',
-  blog_id int(10) unsigned NOT NULL default '0',
-  last_modification timestamp(14) NOT NULL,
-  in_main_page TINYINT(1) NOT NULL DEFAULT '1',
-  parent_id INTEGER(10) NOT NULL DEFAULT '0',
-  description TEXT NOT NULL DEFAULT '',
-  properties text NOT NULL default '',
-  mangled_name varchar(255) NOT NULL default '',
-  num_articles int(10) NOT NULL default 0,
-  num_published_articles int(10) NOT NULL default 0,
-  PRIMARY KEY  (id),
-  KEY parent_id (parent_id),
-  KEY blog_id (blog_id),
-  KEY mangled_name (mangled_name)
-) TYPE=MyISAM;";
-
-    $Tables[2]["desc"] = "Comments";
-    $Tables[2]["code"] = "CREATE TABLE {dbprefix}articles_comments (
-  id int(10) unsigned NOT NULL auto_increment,
-  article_id int(10) unsigned NOT NULL default '0',
-  blog_id int(10) unsigned NOT NULL default '0',
-  topic text NOT NULL,
-  text text,
-  date timestamp(14) NOT NULL,
-  user_email varchar(255) default '',
-  user_url varchar(255) default '',
-  user_name varchar(255) NOT NULL default 'Anonymous',
-  parent_id int(10) unsigned default '0',
-  client_ip varchar(15) default '0.0.0.0',
-  send_notification tinyint(1) default '0',
-  status tinyint(2) default '1',
-  spam_rate float default '0',
-  properties TEXT NOT NULL DEFAULT '',
-  normalized_text TEXT NOT NULL DEFAULT '',
-  normalized_topic TEXT NOT NULL DEFAULT '',
-  type int(3) NOT NULL DEFAULT '0',  
-  PRIMARY KEY  (id),
-  KEY parent_id (parent_id),
-  KEY article_id (article_id),
-  KEY blog_id (blog_id),
-  KEY article_id_blog_id(article_id,blog_id),
-  FULLTEXT KEY normalized_fields (normalized_text,normalized_topic),
-  FULLTEXT KEY normalized_text (normalized_text),
-  FULLTEXT KEY normalized_topic (normalized_topic)
-) TYPE=MyISAM;";
-
-    $Tables[3]["desc"] = "Notifications";
-    $Tables[3]["code"] = "CREATE TABLE {dbprefix}articles_notifications (
-  id int(10) NOT NULL auto_increment,
-  blog_id int(10) NOT NULL default '0',
-  user_id int(10) NOT NULL default '0',
-  article_id int(10) NOT NULL default '0',
-  PRIMARY KEY  (id),
-  KEY article_id (article_id),
-  KEY user_id (user_id),
-  KEY blog_id (blog_id)
-) TYPE=MyISAM;";
-
-    $Tables[4]["desc"] = "Blogs";
-    $Tables[4]["code"] = "CREATE TABLE {dbprefix}blogs (
-  id int(10) unsigned NOT NULL auto_increment,
-  blog varchar(50) NOT NULL default '',
-  owner_id int(10) unsigned NOT NULL default '0',
-  blog_category_id int(10) unsigned NOT NULL default '0',
-  about text,
-  settings text NOT NULL,
-  mangled_blog varchar(50) NOT NULL default '',
-  status int(4) NOT NULL default '1',
-  show_in_summary int(4) not null default '1',
-  create_date TIMESTAMP(14) NOT NULL,
-  last_update_date TIMESTAMP(14) NOT NULL,
-  modification_date TIMESTAMP(14) NOT NULL,
-  PRIMARY KEY  (id),
-  KEY owner_id (owner_id),
-  KEY mangled_blog (mangled_blog),
-  KEY blog_category_id(blog_category_id)
-) TYPE=MyISAM;";
-
-    $Tables[5]["desc"] = "MyLinks";
-    $Tables[5]["code"] = "CREATE TABLE {dbprefix}mylinks (
-  id int(10) unsigned NOT NULL auto_increment,
-  category_id int(10) unsigned NOT NULL default '0',
-  url varchar(255) NOT NULL default '',
-  name varchar(100) default '',
-  description text NOT NULL,
-  blog_id int(10) unsigned NOT NULL default '0',
-  rss_feed varchar(255) not null default '',
-  date timestamp(14) not null,
-  properties TEXT NOT NULL DEFAULT '',
-  PRIMARY KEY  (id),
-  KEY blog_id (blog_id),
-  KEY category_id (category_id)
-) TYPE=MyISAM;";
-
-    $Tables[6]["desc"] = "MyLinks Categories";
-    $Tables[6]["code"] = "CREATE TABLE {dbprefix}mylinks_categories (
-  id int(10) NOT NULL auto_increment,
-  name varchar(100) NOT NULL default '',
-  blog_id int(10) NOT NULL default '0',
-  last_modification timestamp(14) NOT NULL,
-  properties TEXT NOT NULL DEFAULT '',
-  num_links int(10) NOT NULL default '0',
-  PRIMARY KEY  (id),
-  KEY blog_id (blog_id)
-) TYPE=MyISAM;";
-
-    $Tables[9]["desc"] = "Permissions";
-    $Tables[9]["code"] = "CREATE TABLE {dbprefix}permissions (
-  id int(10) unsigned NOT NULL auto_increment,
-  permission varchar(25) NOT NULL default '',
-  description varchar(100) NOT NULL default '',
-  PRIMARY KEY  (id)
-) TYPE=MyISAM;";
-
-    $Tables[10]["desc"] = "Referrers";
-    $Tables[10]["code"] = "CREATE TABLE {dbprefix}referers (
-  id int(10) NOT NULL auto_increment,
-  url text NOT NULL,
-  article_id int(10) NOT NULL default '0',
-  blog_id int(10) NOT NULL default '0',
-  hits int(10) default '1',
-  last_date timestamp(14),
-  PRIMARY KEY  (id),
-  KEY article_id (article_id),
-  KEY blog_id (blog_id),
-  KEY blog_id_article_id (blog_id, article_id)
-) TYPE=MyISAM;";
-
-    $Tables[12]["desc"] = "Users";
-    $Tables[12]["code"] = "CREATE TABLE {dbprefix}users (
-  id int(10) unsigned NOT NULL auto_increment,
-  user varchar(15) NOT NULL default '',
-  password varchar(32) NOT NULL default '',
-  email varchar(255) NOT NULL default '',
-  full_name varchar(255) NOT NULL default '',
-  about text,
-  properties TEXT NOT NULL default '',
-  status integer(4) NOT NULL DEFAULT 1,
-  resource_picture_id integer(10) NOT NULL DEFAULT 0,
-  PRIMARY KEY  (id),
-  UNIQUE KEY user (user)
-) TYPE=MyISAM;";
-
-    $Tables[13]["desc"] = "Permissions";
-    $Tables[13]["code"] = "CREATE TABLE {dbprefix}users_permissions (
-  id int(10) unsigned NOT NULL auto_increment,
-  user_id int(10) unsigned NOT NULL default '0',
-  blog_id int(10) unsigned NOT NULL default '0',
-  permission_id int(10) unsigned NOT NULL default '0',
-  PRIMARY KEY  (id),
-  KEY user_id (user_id),
-  KEY blog_id (blog_id),
-  KEY user_id_permission_id (user_id,permission_id)
-) TYPE=MyISAM;";
-
-
-   $Tables[14]["desc"] = "Configuration";
-   $Tables[14]["code"] = "CREATE TABLE {dbprefix}config (
-   id int(10) NOT NULL auto_increment,
-   config_key varchar(255) NOT NULL default '',
-   config_value text NOT NULL,
-   value_type int(3) default '0',
-   PRIMARY KEY  (id,config_key)
-   ) TYPE=MyISAM;";
-
-   $Tables[15]["desc"] = "Filtered Content";
-   $Tables[15]["code"] = "CREATE TABLE {dbprefix}filtered_content (
-   id int(10) NOT NULL auto_increment,
-   reg_exp text,
-   blog_id int(10) NOT NULL default '0',
-   reason text,
-   date timestamp(14) NOT NULL,
-   PRIMARY KEY  (id),
-   KEY blog_id (blog_id)
-   ) TYPE=MyISAM;";
-
-   $Tables[16]["desc"] = "Blocked content";
-   $Tables[16]["code"] = "CREATE TABLE {dbprefix}host_blocking_rules (
-   id int(10) NOT NULL auto_increment,
-   reason text,
-   date timestamp(14) NOT NULL,
-   blog_id int(10) NOT NULL default '0',
-   block_type int(1) default '1',
-   list_type int(1) default '1',
-   mask int(2) default '0',
-   host varchar(15) default '0.0.0.0',
-   PRIMARY KEY  (id),
-   KEY blog_id (blog_id)
-   ) TYPE=MyISAM;";
-
-   $Tables[17]["desc"] = "Gallery Resources";
-   $Tables[17]["code"] = "CREATE TABLE {dbprefix}gallery_resources (
-   id int(10) NOT NULL auto_increment,
-   owner_id int(10) NOT NULL default '0',
-   album_id int(10) NOT NULL default '0',
-   description text,
-   date timestamp(14) NOT NULL,
-   flags int(10) default '0',
-   resource_type int(3) default NULL,
-   file_path varchar(255) default '',
-   file_name varchar(255) default '',
-   metadata text,
-   thumbnail_format varchar(4) not null default 'same',
-   normalized_description text NOT NULL default '',
-   properties TEXT NOT NULL DEFAULT '',
-   PRIMARY KEY  (id),
-   KEY album_id (album_id),
-   KEY owner_id (owner_id),
-   KEY file_name (file_name),
-   KEY album_id_owner_id (album_id, owner_id),
-   KEY resource_type (resource_type),
-   FULLTEXT KEY normalized_description (normalized_description)
-   ) TYPE=MyISAM;";
-
-   $Tables[18]["desc"] = "Gallery Albums";
-   $Tables[18]["code"] = "CREATE TABLE {dbprefix}gallery_albums (
-   id int(10) NOT NULL auto_increment,
-   owner_id int(10) NOT NULL default '0',
-   description text NOT NULL,
-   name varchar(255) NOT NULL default '',
-   flags int(10) NOT NULL default '0',
-   parent_id int(10) NOT NULL default '0',
-   date timestamp(14) NOT NULL,
-   properties text NOT NULL DEFAULT '',
-   show_album TINYINT(1) DEFAULT 1,
-   normalized_description text NOT NULL default '',
-   normalized_name varchar(255) NOT NULL default '',
-   mangled_name varchar(255) NOT NULL default '',
-   num_resources int(10) NOT NULL default '0',
-   PRIMARY KEY  (id),
-   KEY parent_id (parent_id),
-   KEY owner_id (owner_id),
-   KEY mangled_name (mangled_name),
-   KEY owner_id_mangled_name (owner_id, mangled_name),
-   FULLTEXT KEY normalized_name (normalized_name),
-   FULLTEXT KEY normalized_description (normalized_description),
-   FULLTEXT KEY normalized_fields (normalized_name, normalized_description)
-   ) TYPE=MyISAM;";
-
-   $Tables[19]["desc"] = "Bayesian Filter data table";
-   $Tables[19]["code"] = "CREATE TABLE {dbprefix}bayesian_filter_info (
-   id int(10) unsigned NOT NULL auto_increment,
-   blog_id int(10) unsigned default NULL,
-   total_spam int(10) unsigned default NULL,
-   total_nonspam int(10) unsigned default NULL,
-   PRIMARY KEY  (id),
-   KEY blog_id (blog_id)
-   ) TYPE=MyISAM;";
-
-   $Tables[20]["desc"] = "Bayesian Filter Information";
-   $Tables[20]["code"] = "CREATE TABLE {dbprefix}bayesian_tokens (
-   id int(10) unsigned NOT NULL auto_increment,
-   blog_id int(10) unsigned default NULL,
-   token char(100) default NULL,
-   spam_occurrences int(10) unsigned default NULL,
-   nonspam_occurrences int(10) unsigned default NULL,
-   prob float default NULL,
-   PRIMARY KEY  (id),
-   KEY blog_id (blog_id),
-   KEY token (token)
-   ) TYPE=MyISAM;";
-
-   $Tables[21]["desc"] = "Map of categories to articles";
-   $Tables[21]["code"] = "CREATE TABLE {dbprefix}article_categories_link(
-   article_id int(10) NOT NULL,
-   category_id int(10) NOT NULL,
-   PRIMARY KEY (article_id, category_id)
-   ) TYPE=MyISAM;";
-
-   $Tables[22]["desc"] = "Definition of custom fields";
-   $Tables[22]["code"] = "CREATE TABLE {dbprefix}custom_fields_definition (
-   id int(10) NOT NULL auto_increment,
-   field_name varchar(255) NOT NULL default '',
-   field_description text NOT NULL,
-   field_type int(2) NOT NULL default '1',
-   blog_id int(10) NOT NULL default '0',
-   date TIMESTAMP(14),
-   searchable TINYINT(1) default 1,
-   hidden TINYINT(1) default 1,
-   PRIMARY KEY  (id,field_name),
-   KEY blog_id (blog_id)
-   ) TYPE=MyISAM;";
-
-   $Tables[23]["desc"] = "Custom fields that have been assigned to articles";
-   $Tables[23]["code"] = "CREATE TABLE {dbprefix}custom_fields_values (
-   id int(10) NOT NULL auto_increment,
-   field_id int(10) NOT NULL default '0',
-   field_value text NOT NULL,
-   normalized_value text NOT NULL,
-   blog_id int(10) default NULL,
-   article_id int(10) default NULL,
-   PRIMARY KEY  (id),
-   FULLTEXT KEY normalized_value (normalized_value),
-   KEY blog_id (blog_id),
-   KEY article_id (article_id),
-   KEY field_id (field_id),
-   KEY blog_id_article_id (blog_id, article_id)
-   ) TYPE=MyISAM;";
-
-   $Tables[24]["desc"] = "Text of the articles";
-   $Tables[24]["code"] = "CREATE TABLE {dbprefix}articles_text (
-   id int(10) NOT NULL auto_increment,
-   article_id int(10) NOT NULL DEFAULT 0,
-   text TEXT NOT NULL DEFAULT '',
-   topic TEXT NOT NULL DEFAULT '',
-   normalized_text TEXT NOT NULL DEFAULT '',
-   normalized_topic TEXT NOT NULL DEFAULT '',
-   mangled_topic text NOT NULL,
-   PRIMARY KEY (id),
-   KEY article_id (article_id),
-   FULLTEXT KEY normalized_text (normalized_text),
-   FULLTEXT KEY normalized_topic (normalized_topic),
-   FULLTEXT KEY normalized_fields (normalized_text, normalized_topic)
-   ) TYPE=MyISAM;";
-   
-   $Tables[25]["desc"] = "PhpBB2 User Integration Table";
-   $Tables[25]["code"] = "CREATE TABLE {dbprefix}phpbb2_users (
-   id int(10) unsigned NOT NULL auto_increment,
-   phpbb_id int(10) unsigned NOT NULL,
-   full_name varchar(255) NOT NULL default '',
-   about text,
-   properties TEXT NOT NULL default '',
-   resource_picture_id integer(10) NOT NULL DEFAULT 0,
-   status INTEGER(10) NOT NULL DEFAULT 0,
-   PRIMARY KEY  (id),
-   UNIQUE KEY phpbb_id(phpbb_id)
-   ) TYPE=MyISAM;";
-   
-   /*** new in 1.1 ***/   
-   $Tables[26]["desc"] = "Blog categories";
-   $Tables[26]["code"] = "CREATE TABLE {dbprefix}blog_categories (
-   id int(10) unsigned NOT NULL auto_increment,
-   name varchar(255) NOT NULL default '',
-   description varchar(255) NOT NULL default '',
-   mangled_name varchar(255) NOT NULL default '',
-   properties TEXT NOT NULL DEFAULT '',
-   num_blogs int(10) NOT NULL default '0',
-   PRIMARY KEY (id),
-   KEY mangled_name(mangled_name)
-   ) TYPE=MyISAM;";
-
-   // ---
-
-   // ---
-   // end of changes needed in 1.0
-   // ---
-
-$Inserts[0] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('comments_enabled','1',1);";
-$Inserts[1] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('rdf_enabled','1',1);";
-$Inserts[2] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('temp_folder','./tmp',3);";
-$Inserts[3] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('base_url','{plog_base_url}',3);";
-$Inserts[4] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('show_posts_max','15',1);";
-$Inserts[5] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('recent_posts_max','10',1);";
-$Inserts[6] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('default_template','standard',3);";
-$Inserts[7] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('template_folder','./templates',3);";
-$Inserts[8] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('default_blog_id','1',1);";
-$Inserts[9] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('default_locale','en_UK',3);";
-$Inserts[10] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('html_allowed_tags_in_comments','<a><i><br><br/><b>',3);";
-$Inserts[11] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('referer_tracker_enabled','1',1);";
-$Inserts[12] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('rss_parser_enabled','1',1);";
-$Inserts[13] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('show_more_enabled','1',1);";
-$Inserts[14] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('show_more_threshold','150',1);";
-$Inserts[15] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('update_article_reads','1',1);";
-$Inserts[16] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('email_service_enabled','1',1);";
-$Inserts[17] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('post_notification_source_address','noreply at your.host.com',3);";
-$Inserts[18] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('request_format_mode','1',1);";
-$Inserts[19] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('xmlrpc_ping_hosts','a:2:{i:0;s:27:\"http://rpc.weblogs.com/RPC2\";i:1;s:0:\"\";}',5);";
-$Inserts[20] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('trackback_server_enabled','1',1);";
-$Inserts[21] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('htmlarea_enabled','1',1);";
-$Inserts[22] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('plugin_manager_enabled','1',1);";
-$Inserts[23] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('check_email_address_validity','0',1);";
-$Inserts[24] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('summary_page_show_max','15',1);";
-$Inserts[25] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('minimum_password_length','4',1);";
-$Inserts[26] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('templates','a:3:{i:0;s:7:\"blueish\";i:1;s:4:\"grey\";i:2;s:8:\"standard\";}',5);";
-$Inserts[27] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('locales','a:0:{}',5)";
-$Inserts[28] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('email_service_type','php',3);";
-$Inserts[29] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('smtp_host','your.smtp.host.com',3);";
-$Inserts[30] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('smtp_port','25',1);";
-$Inserts[31] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('smtp_use_authentication','0',1);";
-$Inserts[32] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('smtp_username','',3);";
-$Inserts[33] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('smtp_password','',3);";
-$Inserts[34] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('locale_folder','./locale',3);";
-$Inserts[35] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('xmlrpc_ping_enabled','0',1);";
-$Inserts[36] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('path_to_tar','{path_to_tar}',3);";
-$Inserts[37] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('path_to_gzip','{path_to_gzip}',3);";
-$Inserts[38] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('path_to_bz2','{path_to_bz2}',3);";
-$Inserts[39] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('path_to_unzip','{path_to_unzip}',3);";
-$Inserts[40] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('users_can_add_templates',1,1);";
-$Inserts[41] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('maximum_file_upload_size', 2000000, 1);";
-$Inserts[42] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('upload_forbidden_files', '*.php *.php3 *.php4 *.phtml *.htm *.html *.exe *.com *.bat .htaccess *.sh', 3);";
-$Inserts[43] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('comments_order', 1, 1);";
-$Inserts[44] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('security_pipeline_enabled', 1, 1);";
-$Inserts[45] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('maximum_comment_size', 0, 1 );";
-$Inserts[46] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('resources_enabled', 1, 1 );";
-$Inserts[47] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('thumbnail_method', 'gd', 3);";
-$Inserts[48] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('path_to_convert', '{path_to_convert}', 3);";
-$Inserts[49] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('thumbnail_height', 120, 1);";
-$Inserts[50] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('thumbnail_width', 120, 1);";
-$Inserts[51] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('thumbnails_keep_aspect_ratio', 1, 1);";
-$Inserts[52] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('xmlrpc_api_enabled', 1, 1);";
-$Inserts[53] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('uploads_enabled', 1, 1);";
-$Inserts[54] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('default_rss_profile', 'rss090', 3);";
-$Inserts[55] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('bayesian_filter_enabled', 1, 2);";
-$Inserts[56] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('bayesian_filter_spam_probability_treshold', '0.9', 6);";
-$Inserts[57] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('bayesian_filter_nonspam_probability_treshold', '0.2', 6);";
-$Inserts[58] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('bayesian_filter_min_length_token', '3', 1);";
-$Inserts[59] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('bayesian_filter_max_length_token', '100', 1);";
-$Inserts[60] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('bayesian_filter_number_significant_tokens', 15, 1);";
-$Inserts[61] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('bayesian_filter_spam_comments_action', 0, 1 );";
-$Inserts[62] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('ip_address_filter_enabled', 1, 1 );";
-$Inserts[63] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('content_filter_enabled', 1, 1 );";
-$Inserts[64] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('thumbnail_format','same',3);";
-$Inserts[65] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('resources_folder','./gallery/',3);";
-$Inserts[66] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('beautify_comments_text', '1', 1);";
-$Inserts[67] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('disable_apache_error_handler', '0', 1);";
-$Inserts[68] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('show_future_posts_in_calendar', '0', 1);";
-$Inserts[69] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('xhtml_converter_enabled', '1', 1);";
-$Inserts[70] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('xhtml_converter_aggresive_mode_enabled', '0', 1);";
-$Inserts[71] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('search_engine_enabled', '1', 1);";
-$Inserts[72] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('search_in_custom_fields', '1', 1);";
-$Inserts[73] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('search_in_comments', '1', 1);";
-$Inserts[74] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('resources_quota', '0', 1);";
-$Inserts[75] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('category_link_format', '/blog/{blogname}/{catname}$', 3);";
-$Inserts[76] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('blog_link_format', '/blog/{blogname}$', 3);";
-$Inserts[77] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('archive_link_format', '/blog/{blogname}/archives/{year}/?{month}/?{day}', 3);";
-$Inserts[78] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('user_posts_link_format', '/blog/{blogname}/user/{username}$', 3);";
-$Inserts[79] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('post_trackbacks_link_format', '/blog/{blogname}/post/trackbacks/{postname}$', 3);";
-$Inserts[80] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('template_link_format', '/blog/{blogname}/page/{templatename}$', 3);";
-$Inserts[81] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('album_link_format', '/blog/{blogname}/album/{albumname}$', 3);";
-$Inserts[82] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('resource_link_format', '/blog/{blogname}/resource/{albumname}/{resourcename}$', 3);";
-$Inserts[83] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('resource_preview_link_format', '/blog/{blogname}/resource/{albumname}/preview/{resourcename}$', 3);";
-$Inserts[84] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('resource_download_link_format', '/blog/{blogname}/resource/{albumname}/download/{resourcename}$', 3);";
-$Inserts[85] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('permalink_format', '/blog/{blogname}/{catname}/{year}/{month}/{day}/{postname}$', 3);";
-$Inserts[86] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('script_name', 'index.php', 3);";
-$Inserts[87] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('thumbnail_generator_use_smoothing_algorithm', '0', 1);";
-$Inserts[88] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('resource_server_use_http_caching', '1', 1);";
-$Inserts[89] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('medium_size_thumbnail_width', '640', 1);";
-$Inserts[90] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('medium_size_thumbnail_height', '480', 1);";
-$Inserts[91] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('resource_medium_size_preview_link_format', '/blog/{blogname}/resource/{albumname}/preview-med/{resourcename}$', 3);";
-$Inserts[92] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('subdomains_enabled', '0', 1);";
-$Inserts[93] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('include_blog_id_in_url', '1', 1);";
-$Inserts[94] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('send_xmlrpc_pings_enabled_by_default', '1', 1);";
-$Inserts[95] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('forbidden_usernames', 'admin www blog ftp wiki forums', 3);";
-$Inserts[96] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('force_registration_confirmation', '0', 1);";
-$Inserts[97] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('summary_blogs_per_page', '25', 3);";
-$Inserts[98] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('subdomains_base_url', '', 3);";
-$Inserts[99] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('autosave_new_drafts_time_millis', '300000', 3);";
-$Inserts[100] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('save_drafts_via_xmlhttprequest_enabled', '1', 1);";
-$Inserts[101] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('need_email_confirm_registration', '1', 1);";
-$Inserts[102] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('force_one_blog_per_email_account', '0', 1);";
-$Inserts[103] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('summary_show_agreement', '1', 1);";
-$Inserts[104] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('default_time_offset', '0', 3);";
-$Inserts[105] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('template_cache_enabled', '1', 1);";
-$Inserts[106] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('template_http_cache_enabled', '0', 1);";
-$Inserts[107] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('template_http_cache_enabled', '0', 1);";
-$Inserts[108] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('template_compile_check', '1', 1);";
-$Inserts[109] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('update_cached_article_reads', '1', 1);";
-$Inserts[110] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('allow_php_code_in_templates', '0', 1);";
-$Inserts[111] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('thumbnail_generator_use_smoothing_algorithm', '1', 1);";
-$Inserts[112] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('template_cache_lifetime', '-1', 3);";
-$Inserts[113] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('use_http_accept_language_detection', '0', 1);";
-
-    /**
-     * Open a connection to the database
-     */
-     function connectDb( $ignoreError = false , $selectDatabase = true )
-     {
-        $config = new ConfigFileStorage();
-        // open a connection to the database
-        //$db = NewADOConnection('mysql');
-        $db = PDb::getDriver('mysql');
-        if ( $selectDatabase ) {
-            $res = $db->Connect($config->getValue( "db_host" ), $config->getValue( "db_username" ), $config->getValue( "db_password" ), $config->getValue( "db_database" ));
-        } else {
-            $res = $db->Connect($config->getValue( "db_host" ), $config->getValue( "db_username" ), $config->getValue( "db_password" ));
-        }
-
-        if( DB_WIZARD_DEBUG )
-            $db->debug = true;
-
-        // return error
-        if( $ignoreError )
-            return $db;
-
-        if( !$res )
-            return false;
-
-        return $db;
-    }
-
-    /**
-     * Returns the database prefix
-     */
-    function getDbPrefix()
-    {
-        $config = new ConfigFileStorage();
-        return $config->getValue( "db_prefix" );
-    }
-
-    /**
-     * some useful little functions
-     */
-    class WizardTools extends Object
-    {
-       /**
-        * returns true if plog has already been installed before or
-        * false otherwise
-        */
-       function isNewInstallation()
-       {
-           $configFile = new ConfigFileStorage();
-           // if plog hasn't been installed, this file will have empty settings
-           if( $configFile->getValue( "db_host") == "" && $configFile->getValue( "db_username") == "" &&
-               $configFile->getValue( "db_database") == "" && $configFile->getValue( "db_prefix" ) == "" &&
-               $configFile->getValue( "db_password" ) == "" )
-               $isNew = true;
-           else
-               $isNew = false;
-
-           return( $isNew );
-       }
-    }
-
-    /**
-     * Renders a template file.
-     */
-    class WizardView extends View
-    {
-
-        var $_templateName;
-
-        function WizardView( $templateName )
-        {
-            $this->View();
-            $this->_templateName = $templateName;
-        }
-
-        function render()
-        {
-            // build the file name
-            $templateFileName = "wizard/".$this->_templateName.".template";
-
-            //$t = new Template( $templateFileName, "" );
-            $t = new Smarty();
-            $v = new Version();
-            $this->_params->setValue( "version", $v->getVersion());
-            $this->_params->setValue( "projectPage", $v->getProjectPage());
-            $this->_params->setValue( "safeMode", ini_get("safe_mode"));
-            $t->assign( $this->_params->getAsArray());
-            $t->template_dir    = "./templates";
-            $t->compile_dir     = TEMP_FOLDER;
-            $t->cache_dir       = TEMP_FOLDER;
-            $t->use_sub_dirs    = false;
-            $t->caching = false;
-
-            print $t->fetch( $templateFileName );
-        }
-    }
-
-    /**
-     * Gets the information about the database from the user.
-     */
-    class WizardIntro extends Action
-    {
-        function WizardIntro( $actionInfo, $request )
-        {
-            $this->Action( $actionInfo, $request );
-        }
-
-        function perform()
-        {
-            // we can detect whether plog is already installed or not and direct users to the right
-            // place
-            if( WizardTools::isNewInstallation())
-                $this->_view = new WizardView( "intro" );
-            else {
-                Controller::setForwardAction( "Update1" );
-                return false;
-            }
-
-            $this->setCommonData();
-            return true;
-        }
-    }
-
-    /**
-     *
-     * Saves data to the configuration file
-     *
-     */
-    class WizardStepOne extends Action
-    {
-
-        var $_dbServer;
-        var $_dbUser;
-        var $_dbPassword;
-        var $_dbName;
-        var $_dbPrefix;
-
-        function WizardStepOne( $actionInfo, $request )
-        {
-            $this->Action( $actionInfo, $request );
-
-            // data validation
-            $this->registerFieldValidator( "dbServer", new StringValidator());
-            $this->registerFieldValidator( "dbUser", new StringValidator());
-            $this->registerFieldValidator( "dbPassword",  new StringValidator(), true );
-            $this->registerFieldValidator( "dbName", new StringValidator());
-            $this->registerFieldValidator( "dbPrefix", new StringValidator(), true );
-            $errorView = new WizardView( "intro" );
-            $errorView->setErrorMessage( "Some data was incorrect or missing." );
-            $this->setValidationErrorView( $errorView );
-        }
-
-        function perform()
-        {
-            // fetch the data needed from the request
-            $this->_dbServer   = $this->_request->getValue( "dbServer" );
-            $this->_dbUser     = $this->_request->getValue( "dbUser" );
-            $this->_dbPassword = $this->_request->getValue( "dbPassword" );
-            $this->_dbName     = $this->_request->getValue( "dbName" );
-            $this->_skipThis   = $this->_request->getValue( "skipDbInfo" );
-            $this->_dbPrefix   = $this->_request->getValue( "dbPrefix", DEFAULT_DB_PREFIX );
-
-            // we should now save the data to the configuration file, just before
-            // we read it
-            $configFile = new ConfigFileStorage();
-
-            // we expect everything to be fine
-            $errors = false;
-
-            // before doing anything, we should check of the configuration file is
-            // writable by this script, or else, throw an error and bail out gracefully
-            $configFileName = $configFile->getConfigFileName();
-            if( !File::exists( $configFileName )) {
-                if (! File::touch( $configFileName ) ) {
-                    $this->_view = new WizardView( "intro" );
-                    $message = "Could not create the pLog configuration file $configFileName. Please make sure
-                                that the file can be created by the user running the webserver. It is needed to
-                                store the database configuration settings.";
-                    $this->_view->setErrorMessage( $message );
-                    $this->setCommonData( true );
-                    return false;
-                } else {
-                    ConfigFileStorage::createConfigFile( $configFileName );
-                }
-            }
-            if( File::exists( $configFileName ) && !File::isWritable( $configFileName )) {
-                $this->_view = new WizardView( "intro" );
-                $message = "Please make sure that the file $configFileName can be written by this script during
-                            the installation process. It is needed to store the database configuration settings. Once the
-                            installation is complete, please revert the permissions to no writing possible.";
-                $this->_view->setErrorMessage( $message );
-                $this->setCommonData( true );
-                return false;
-            }
-
-            // continue if everything went fine
-            if( !$configFile->saveValue( "db_username", $this->_dbUser ) ||
-                !$configFile->saveValue( "db_password", $this->_dbPassword ) ||
-                !$configFile->saveValue( "db_host", $this->_dbServer ) ||
-                !$configFile->saveValue( "db_database", $this->_dbName ) ||
-                !$configFile->saveValue( "db_prefix", $this->_dbPrefix )) {
-                $errors = true;
-            }
-
-            if( $errors ) {
-                $message = "Could not save values to the configuration file. Please make sure it is available and
-                            that has write permissions for the user under your web server is running.";
-                $this->_view = new WizardView( "intro" );
-                $this->_view->setErrorMessage( $message );
-
-                return( false );
-            }
-            else {
-                $this->_view = new WizardView( "step1" );
-
-                // now we better read the information from the config file to make sure that
-                // it has been correctly saved
-                $this->setCommonData( true );
-
-                return true;
-            }
-        }
-    }
-
-    /**
-     *
-     * Second step where we connect to the database and create the tables.
-     *
-     */
-    class WizardStepTwo extends Action
-    {
-
-        var $_db;
-        var $_database;
-        var $_createDatabase;
-
-        function setDbConfigValues( &$view )
-        {
-            $configFile = new ConfigFileStorage();
-            $configFile->reload();
-            $view->setValue( "dbUser", $configFile->getValue( "db_username" ));
-            $view->setValue( "dbPassword", $configFile->getValue( "db_password" ));
-            $view->setValue( "dbServer", $configFile->getValue( "db_host" ));
-            $view->setValue( "dbName", $configFile->getValue( "db_database" ));
-            $view->setValue( "dbPrefix", $configFile->getValue( "db_prefix" ));
-            return true;
-        }
-
-        function perform()
-        {
-            global $Tables;
-            global $Inserts;
-
-            $createDb = $this->_request->getValue( "createDatabase" );
-
-            // only check for errors in case the database table should already exist!
-            if( !$createDb ) {
-                $connectionEsablished = false;
-
-                // Lets check the 'everything is fine' case first..
-                $this->_db = connectDb();
-                if( $this->_db ) {
-                     $connectionEsablished = true;
-                } else {
-                     $connectionEsablished = false;
-                     $message = "There was an error selecting the database. Please verify the database was already created or check the 'Create database' checkbox.";
-                }
-
-                // We were unable to connect to the db and select the right db.. lets try
-                // just to connect.. maybe the database needs to be created (even though the
-                // user did not check the appropriate box).
-                if ( !$connectionEsablished ) {
-                    $this->_db = connectDb( true, false );
-                    if( !$this->_db ) {
-                         $message = "There was an error connecting to the database. Please check your settings.";
-                    }
-                }
-
-                if ( !$connectionEsablished ) {
-                    $this->_view = new WizardView( "step1" );
-                    $this->setDbConfigValues( $this->_view );
-                    $this->_view->setErrorMessage( $message );
-                    $this->setCommonData( true );
-                    return false;
-                }
-            }
-
-            $config = new ConfigFileStorage();
-            $this->_database = $config->getValue( "db_database" );
-            $this->_dbPrefix = $config->getValue( "db_prefix" );
-
-            // create the database
-            if( $createDb ) {
-                $this->_db = connectDb( false, false );
-                if( !$this->_db->Execute( "CREATE DATABASE ".$this->_database )) {
-                    $message = "Error creating the database: ".$this->_db->ErrorMsg();
-                    $this->_view = new WizardView( "step1" );
-                    $this->setDbConfigValues( $this->_view );
-                    $this->_view->setErrorMessage( $message );
-                    $this->setCommonData( true );
-                    return false;
-                } else {
-                    $message = "Database created successfully.<br/>";
-                }
-            }
-
-            // reconnect using the new database.
-            $config = new ConfigFileStorage();
-            $this->_db->Connect($config->getValue( "db_host" ), $config->getValue( "db_username" ), $config->getValue( "db_password" ), $config->getValue( "db_database" ));
-
-            // create the tables
-            $errors = false;
-            foreach( $Tables as $table ) {
-                $query = str_replace( "{dbprefix}", $this->_dbPrefix, $table["code"] );
-                if( $this->_db->Execute( $query ))
-                    $message .= "Table <strong>".$table["desc"]."</strong> created successfully.<br/>";
-                else {
-                    $message .= "Error creating table: ".$this->_db->ErrorMsg()."<br/>";
-                    $errors = true;
-                }
-            }
-
-            if( $errors ) {
-                $message = "There was an error creating the tables in the database. Please make sure that the user chosen to connect to the database has enough permissions to create tables.<br/><br/>$message";
-                $this->_view = new WizardView( "step1" );
-                $this->_view->setErrorMessage( $message );
-                $this->setDbConfigValues( $this->_view );
-                $this->setCommonData();
-                return false;
-            }
-
-            // try to guess the url where plog is running
-             // try to guess the url where plog is running
-             $httpProtocol = (array_key_exists("HTTPS", $_SERVER) && $_SERVER["HTTPS"] == "on") ? "https://" : "http://";
-             $httpHost = $_SERVER["HTTP_HOST"];
-             $requestUrl = $_SERVER["REQUEST_URI"];
-             $requestUrl = str_replace( "/wizard.php", "", $requestUrl );
-             $plogUrl = $httpProtocol.$httpHost.$requestUrl;
-
-            // Find some of the tools we are going to need (last one is for os x, with fink installed)
-            // TBD: support for Windows specific directories
-            $folders = Array( "/bin/", "/usr/bin/", "/usr/local/bin/", "/sw/bin/" );
-            $finder = new FileFinder();
-            $pathToUnzip = $finder->findBinary( "unzip", $folders );
-            $pathToTar = $finder->findBinary( "tar", $folders);
-            $pathToGzip = $finder->findBinary( "gzip", $folders);
-            $pathToBzip2 = $finder->findBinary( "bzip2", $folders);
-            $pathToConvert = $finder->findBinary( "convert", $folders);
-
-            // and execute some insert's
-            foreach( $Inserts as $insert ) {
-                $query = str_replace( "{dbprefix}", $this->_dbPrefix, $insert );
-                $query = str_replace( "{plog_base_url}", $plogUrl, $query );
-                // replace also the placeholders for the paths to the tools
-                $query = str_replace( "{path_to_tar}", $pathToTar, $query );
-                $query = str_replace( "{path_to_unzip}", $pathToUnzip, $query );
-                $query = str_replace( "{path_to_bz2}", $pathToBzip2, $query );
-                $query = str_replace( "{path_to_gzip}", $pathToGzip, $query );
-                $query = str_replace( "{path_to_convert}", $pathToConvert, $query );
-                $query = str_replace( "{path_to_convert}", $pathToConvert, $query );
-                if( !$this->_db->Execute( $query )) {
-                    $message .= "Error executing code: ".$this->_db->ErrorMsg()."<br/>";
-                    $errors = true;
-                }
-            }
-
-            //
-            // show some information regarding the helper tools we're going to need
-            // and wether they were found or not
-            //
-            $message .= "<br/><b>-- Helper tools --</b><br/>";
-            if( $pathToTar == "" )
-                $message .= "The helper tool 'tar' was not found<br/>";
-            else
-                $message .= "The helper tool 'tar' was found in $pathToTar<br/>";
-            if( $pathToGzip == "" )
-                $message .= "The helper tool 'gzip' was not found<br/>";
-            else
-                $message .= "The helper tool 'gzip' was found in $pathToGzip<br/>";
-            if( $pathToUnzip == "" )
-                $message .= "The helper tool 'unzip' was not found<br/>";
-            else
-                $message .= "The helper tool 'unzip' was found in $pathToUnzip<br/>";
-            if( $pathToBzip2 == "" )
-                $message .= "The helper tool 'bzip2' was not found<br/>";
-            else
-                $message .= "The helper tool 'bzip2' was found in $pathToTar<br/>";
-            if( $pathToConvert == "" )
-                $message .= "The helper tool 'convert' (from the ImageMagick package) was not found<br/>";
-            else
-                $message .= "The helper tool 'convert' (from the ImageMagick package) was found in $pathToConvert<br/>";
-
-            if( $errors ) {
-                $this->_view = new WizardView( "step1" );
-                $this->setDbConfigValues( $this->_view );
-                $message = "There was an error initializing some of the tables. Please make sure that the user chosen to connect to the database has enough permissions to add records to the database.<br/><br/>$message";
-                $this->_view->setErrorMessage( $message );
-                $this->setCommonData();
-            }
-            else {
-                $this->_view = new WizardView( "step2" );
-                $this->_view->setValue( "message", $message );
-            }
-
-            // Scan for locales
-            $locales = new Locales();
-            // find all the new locales that we have not yet stored
-            $f = new LocaleFinder();
-            $newLocaleCodes = $f->find();
-
-            foreach( $newLocaleCodes as $newLocaleCode ) {
-                $res = $locales->addLocale( $newLocaleCode );
-            }
-
-            return true;
-        }
-    }
-
-    /**
-     *
-     * this action only shows some feedback
-     *
-     */
-    class WizardStepThree extends Action
-    {
-        function perform()
-        {
-            $this->_view = new WizardView( "step3" );
-            $this->setCommonData();
-        }
-    }
-
-    /**
-     *
-     * Create the first user in the database
-     *
-     */
-    class WizardStepFour extends Action
-    {
-
-        var $_userName;
-        var $_userPassword;
-        var $_confirmPassword;
-        var $_userEmail;
-        var $_userFullName;
-
-        function WizardStepFour( $actionInfo, $request )
-        {
-            $this->Action( $actionInfo, $request );
-
-            $this->registerFieldValidator( "userName", new StringValidator());
-            $this->registerFieldValidator( "userPassword", new PasswordValidator());
-            $this->registerFieldValidator( "userPasswordCheck", new PasswordValidator());
-            $this->registerFieldValidator( "userEmail", new EmailValidator());
-            $this->registerField( "userFullName" );
-            $view = new WizardView( "step3" );
-            $view->setErrorMessage( "Some data is missing or incorrect" );
-            $this->setValidationErrorView( $view );
-        }
-
-        // creates the user
-        function perform()
-        {
-            $this->_userName = $this->_request->getValue( "userName" );
-            $this->_userPassword = $this->_request->getValue( "userPassword" );
-            $this->_confirmPassword = $this->_request->getValue( "userPasswordCheck" );
-            $this->_userEmail = $this->_request->getValue( "userEmail" );
-            $this->_userFullName = $this->_request->getValue( "userFullName" );
-
-            $db = connectDb();
-
-            if( !$db ) {
-                $this->_view = new WizardView( "step3" );
-                $this->_view->setErrorMessage( "There was an error connecting to the database. Please check your settings." );
-                $this->setCommonData();
-                return false;
-            }
-
-            if( $this->_confirmPassword != $this->_userPassword ) {
-                $this->_view = new WizardView( "step3" );
-                $this->_form->setFieldValidationStatus( "userPasswordCheck", false );
-                $this->setCommonData( true );
-                return false;
-            }
-
-            $dbPrefix = Db::getPrefix();
-
-            $users = new Users();
-            $user = new UserInfo( $this->_userName,
-                                  $this->_userPassword,
-                                  $this->_userEmail,
-                                  "",
-                                  $this->_userFullName);
-            $userId = $users->addUser( $user );
-            if( !$userId ) {
-                $this->_view = new WizardView( "step3" );
-                $message = "There was an error adding the user. Make sure that the user does not already exist in the database (".$users->DbError().")";
-                $this->_view->setErrorMessage( $message );
-                $this->setCommonData();
-                return false;
-            }
-
-            // we also have to execute the code to give administrator privileges to this user
-            $query = "INSERT INTO {$dbPrefix}users_permissions(user_id,blog_id,permission_id) VALUES( $userId, 0, 1 );";
-            $db->Execute( $query );
-
-            $this->_view = new Wizardview( "step4" );
-            $this->_view->setValue( "ownerid", $userId );
-            $this->_view->setValue( "siteLocales", Locales::getLocales());
-            $this->_view->setValue( "defaultLocale", Locales::getDefaultLocale());
-            $ts = new TemplateSets();
-            $this->_view->setValue( "siteTemplates", $ts->getGlobalTemplateSets());
-            $this->setCommonData();
-            return true;
-        }
-
-    }
-
-    class WizardStepFive extends Action
-    {
-
-        var $_blogName;
-        var $_ownerId;
-        var $_blogProperties;
-
-        function WizardStepFive( $actionInfo, $request )
-        {
-              $this->Action( $actionInfo, $request );
-
-              $this->registerFieldValidator( "blogName", new StringValidator());
-              $this->registerFieldValidator( "ownerid", new IntegerValidator());
-              $this->registerFieldValidator( "blogTemplate", new StringValidator());
-              $this->registerFieldValidator( "blogLocale", new StringValidator());
-              $view = new WizardView( "step4" );
-              $view->setErrorMessage( "Some data is missing or incorrect" );
-              $view->setValue( "siteLocales", Locales::getLocales());
-              $ts = new TemplateSets();
-              $view->setValue( "siteTemplates", $ts->getGlobalTemplateSets());
-              $this->setValidationErrorView( $view );
-        }
-
-        function perform()
-        {
-            // retrieve the values from the view
-            $this->_blogName = $this->_request->getValue( "blogName" );
-            $this->_ownerId  = $this->_request->getValue( "ownerid" );
-            $this->_blogProperties = $this->_request->getValue( "properties" );
-            $this->_blogTemplate = $this->_request->getValue( "blogTemplate" );
-            $this->_blogLocale = $this->_request->getValue( "blogLocale" );
-
-            // configure the blog
-            $blogs = new Blogs();
-            $blog = new BlogInfo( $this->_blogName, $this->_ownerId, "", "" );
-            $blog->setProperties( $this->_blogProperties );
-            $blog->setStatus( BLOG_STATUS_ACTIVE );
-            $blogSettings = $blog->getSettings();
-            $blogSettings->setValue( "locale", $this->_blogLocale );
-            $blogSettings->setValue( "template", $this->_blogTemplate );
-            $blog->setSettings( $blogSettings );
-
-            // and now save it to the database
-            $newblogId = $blogs->addBlog( $blog );
-            if( !$newblogId ) {
-                $this->_view = new WizardView( "step4" );
-                $this->_view->setValue( "siteLocales", Locales::getLocales());
-                $ts = new TemplateSets();
-                $this->_view->setValue( "siteTemplates", $ts->getGlobalTemplateSets());
-                $this->_view->setErrorMessage( "There was an error creating the new blog" );
-                $this->setCommonData( true );
-                return false;
-            }
-
-            // if the blog was created, we can add some basic information
-            // add a category
-            $articleCategories = new ArticleCategories();
-            $articleCategory = new ArticleCategory( "General", "", $newblogId, true );
-            $catId = $articleCategories->addArticleCategory( $articleCategory );
-
-            // load the right locale
-            $locale =& Locales::getLocale( $this->_blogLocale );
-            // and load the right text
-            $articleTopic = $locale->tr( "register_default_article_topic" );
-            $articleText  = $locale->tr( "register_default_article_text" );
-            $article = new Article( $articleTopic, $articleText, Array( $catId ), $this->_ownerId, $newblogId, POST_STATUS_PUBLISHED, 0, Array(), "welcome" );
-            $t = new Timestamp();
-            $article->setDateObject( $t );
-            $articles = new Articles();
-            $articles->addArticle( $article );
-
-            // save a few things in the default configuration
-            $config =& Config::getConfig();
-            // default blog id
-            $config->saveValue( "default_blog_id", (int)$newblogId );
-            // default locale
-            $config->saveValue( "default_locale", $this->_blogLocale );
-            // and finally, the default template
-            $config->saveValue( "default_template", $this->_blogTemplate );
-
-            //
-            // detect wether we have GD available and set the blog to use it
-            //
-            if( GdDetector::detectGd()) {
-                $config->saveValue( "thumbnail_method", "gd" );
-                $message = "GD has been detected and set as the backend for dealing with images.";
-            }
-            else {
-                $pathToConvert = $config->getValue( "path_to_convert" );
-                if( $pathToConvert ) {
-                    $config->saveValue( "thumbnail_method", "imagemagick" );
-                    $message = "ImageMagick has been detected and set as the backend for dealing with images.";
-                }
-                else {
-                    // nothing was found, so we'll have to do away with the 'null' resizer...
-                    $config->saveValue( "thumbnail_method", "null" );
-                    $message = "Neither GD nor ImageMagick have been detected in this host so it will not be possible to generate thumbnails from images.";
-                }
-            }
-
-            $this->_view = new WizardView( "step5" );
-            $this->_view->setValue( "message", $message );
-            return true;
-        }
-    }
-
-    //
-    // The following classes take care of updating the database to the last release
-    //
-    // Things that need to be done when going from 0.3.x to 1.0:
-    //
-    // - add the new tables:
-    //     plog_article_categories_link
-    //     plog_custom_fields_definition
-    //     plog_custom_fields_values
-    //
-    // - make modifications to some of the old tables:
-    //     plog_articles
-    //          normalized_text: TEXT
-    //          normalized_topic: TEXT
-    //          mangled_topic: TEXT
-    //          category_id: DROP
-    //          FULLTEXT(normalized_text)
-    //          FULLTEXT(normalized_topic)
-    //          FULLTEXT(normalized_text, normalized_topic)
-    //     plog_articles_categories
-    //          parent_id: INTEGER
-    //          mangled_name: TEXT
-    //          properties: TEXT
-    //     plog_articles_comments
-    //          normalized_text: TEXT
-    //          normalized_topic: TEXT
-    //          FULLTEXT(normalized_text)
-    //          FULLTEXT(normalized_topic)
-    //          FULLTEXT(normalized_text, normalized_topic)
-    //     plog_blogs
-    //          mangled_blog: TEXT
-    //          properties: TEXT
-    //     plog_gallery_albums
-    //          normalized_name: VARCHAR
-    //          normalized_description: TEXT
-    //          mangled_name: VARCHAR
-    //          FULLTEXT(normalized_name)
-    //          FULLTEXT(normalized_description)
-    //          FULLTEXT(normalized_name, normalized_description)
-    //     plog_gallery_resources
-    //          normalized_description: TEXT
-    //          FULLTEXT(normalized_description)
-    //     plog_mylinks
-    //          properties: TEXT
-    //     plog_mylinks_categories
-    //          properties: TEXT
-    //     plog_users
-    //          properties: TEXT
-    //          full_name: VARCHAR
-    //
-    // - for all the articles in the db, fill in the normalized_text, normalized_topic and mangled_topic
-    //   fields using the TextFilter class
-    //
-    // - for all articles in the db, change the status from a string ('published', 'draft', 'deleted') to
-    // an integer (POST_STATUS_{PUBLISHED|DELETED|DRAFT}
-    //
-    // - for all articles and categories, arrange the plog_article_categories_link table so that everything works
-    //   as before
-    //
-    // - for all article categories, fill in the mangled_name field
-    //
-    // - for all comments, fill in the normalized_text and normalized_topic fields
-    //
-    // - for all blogs, fill in the mangled_blog field
-    //
-    // - for all albums, fill in the normalized_name, normalized_description and mangled_name fields
-    //
-    // - for all resources, fill in the normalized_description field
-
-
-    class UpdateStepOne extends Action
-    {
-
-        function perform()
-        {
-            $this->_view = new WizardView( "update1" );
-            WizardStepTwo::setDbConfigValues( $this->_view );
-            $this->setCommonData();
-        }
-    }
-
-    class UpdateStepTwo extends Action
-    {
-
-        var $_db;
-        var $_dbPrefix;
-
-        function validate()
-        {
-            $configFile = new ConfigFileStorage();
-            $this->_dbPrefix = $configFile->getValue( "db_prefix" );
-
-            return true;
-        }
-
-        function perform()
-        {
-            // we need to create the new tables here
-            $newTables = Array( 21, 22, 23, 24 );
-
-            global $Tables;
-            global $Changes;
-            global $Inserts;
-
-            // connect to the db
-            $this->_db = connectDb();
-
-            // store error messages in this var
-            $message = "";
-
-            if( !$this->_db ) {
-                $this->_view = new WizardView( "update1" );
-                WizardStepTwo::setDbConfigValues( $this->_view );
-                $this->_view->setErrorMessage( "There was an error connecting to the database. Please check your settings." );
-                return false;
-            }
-
-            // ---
-            // create the new tables in 1.0
-            // ---
-            // loop only through the new tables
-            foreach( $newTables as $tableId ) {
-                // get info about the table we'd like to use
-                $table = $Tables[$tableId];
-                // and run the query
-                $query = str_replace( "{dbprefix}", $this->_dbPrefix, $table["code"] );
-                if( $this->_db->Execute( $query ))
-                    $message .= "New table <strong>".$table["desc"]."</strong> created successfully.<br/>";
-                else {
-                    $message .= "Error creating table: ".$this->_db->ErrorMsg()."<br/>";
-                    $errors = true;
-                }
-            }
-            if( !$errors ) {
-                $message .= "** New tables created successfully **<br/><br/>";
-            }
-
-            // ---
-            // make changes to the tables that need changes
-            // ---
-            foreach( $Changes as $tableId => $changeTable) {
-                $errorMessage = "";            
-                foreach( $changeTable as $changeCode ) {
-                    // and run the query
-                    $query = str_replace( "{dbprefix}", $this->_dbPrefix, $changeCode );
-                    if( !$this->_db->Execute( $query )) {
-                        $errors = true;                    
-                        $errorMessage .= $this->_db->ErrorMsg()."<br/>";
-                    }
-                }
-
-                if( !$errors )
-                    $message .= "Changes to table <strong>$tableId</strong> executed successfully.<br/>";
-                else {
-                    $message .= "Error modifying table $tableId: ".$errorMessage;
-                }
-            }
-
-            if( !$errors ) {
-                $message .= "** Modifications to old tables carried out successfully **<br/><br/>";
-            }
-
-            // ---
-            // add the new configuration settings that were added for 1.0
-            // ---
-            $newSettings = range( 71, 112 );
-            foreach( $newSettings as $settingId ) {
-                $setting = $Inserts[$settingId];
-                $query = str_replace( "{dbprefix}", $this->_dbPrefix, $setting );
-                if( !$this->_db->Execute( $query )) {
-                    $message .= "There was an error executing: ".$this->_db->ErrorMsg()."<br/>";
-                    $errors = true;
-                }
-            }
-
-            //
-            // there's nothing left to do so we can quit now!!
-            //
-            if( !$errors ) {
-                $this->_view = new WizardView( "update2" );
-                $this->_view->setValue( "message", $message );
-            }
-            else {
-                $this->_view = new WizardView( "update1" );
-                WizardStepTwo::setDbConfigValues( $this->_view );
-                $this->_view->setErrorMessage( $message );
-            }
-
-            return true;
-        }
-    }
-
-    /**
-     * this is the first step of the transformations to some of the fields in the tables.
-     * Precisely, it is in this step where we regenerate the indexes for the search engine... However, it
-     * could take it a while...
-     */
-    class UpdateStepThree extends Action
-    {
-        function UpdateStepThree( $actionInfo, $httpRequest )
-        {
-            $this->Action( $actionInfo, $httpRequest );
-
-            // load the current step, if any
-            $this->_curStep = $this->_request->getValue( "curStep" );
-            $this->_numPosts = $this->_request->getValue( "numPosts" );
-
-            //print("cur step = ".$this->_curStep." - num posts = ".$this->_numPosts."<br/>");
-        }
-
-        function getStatusId( $statusStr )
-        {
-            if( $statusStr == 'published' ) return POST_STATUS_PUBLISHED;
-            if( $statusStr == 'draft' ) return POST_STATUS_DRAFT;
-            if( $statusStr == 'deleted' ) return POST_STATUS_DELETED;
-
-            return false;
-        }
-
-       function perform()
-       {
-            // get a connection to the db
-            $db = connectDb();
-            $dbPrefix = getDbPrefix();
-            $db->debug=false;
-
-            // no errors here
-            $errors = false;
-
-            // see how many records we have
-            $queryCount = "SELECT COUNT(*) AS total FROM {$dbPrefix}articles";
-            $result = $db->Execute( $queryCount );
-            $row = $result->FetchRow();
-            $numRecords = $row["total"];
-            $this->_totalPosts = $numRecords;
-            // check whether we should use multiple steps
-            $multipleSteps = ( $numRecords > WIZARD_MAX_RECORDS_THRESHOLD );
-            if( $multipleSteps ) {
-                // how many steps do we need?
-                $numSteps = ceil( $numRecords / WIZARD_MAX_RECORDS_PER_STEP );
-                $this->_numSteps = $numSteps;
-                //print("using different steps! numSteps = $numSteps<br/>");
-            }
-
-            // run the query and loop through the results
-            $query = "SELECT * FROM {$dbPrefix}articles";
-            if( $multipleSteps ) {
-                // generate the LIMIT condition for this page
-                $query .= " LIMIT ".$this->_curStep*WIZARD_MAX_RECORDS_PER_STEP.", ".WIZARD_MAX_RECORDS_PER_STEP;
-            }
-
-            //print("query = $query<br/>");
-
-            $result = $db->Execute( $query );
-
-            $tf = new TextFilter();
-
-            $numPosts = $result->RowCount();
-
-            while( $row = $result->FetchRow()) {
-                // for each one of the articles, fill in the mangled_topic, normalized_text and normalized_value
-                $normalizedTopic = Db::qstr($tf->normalizeText( $row["topic"] ));
-                $postTopic       = Db::qstr($row["topic"]);
-                $normalizedText  = Db::qstr($tf->normalizeText( $row["text"] ));
-                $postText        = Db::qstr($row["text"]);
-                $mangledTopic    = Db::qstr($tf->urlize( $row["topic"] ));
-                $status          = $this->getStatusId( $row["old_status"] );
-                $artId           = $row["id"];
-                $catId           = $row["category_id"];
-
-                $query = "UPDATE {$dbPrefix}articles SET slug = '$mangledTopic', date = date, status = $status
-                          WHERE id = $artId";
-
-                $query2= "INSERT INTO {$dbPrefix}article_categories_link(article_id, category_id)
-                          VALUES ( $artId, $catId )";
-
-                $query3= "INSERT INTO {$dbPrefix}articles_text (article_id,text,topic,normalized_text,normalized_topic,mangled_topic)
-                          VALUES('$artId','$postText','$postTopic','$normalizedTopic','$normalizedText','$mangledTopic')";
-
-
-                // execute the two queries
-                $res  = $db->Execute( $query );
-                $res2 = $db->Execute( $query2 );
-                $res3 = $db->Execute( $query3 );
-
-                /*if( !$res || !$res2 || !$res3 )
-                    $errors = true;*/
-            }
-
-            // check whether we've already done the last step or not
-            $lastStepDone = ( $this->_curStep >= $this->_numSteps );
-
-            // if error
-            if( $errors ) {
-                $this->_view = new WizardView( "update2" );
-                $this->_view->setErrorMessage( "There was an error updating the articles table." );
-                $this->setCommonData();
-                return false;
-            }
-
-            //$query1 = "ALTER TABLE {$dbPrefix}articles DROP COLUMN old_status, DROP COLUMN category_id";
-            //$db->Execute( $query1 );
-
-            // if everyhting's fine, say so...
-            if( !$multipleSteps || $lastStepDone ) {
-                $this->_view = new WizardView( "update3" );
-                $this->_view->setValue( "totalPosts", $this->_totalPosts );
-            }
-            else {
-                // if we're using multiple steps, show the same page
-                $this->_view = new WizardView( "update2" );
-                $this->_view->setValue( "numPosts", $numPosts );
-                $this->_view->setValue( "curStep", $this->_curStep+1 );
-                $this->_view->setValue( "totalPosts", $this->_totalPosts );
-                $this->_view->setValue( "numSteps", $this->_numSteps );
-                $this->_view->setValue( "multipleSteps", true );
-            }
-
-            return true;
-        }
-
-    }
-
-    // ---
-    // this action will do the same as before but for the rest of the tables that need some data to
-    // be normalized/mangled
-    // ---
-    class UpdateStepFour extends Action
-    {
-
-        var $dbPrefix;
-        var $db;
-        var $t;
-
-        function validate()
-        {
-            $this->db = connectDb();
-            $this->dbPrefix = getDbPrefix();
-            $this->t = new TextFilter();
-
-            return true;
-        }
-
-        //
-        // process the article categories
-        //
-        function updateArticleCategories()
-        {
-            $dbPrefix = $this->dbPrefix;
-            $query = "SELECT * FROM {$dbPrefix}articles_categories";
-            $result = $this->db->Execute( $query );
-
-            while( $row = $result->FetchRow()) {
-                $catId = $row["id"];
-                $mangledName = $this->t->urlize( $row["name"] );
-                $query = "UPDATE {$dbPrefix}articles_categories
-                          SET mangled_name = '$mangledName', last_modification = last_modification
-                          WHERE id = $catId";
-
-                $res = $this->db->Execute( $query );
-
-                // this is not very nice to see but it works... :)
-                if( !$res ) {
-                    $this->message .= "There was an error updating the article categories table.<br/>";
-                    return false;
-                }
-            }
-
-            $this->message .= "Article Categories table updated successfully!<br/>";
-
-            return true;
-        }
-
-        //
-        // process the comments
-        //
-        function updateArticleComments()
-        {
-            $dbPrefix = $this->dbPrefix;
-            $query = "SELECT * FROM {$dbPrefix}articles_comments";
-            $result = $this->db->Execute( $query );
-
-            while( $row = $result->FetchRow()) {
-                $commentId = $row["id"];
-                $normText = Db::qstr($this->t->normalizeText( $row["text"] ));
-                $normTopic = Db::qstr($this->t->normalizeText( $row["topic"] ));
-                $query = "UPDATE {$dbPrefix}articles_comments
-                          SET normalized_text = '$normText', normalized_topic = '$normTopic', date = date
-                          WHERE id = $commentId";
-
-                $res = $this->db->Execute( $query );
-
-                if( !$res ) {
-                    $this->message .= "There was an error updating the comments table.<br/>";
-                    return false;
-                }
-            }
-
-            $this->message .= "Comments table updated successfully!<br/>";
-
-            return true;
-        }
-
-        //
-        // process the blogs
-        //
-        function updateBlogs()
-        {
-            $dbPrefix = $this->dbPrefix;
-            $query = "SELECT * FROM {$dbPrefix}blogs";
-            $result = $this->db->Execute( $query );
-
-            while( $row = $result->FetchRow()) {
-                $blogId = $row["id"];
-                $mangledBlog = $this->t->urlize( $row["blog"] );
-                $query = "UPDATE {$dbPrefix}blogs
-                          SET mangled_blog = '$mangledBlog' WHERE id = $blogId";
-
-                $res = $this->db->Execute( $query );
-
-                if( !$res ) {
-                    $this->message .= "There wasn an error updaing the blogs table.<br/>";
-                    return false;
-                }
-            }
-
-            $this->message .= "Blogs table updated successfully!<br/>";
-
-            return true;
-        }
-
-        //
-        // process the albums
-        //
-        function updateAlbums()
-        {
-            $dbPrefix = $this->dbPrefix;
-            $query = "SELECT * FROM {$dbPrefix}gallery_albums";
-            $result = $this->db->Execute( $query );
-
-            while( $row = $result->FetchRow()) {
-                $albumId = $row["id"];
-                $mangledName = Db::qstr($this->t->urlize( $row["name"] ));
-                $normName = Db::qstr($this->t->normalizeText( $row["name"] ));
-                $normDescription = Db::qstr($this->t->normalizeText( $row["description"] ));
-                $query = "UPDATE {$dbPrefix}gallery_albums
-                          SET mangled_name = '$mangledName', normalized_name = '$normName',
-                          normalized_description = '$normDescription', date = date
-                          WHERE id = $albumId";
-
-                $res = $this->db->Execute( $query );
-
-                if( !$res ) {
-                    $this->message .= "There was an error updating the albums table.<br/>";
-                    return false;
-                }
-            }
-
-            $this->message .= "Resource Albums table updated successfully!<br/>";
-
-            return true;
-        }
-
-        //
-        // and finally, the resources...
-        //
-        function updateResources()
-        {
-            $dbPrefix = $this->dbPrefix;
-            $query = "SELECT * FROM {$dbPrefix}gallery_resources";
-            $result = $this->db->Execute( $query );
-
-            while( $row = $result->FetchRow()) {
-                $resId = $row["id"];
-                //$normName = $this->t->normalizeText( $row["name"] );
-                $normDescription = Db::qstr($this->t->normalizeText( $row["description"] ));
-                $query = "UPDATE {$dbPrefix}gallery_resources
-                          SET normalized_description = '$normDescription', date = date
-                          WHERE id = $resId";
-
-                $res = $this->db->Execute( $query );
-                if( !$res ) {
-                    $this->message .= "There was an error updating the resources table.<br/>";
-                    return false;
-                }
-            }
-
-            $this->message .= "Resources table updated successfully!<br/>";
-
-            return true;
-
-        }
-
-        //
-        // process the articles' text
-        //
-        function updateArticleText()
-        {
-            $dbPrefix = $this->dbPrefix;
-            // drop unneeded columns from articles table
-            $alter_query[] = "ALTER TABLE ".$dbPrefix."articles DROP COLUMN text";
-            $alter_query[] = "ALTER TABLE ".$dbPrefix."articles DROP COLUMN topic";
-
-            foreach ($alter_query as $value) {
-                $this->db->Execute($value);
-            }
-
-
-            $this->message .= "articles_text table updated successfully!<br/>";
-
-            return true;
-        }
-
-        function perform()
-        {
-            $updaters = Array( "updateArticleCategories", "updateArticleComments",
-                               "updateBlogs", "updateAlbums", "updateResources", "updateArticleText" );
-
-            // loop through each one of the methods to take care of updating one of the tables
-            foreach( $updaters as $method ) {
-                $result = $this->$method();
-
-                if( !$result ) {
-                    $this->_view = new WizardView( "update3" );
-                    $this->_view->setErrorMessage( $this->message );
-                    return false;
-                }
-            }
-
-            // everything went fine so we can show the final page!
-            $this->_view = new WizardView( "update4" );
-            $this->_view->setValue( "message", $this->message );
-
-            return true;
-        }
-
-    }
-
-    // check if the "./tmp" folder is writable by us, otherwise
-    // throw an error before the user gets countless errors
-    // from Smarty
-    if( !File::isWritable( TEMP_FOLDER ) || !File::isDir( TEMP_FOLDER )) {
-        print("<span style=\"color:red; font-size: 14px;\">Error</span><br/><br/>This wizard needs the ".TEMP_FOLDER." folder to be writable by the web server user.<br/><br/>Please correct that and try again.");
-        die();
-    }
-
-    //// main part ////
-    $controller = new Controller( $_actionMap, "nextStep" );
-    $controller->process( HttpVars::getRequest());
-?>
+<?php
+
+    if (!defined( "PLOG_CLASS_PATH" )) {
+        define( "PLOG_CLASS_PATH", dirname(__FILE__)."/");
+    }
+
+    set_time_limit (5 * 3600);
+
+    //
+    // enable this for debugging purposes
+    //
+    define( "DB_WIZARD_DEBUG", false );
+
+    //
+    // in case you're having problems with time outs while upgrading (probably too
+    // many records) lower this figure
+    //
+    define( "WIZARD_MAX_RECORDS_PER_STEP", 50 );
+
+    //
+    // threshold that defines up to how many records we should not divide the
+    // transformations in more than one step
+    //
+    define( "WIZARD_MAX_RECORDS_THRESHOLD", 100 );
+
+    // many hosts don't have this enabled and we, for the time being, need it...
+    ini_set("arg_seperator.output", "&amp;");
+
+    include_once( PLOG_CLASS_PATH."class/controller/controller.class.php" );
+    include_once( PLOG_CLASS_PATH."class/template/templateservice.class.php" );
+    include_once( PLOG_CLASS_PATH."class/action/action.class.php" );
+    include_once( PLOG_CLASS_PATH."class/database/db.class.php" );
+    include_once( PLOG_CLASS_PATH."class/template/template.class.php" );
+    include_once( PLOG_CLASS_PATH."class/view/view.class.php" );
+    include_once( PLOG_CLASS_PATH."class/data/validator/stringvalidator.class.php" );
+    include_once( PLOG_CLASS_PATH."class/data/validator/integervalidator.class.php" );
+    include_once( PLOG_CLASS_PATH."class/data/validator/emailvalidator.class.php" );
+    include_once( PLOG_CLASS_PATH."class/data/validator/passwordvalidator.class.php" );
+    include_once( PLOG_CLASS_PATH."class/dao/users.class.php" );
+    include_once( PLOG_CLASS_PATH."class/dao/blogs.class.php" );
+    include_once( PLOG_CLASS_PATH."class/dao/articlecategories.class.php" );
+    include_once( PLOG_CLASS_PATH."class/dao/articles.class.php" );
+    include_once( PLOG_CLASS_PATH."class/net/http/httpvars.class.php" );
+    include_once( PLOG_CLASS_PATH."class/dao/userpermissions.class.php" );
+    include_once( PLOG_CLASS_PATH."class/misc/version.class.php" );
+    include_once( PLOG_CLASS_PATH."class/file/file.class.php" );
+    include_once( PLOG_CLASS_PATH."class/file/finder/filefinder.class.php" );
+    include_once( PLOG_CLASS_PATH."class/gallery/resizers/gddetector.class.php" );
+    include_once( PLOG_CLASS_PATH."class/config/configfilestorage.class.php" );
+    include_once( PLOG_CLASS_PATH."class/data/textfilter.class.php" );
+    include_once( PLOG_CLASS_PATH."class/locale/locales.class.php" );
+    include_once( PLOG_CLASS_PATH."class/locale/localefinder.class.php" );
+    include_once( PLOG_CLASS_PATH."class/template/templatesets/templatesets.class.php" );
+    include_once( PLOG_CLASS_PATH."class/dao/bloginfo.class.php" );
+    include_once( PLOG_CLASS_PATH."class/dao/article.class.php" );
+
+    define( "TEMP_FOLDER", "./tmp" );
+
+    // sql querys used to create the tables
+
+    // maps used to map requests with actions
+    $_actionMap["Default"] = "WizardIntro";
+    $_actionMap["Intro"] = "WizardIntro";
+    $_actionMap["Step1"] = "WizardStepOne";
+    $_actionMap["Step2"] = "WizardStepTwo";
+    $_actionMap["Step3"] = "WizardStepThree";
+    $_actionMap["Step4"] = "WizardStepFour";
+    $_actionMap["Step5"] = "WizardStepFive";
+    $_actionMap["Update1"] = "UpdateStepOne";
+    $_actionMap["Update2"] = "UpdateStepTwo";
+    $_actionMap["Update3"] = "UpdateStepThree";
+    $_actionMap["Update4"] = "UpdateStepFour";
+
+
+
+    $Tables[0]["desc"] = "Articles";
+    $Tables[0]["code"] = "CREATE TABLE {dbprefix}articles (
+  id int(10) unsigned NOT NULL auto_increment,
+  category_id int(10) unsigned NOT NULL default '0',
+  date timestamp(14) NOT NULL,
+  modification_date timestamp(14) NOT NULL,
+  user_id int(10) unsigned NOT NULL default '0',
+  blog_id int(10) unsigned NOT NULL default '0',
+  status INTEGER(5) NOT NULL default 1,
+  num_reads int(10) default '0',
+  properties TEXT NOT NULL default '',
+  slug varchar(255) NOT NULL,
+  num_comments int(10) NOT NULL default '0', 
+  num_nonspam_comments int(10) NOT NULL default '0', 
+  num_trackbacks int(10) NOT NULL default '0',
+  num_nonspam_trackbacks int(10) NOT NULL default '0',
+  PRIMARY KEY (id),
+  KEY num_reads (num_reads),
+  KEY category_id (category_id),
+  KEY blog_id (blog_id),
+  KEY user_id (user_id),
+  KEY slug (slug),
+  KEY blog_id_slug (blog_id,slug),
+  KEY blog_id_slug_category_id (blog_id,slug,category_id)
+) TYPE=MyISAM;";
+
+    $Tables[1]["desc"] = "Article categories";
+    $Tables[1]["code"] = "CREATE TABLE {dbprefix}articles_categories (
+  id int(10) unsigned NOT NULL auto_increment,
+  name varchar(255) NOT NULL default '',
+  url varchar(255) NOT NULL default '',
+  blog_id int(10) unsigned NOT NULL default '0',
+  last_modification timestamp(14) NOT NULL,
+  in_main_page TINYINT(1) NOT NULL DEFAULT '1',
+  parent_id INTEGER(10) NOT NULL DEFAULT '0',
+  description TEXT NOT NULL DEFAULT '',
+  properties text NOT NULL default '',
+  mangled_name varchar(255) NOT NULL default '',
+  num_articles int(10) NOT NULL default 0,
+  num_published_articles int(10) NOT NULL default 0,
+  PRIMARY KEY  (id),
+  KEY parent_id (parent_id),
+  KEY blog_id (blog_id),
+  KEY mangled_name (mangled_name)
+) TYPE=MyISAM;";
+
+    $Tables[2]["desc"] = "Comments";
+    $Tables[2]["code"] = "CREATE TABLE {dbprefix}articles_comments (
+  id int(10) unsigned NOT NULL auto_increment,
+  article_id int(10) unsigned NOT NULL default '0',
+  blog_id int(10) unsigned NOT NULL default '0',
+  topic text NOT NULL,
+  text text,
+  date timestamp(14) NOT NULL,
+  user_email varchar(255) default '',
+  user_url varchar(255) default '',
+  user_name varchar(255) NOT NULL default 'Anonymous',
+  parent_id int(10) unsigned default '0',
+  client_ip varchar(15) default '0.0.0.0',
+  send_notification tinyint(1) default '0',
+  status tinyint(2) default '1',
+  spam_rate float default '0',
+  properties TEXT NOT NULL DEFAULT '',
+  normalized_text TEXT NOT NULL DEFAULT '',
+  normalized_topic TEXT NOT NULL DEFAULT '',
+  type int(3) NOT NULL DEFAULT '0',  
+  PRIMARY KEY  (id),
+  KEY parent_id (parent_id),
+  KEY article_id (article_id),
+  KEY blog_id (blog_id),
+  KEY article_id_blog_id(article_id,blog_id),
+  FULLTEXT KEY normalized_fields (normalized_text,normalized_topic),
+  FULLTEXT KEY normalized_text (normalized_text),
+  FULLTEXT KEY normalized_topic (normalized_topic)
+) TYPE=MyISAM;";
+
+    $Tables[3]["desc"] = "Notifications";
+    $Tables[3]["code"] = "CREATE TABLE {dbprefix}articles_notifications (
+  id int(10) NOT NULL auto_increment,
+  blog_id int(10) NOT NULL default '0',
+  user_id int(10) NOT NULL default '0',
+  article_id int(10) NOT NULL default '0',
+  PRIMARY KEY  (id),
+  KEY article_id (article_id),
+  KEY user_id (user_id),
+  KEY blog_id (blog_id)
+) TYPE=MyISAM;";
+
+    $Tables[4]["desc"] = "Blogs";
+    $Tables[4]["code"] = "CREATE TABLE {dbprefix}blogs (
+  id int(10) unsigned NOT NULL auto_increment,
+  blog varchar(50) NOT NULL default '',
+  owner_id int(10) unsigned NOT NULL default '0',
+  blog_category_id int(10) unsigned NOT NULL default '0',
+  about text,
+  settings text NOT NULL,
+  mangled_blog varchar(50) NOT NULL default '',
+  status int(4) NOT NULL default '1',
+  show_in_summary int(4) not null default '1',
+  create_date TIMESTAMP(14) NOT NULL,
+  last_update_date TIMESTAMP(14) NOT NULL,
+  num_posts int(10) NOT NULL DEFAULT '0',
+  num_comments int(10) NOT NULL DEFAULT '0',
+  num_trackbacks int(10) NOT NULL DEFAULT '0',
+  PRIMARY KEY  (id),
+  KEY owner_id (owner_id),
+  KEY mangled_blog (mangled_blog),
+  KEY blog_category_id(blog_category_id)
+) TYPE=MyISAM;";
+
+    $Tables[5]["desc"] = "MyLinks";
+    $Tables[5]["code"] = "CREATE TABLE {dbprefix}mylinks (
+  id int(10) unsigned NOT NULL auto_increment,
+  category_id int(10) unsigned NOT NULL default '0',
+  url varchar(255) NOT NULL default '',
+  name varchar(100) default '',
+  description text NOT NULL,
+  blog_id int(10) unsigned NOT NULL default '0',
+  rss_feed varchar(255) not null default '',
+  date timestamp(14) not null,
+  properties TEXT NOT NULL DEFAULT '',
+  PRIMARY KEY  (id),
+  KEY blog_id (blog_id),
+  KEY category_id (category_id)
+) TYPE=MyISAM;";
+
+    $Tables[6]["desc"] = "MyLinks Categories";
+    $Tables[6]["code"] = "CREATE TABLE {dbprefix}mylinks_categories (
+  id int(10) NOT NULL auto_increment,
+  name varchar(100) NOT NULL default '',
+  blog_id int(10) NOT NULL default '0',
+  last_modification timestamp(14) NOT NULL,
+  properties TEXT NOT NULL DEFAULT '',
+  num_links int(10) NOT NULL default '0',
+  PRIMARY KEY  (id),
+  KEY blog_id (blog_id)
+) TYPE=MyISAM;";
+
+    $Tables[9]["desc"] = "Permissions";
+    $Tables[9]["code"] = "CREATE TABLE {dbprefix}permissions (
+  id int(10) unsigned NOT NULL auto_increment,
+  permission varchar(25) NOT NULL default '',
+  description varchar(100) NOT NULL default '',
+  PRIMARY KEY  (id)
+) TYPE=MyISAM;";
+
+    $Tables[10]["desc"] = "Referrers";
+    $Tables[10]["code"] = "CREATE TABLE {dbprefix}referers (
+  id int(10) NOT NULL auto_increment,
+  url text NOT NULL,
+  article_id int(10) NOT NULL default '0',
+  blog_id int(10) NOT NULL default '0',
+  hits int(10) default '1',
+  last_date timestamp(14),
+  PRIMARY KEY  (id),
+  KEY article_id (article_id),
+  KEY blog_id (blog_id),
+  KEY blog_id_article_id (blog_id, article_id)
+) TYPE=MyISAM;";
+
+    $Tables[12]["desc"] = "Users";
+    $Tables[12]["code"] = "CREATE TABLE {dbprefix}users (
+  id int(10) unsigned NOT NULL auto_increment,
+  user varchar(15) NOT NULL default '',
+  password varchar(32) NOT NULL default '',
+  email varchar(255) NOT NULL default '',
+  full_name varchar(255) NOT NULL default '',
+  about text,
+  properties TEXT NOT NULL default '',
+  status integer(4) NOT NULL DEFAULT 1,
+  resource_picture_id integer(10) NOT NULL DEFAULT 0,
+  site_admin int(10) NOT NULL default '0',
+  PRIMARY KEY  (id),
+  UNIQUE KEY user (user)
+) TYPE=MyISAM;";
+
+    $Tables[13]["desc"] = "Permissions";
+    $Tables[13]["code"] = "CREATE TABLE {dbprefix}users_permissions (
+  id int(10) unsigned NOT NULL auto_increment,
+  user_id int(10) unsigned NOT NULL default '0',
+  blog_id int(10) unsigned NOT NULL default '0',
+  permission_id int(10) unsigned NOT NULL default '0',
+  PRIMARY KEY  (id),
+  KEY user_id (user_id),
+  KEY blog_id (blog_id),
+  KEY user_id_permission_id (user_id,permission_id)
+) TYPE=MyISAM;";
+
+
+   $Tables[14]["desc"] = "Configuration";
+   $Tables[14]["code"] = "CREATE TABLE {dbprefix}config (
+   id int(10) NOT NULL auto_increment,
+   config_key varchar(255) NOT NULL default '',
+   config_value text NOT NULL,
+   value_type int(3) default '0',
+   PRIMARY KEY  (id,config_key)
+   ) TYPE=MyISAM;";
+
+   $Tables[15]["desc"] = "Filtered Content";
+   $Tables[15]["code"] = "CREATE TABLE {dbprefix}filtered_content (
+   id int(10) NOT NULL auto_increment,
+   reg_exp text,
+   blog_id int(10) NOT NULL default '0',
+   reason text,
+   date timestamp(14) NOT NULL,
+   PRIMARY KEY  (id),
+   KEY blog_id (blog_id)
+   ) TYPE=MyISAM;";
+
+   $Tables[16]["desc"] = "Blocked content";
+   $Tables[16]["code"] = "CREATE TABLE {dbprefix}host_blocking_rules (
+   id int(10) NOT NULL auto_increment,
+   reason text,
+   date timestamp(14) NOT NULL,
+   blog_id int(10) NOT NULL default '0',
+   block_type int(1) default '1',
+   list_type int(1) default '1',
+   mask int(2) default '0',
+   host varchar(15) default '0.0.0.0',
+   PRIMARY KEY  (id),
+   KEY blog_id (blog_id)
+   ) TYPE=MyISAM;";
+
+   $Tables[17]["desc"] = "Gallery Resources";
+   $Tables[17]["code"] = "CREATE TABLE {dbprefix}gallery_resources (
+   id int(10) NOT NULL auto_increment,
+   owner_id int(10) NOT NULL default '0',
+   album_id int(10) NOT NULL default '0',
+   description text,
+   date timestamp(14) NOT NULL,
+   flags int(10) default '0',
+   resource_type int(3) default NULL,
+   file_path varchar(255) default '',
+   file_name varchar(255) default '',
+   file_size int(20) not null default 0,
+   metadata text,
+   thumbnail_format varchar(4) not null default 'same',
+   normalized_description text NOT NULL default '',
+   properties TEXT NOT NULL DEFAULT '',
+   PRIMARY KEY  (id),
+   KEY album_id (album_id),
+   KEY owner_id (owner_id),
+   KEY file_name (file_name),
+   KEY album_id_owner_id (album_id, owner_id),
+   KEY resource_type (resource_type),
+   FULLTEXT KEY normalized_description (normalized_description)
+   ) TYPE=MyISAM;";
+
+   $Tables[18]["desc"] = "Gallery Albums";
+   $Tables[18]["code"] = "CREATE TABLE {dbprefix}gallery_albums (
+   id int(10) NOT NULL auto_increment,
+   owner_id int(10) NOT NULL default '0',
+   description text NOT NULL,
+   name varchar(255) NOT NULL default '',
+   flags int(10) NOT NULL default '0',
+   parent_id int(10) NOT NULL default '0',
+   date timestamp(14) NOT NULL,
+   properties text NOT NULL DEFAULT '',
+   show_album TINYINT(1) DEFAULT 1,
+   normalized_description text NOT NULL default '',
+   normalized_name varchar(255) NOT NULL default '',
+   mangled_name varchar(255) NOT NULL default '',
+   num_resources int(10) NOT NULL default '0',
+   num_children int(10) NOT NULL default '0',
+   PRIMARY KEY  (id),
+   KEY parent_id (parent_id),
+   KEY owner_id (owner_id),
+   KEY mangled_name (mangled_name),
+   KEY owner_id_mangled_name (owner_id, mangled_name),
+   FULLTEXT KEY normalized_name (normalized_name),
+   FULLTEXT KEY normalized_description (normalized_description),
+   FULLTEXT KEY normalized_fields (normalized_name, normalized_description)
+   ) TYPE=MyISAM;";
+
+   $Tables[19]["desc"] = "Bayesian Filter data table";
+   $Tables[19]["code"] = "CREATE TABLE {dbprefix}bayesian_filter_info (
+   id int(10) unsigned NOT NULL auto_increment,
+   blog_id int(10) unsigned default NULL,
+   total_spam int(10) unsigned default NULL,
+   total_nonspam int(10) unsigned default NULL,
+   PRIMARY KEY  (id),
+   KEY blog_id (blog_id)
+   ) TYPE=MyISAM;";
+
+   $Tables[20]["desc"] = "Bayesian Filter Information";
+   $Tables[20]["code"] = "CREATE TABLE {dbprefix}bayesian_tokens (
+   id int(10) unsigned NOT NULL auto_increment,
+   blog_id int(10) unsigned default NULL,
+   token char(100) default NULL,
+   spam_occurrences int(10) unsigned default NULL,
+   nonspam_occurrences int(10) unsigned default NULL,
+   prob float default NULL,
+   PRIMARY KEY  (id),
+   KEY blog_id (blog_id),
+   KEY token (token)
+   ) TYPE=MyISAM;";
+
+   $Tables[21]["desc"] = "Map of categories to articles";
+   $Tables[21]["code"] = "CREATE TABLE {dbprefix}article_categories_link(
+   article_id int(10) NOT NULL,
+   category_id int(10) NOT NULL,
+   PRIMARY KEY (article_id, category_id)
+   ) TYPE=MyISAM;";
+
+   $Tables[22]["desc"] = "Definition of custom fields";
+   $Tables[22]["code"] = "CREATE TABLE {dbprefix}custom_fields_definition (
+   id int(10) NOT NULL auto_increment,
+   field_name varchar(255) NOT NULL default '',
+   field_description text NOT NULL,
+   field_type int(2) NOT NULL default '1',
+   blog_id int(10) NOT NULL default '0',
+   date TIMESTAMP(14),
+   searchable TINYINT(1) default 1,
+   hidden TINYINT(1) default 1,
+   PRIMARY KEY  (id,field_name),
+   KEY blog_id (blog_id)
+   ) TYPE=MyISAM;";
+
+   $Tables[23]["desc"] = "Custom fields that have been assigned to articles";
+   $Tables[23]["code"] = "CREATE TABLE {dbprefix}custom_fields_values (
+   id int(10) NOT NULL auto_increment,
+   field_id int(10) NOT NULL default '0',
+   field_value text NOT NULL,
+   normalized_value text NOT NULL,
+   blog_id int(10) default NULL,
+   article_id int(10) default NULL,
+   PRIMARY KEY  (id),
+   FULLTEXT KEY normalized_value (normalized_value),
+   KEY blog_id (blog_id),
+   KEY article_id (article_id),
+   KEY field_id (field_id),
+   KEY blog_id_article_id (blog_id, article_id)
+   ) TYPE=MyISAM;";
+
+   $Tables[24]["desc"] = "Text of the articles";
+   $Tables[24]["code"] = "CREATE TABLE {dbprefix}articles_text (
+   id int(10) NOT NULL auto_increment,
+   article_id int(10) NOT NULL DEFAULT 0,
+   text TEXT NOT NULL DEFAULT '',
+   topic TEXT NOT NULL DEFAULT '',
+   normalized_text TEXT NOT NULL DEFAULT '',
+   normalized_topic TEXT NOT NULL DEFAULT '',
+   mangled_topic text NOT NULL,
+   PRIMARY KEY (id),
+   KEY article_id (article_id),
+   FULLTEXT KEY normalized_text (normalized_text),
+   FULLTEXT KEY normalized_topic (normalized_topic),
+   FULLTEXT KEY normalized_fields (normalized_text, normalized_topic)
+   ) TYPE=MyISAM;";
+   
+   $Tables[25]["desc"] = "PhpBB2 User Integration Table";
+   $Tables[25]["code"] = "CREATE TABLE {dbprefix}phpbb2_users (
+   id int(10) unsigned NOT NULL auto_increment,
+   phpbb_id int(10) unsigned NOT NULL,
+   full_name varchar(255) NOT NULL default '',
+   about text,
+   properties TEXT NOT NULL default '',
+   resource_picture_id integer(10) NOT NULL DEFAULT 0,
+   status INTEGER(10) NOT NULL DEFAULT 0,
+   PRIMARY KEY  (id),
+   UNIQUE KEY phpbb_id(phpbb_id)
+   ) TYPE=MyISAM;";
+   
+   /*** new in 1.1 ***/   
+   $Tables[26]["desc"] = "Blog categories";
+   $Tables[26]["code"] = "CREATE TABLE {dbprefix}blog_categories (
+   id int(10) unsigned NOT NULL auto_increment,
+   name varchar(255) NOT NULL default '',
+   description varchar(255) NOT NULL default '',
+   mangled_name varchar(255) NOT NULL default '',
+   properties TEXT NOT NULL DEFAULT '',
+   num_blogs int(10) NOT NULL default '0',
+   PRIMARY KEY (id),
+   KEY mangled_name(mangled_name)
+   ) TYPE=MyISAM;";
+
+   // ---
+
+   // ---
+   // end of changes needed in 1.0
+   // ---
+
+$Inserts[0] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('comments_enabled','1',1);";
+$Inserts[1] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('rdf_enabled','1',1);";
+$Inserts[2] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('temp_folder','./tmp',3);";
+$Inserts[3] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('base_url','{plog_base_url}',3);";
+$Inserts[4] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('show_posts_max','15',1);";
+$Inserts[5] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('recent_posts_max','10',1);";
+$Inserts[6] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('default_template','standard',3);";
+$Inserts[7] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('template_folder','./templates',3);";
+$Inserts[8] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('default_blog_id','1',1);";
+$Inserts[9] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('default_locale','en_UK',3);";
+$Inserts[10] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('html_allowed_tags_in_comments','<a><i><br><br/><b>',3);";
+$Inserts[11] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('referer_tracker_enabled','1',1);";
+$Inserts[12] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('rss_parser_enabled','1',1);";
+$Inserts[13] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('show_more_enabled','1',1);";
+$Inserts[14] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('show_more_threshold','150',1);";
+$Inserts[15] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('update_article_reads','1',1);";
+$Inserts[16] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('email_service_enabled','1',1);";
+$Inserts[17] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('post_notification_source_address','noreply at your.host.com',3);";
+$Inserts[18] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('request_format_mode','1',1);";
+$Inserts[19] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('xmlrpc_ping_hosts','a:2:{i:0;s:27:\"http://rpc.weblogs.com/RPC2\";i:1;s:0:\"\";}',5);";
+$Inserts[20] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('trackback_server_enabled','1',1);";
+$Inserts[21] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('htmlarea_enabled','1',1);";
+$Inserts[22] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('plugin_manager_enabled','1',1);";
+$Inserts[23] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('check_email_address_validity','0',1);";
+$Inserts[24] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('summary_page_show_max','15',1);";
+$Inserts[25] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('minimum_password_length','4',1);";
+$Inserts[26] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('templates','a:3:{i:0;s:7:\"blueish\";i:1;s:4:\"grey\";i:2;s:8:\"standard\";}',5);";
+$Inserts[27] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('locales','a:0:{}',5)";
+$Inserts[28] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('email_service_type','php',3);";
+$Inserts[29] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('smtp_host','your.smtp.host.com',3);";
+$Inserts[30] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('smtp_port','25',1);";
+$Inserts[31] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('smtp_use_authentication','0',1);";
+$Inserts[32] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('smtp_username','',3);";
+$Inserts[33] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('smtp_password','',3);";
+$Inserts[34] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('locale_folder','./locale',3);";
+$Inserts[35] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('xmlrpc_ping_enabled','0',1);";
+$Inserts[36] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('path_to_tar','{path_to_tar}',3);";
+$Inserts[37] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('path_to_gzip','{path_to_gzip}',3);";
+$Inserts[38] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('path_to_bz2','{path_to_bz2}',3);";
+$Inserts[39] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('path_to_unzip','{path_to_unzip}',3);";
+$Inserts[40] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('users_can_add_templates',1,1);";
+$Inserts[41] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('maximum_file_upload_size', 2000000, 1);";
+$Inserts[42] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('upload_forbidden_files', '*.php *.php3 *.php4 *.phtml *.htm *.html *.exe *.com *.bat .htaccess *.sh', 3);";
+$Inserts[43] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('comments_order', 1, 1);";
+$Inserts[44] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('security_pipeline_enabled', 1, 1);";
+$Inserts[45] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('maximum_comment_size', 0, 1 );";
+$Inserts[46] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('resources_enabled', 1, 1 );";
+$Inserts[47] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('thumbnail_method', 'gd', 3);";
+$Inserts[48] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('path_to_convert', '{path_to_convert}', 3);";
+$Inserts[49] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('thumbnail_height', 120, 1);";
+$Inserts[50] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('thumbnail_width', 120, 1);";
+$Inserts[51] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('thumbnails_keep_aspect_ratio', 1, 1);";
+$Inserts[52] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('xmlrpc_api_enabled', 1, 1);";
+$Inserts[53] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('uploads_enabled', 1, 1);";
+$Inserts[54] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES ('default_rss_profile', 'rss090', 3);";
+$Inserts[55] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('bayesian_filter_enabled', 1, 2);";
+$Inserts[56] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('bayesian_filter_spam_probability_treshold', '0.9', 6);";
+$Inserts[57] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('bayesian_filter_nonspam_probability_treshold', '0.2', 6);";
+$Inserts[58] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('bayesian_filter_min_length_token', '3', 1);";
+$Inserts[59] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('bayesian_filter_max_length_token', '100', 1);";
+$Inserts[60] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('bayesian_filter_number_significant_tokens', 15, 1);";
+$Inserts[61] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('bayesian_filter_spam_comments_action', 0, 1 );";
+$Inserts[62] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('ip_address_filter_enabled', 1, 1 );";
+$Inserts[63] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('content_filter_enabled', 1, 1 );";
+$Inserts[64] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('thumbnail_format','same',3);";
+$Inserts[65] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('resources_folder','./gallery/',3);";
+$Inserts[66] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('beautify_comments_text', '1', 1);";
+$Inserts[67] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('disable_apache_error_handler', '0', 1);";
+$Inserts[68] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('show_future_posts_in_calendar', '0', 1);";
+$Inserts[69] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('xhtml_converter_enabled', '1', 1);";
+$Inserts[70] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('xhtml_converter_aggresive_mode_enabled', '0', 1);";
+$Inserts[71] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('search_engine_enabled', '1', 1);";
+$Inserts[72] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('search_in_custom_fields', '1', 1);";
+$Inserts[73] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('search_in_comments', '1', 1);";
+$Inserts[74] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('resources_quota', '0', 1);";
+$Inserts[75] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('category_link_format', '/blog/{blogname}/{catname}$', 3);";
+$Inserts[76] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('blog_link_format', '/blog/{blogname}$', 3);";
+$Inserts[77] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('archive_link_format', '/blog/{blogname}/archives/{year}/?{month}/?{day}', 3);";
+$Inserts[78] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('user_posts_link_format', '/blog/{blogname}/user/{username}$', 3);";
+$Inserts[79] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('post_trackbacks_link_format', '/blog/{blogname}/post/trackbacks/{postname}$', 3);";
+$Inserts[80] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('template_link_format', '/blog/{blogname}/page/{templatename}$', 3);";
+$Inserts[81] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('album_link_format', '/blog/{blogname}/album/{albumname}$', 3);";
+$Inserts[82] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('resource_link_format', '/blog/{blogname}/resource/{albumname}/{resourcename}$', 3);";
+$Inserts[83] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('resource_preview_link_format', '/blog/{blogname}/resource/{albumname}/preview/{resourcename}$', 3);";
+$Inserts[84] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('resource_download_link_format', '/blog/{blogname}/resource/{albumname}/download/{resourcename}$', 3);";
+$Inserts[85] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('permalink_format', '/blog/{blogname}/{catname}/{year}/{month}/{day}/{postname}$', 3);";
+$Inserts[86] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('script_name', 'index.php', 3);";
+$Inserts[87] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('thumbnail_generator_use_smoothing_algorithm', '0', 1);";
+$Inserts[88] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('resource_server_use_http_caching', '1', 1);";
+$Inserts[89] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('medium_size_thumbnail_width', '640', 1);";
+$Inserts[90] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('medium_size_thumbnail_height', '480', 1);";
+$Inserts[91] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('resource_medium_size_preview_link_format', '/blog/{blogname}/resource/{albumname}/preview-med/{resourcename}$', 3);";
+$Inserts[92] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('subdomains_enabled', '0', 1);";
+$Inserts[93] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('include_blog_id_in_url', '1', 1);";
+$Inserts[94] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('send_xmlrpc_pings_enabled_by_default', '1', 1);";
+$Inserts[95] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('forbidden_usernames', 'admin www blog ftp wiki forums', 3);";
+$Inserts[96] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('force_registration_confirmation', '0', 1);";
+$Inserts[97] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('summary_blogs_per_page', '25', 3);";
+$Inserts[98] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('subdomains_base_url', '', 3);";
+$Inserts[99] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('autosave_new_drafts_time_millis', '300000', 3);";
+$Inserts[100] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('save_drafts_via_xmlhttprequest_enabled', '1', 1);";
+$Inserts[101] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('need_email_confirm_registration', '1', 1);";
+$Inserts[102] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('force_one_blog_per_email_account', '0', 1);";
+$Inserts[103] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('summary_show_agreement', '1', 1);";
+$Inserts[104] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('default_time_offset', '0', 3);";
+$Inserts[105] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('template_cache_enabled', '1', 1);";
+$Inserts[106] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('template_http_cache_enabled', '0', 1);";
+$Inserts[107] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('template_http_cache_enabled', '0', 1);";
+$Inserts[108] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('template_compile_check', '1', 1);";
+$Inserts[109] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('update_cached_article_reads', '1', 1);";
+$Inserts[110] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('allow_php_code_in_templates', '0', 1);";
+$Inserts[111] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('thumbnail_generator_use_smoothing_algorithm', '1', 1);";
+$Inserts[112] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('template_cache_lifetime', '-1', 3);";
+$Inserts[113] = "INSERT INTO {dbprefix}config (config_key, config_value, value_type) VALUES('use_http_accept_language_detection', '0', 1);";
+
+    /**
+     * Open a connection to the database
+     */
+     function connectDb( $ignoreError = false , $selectDatabase = true )
+     {
+        $config = new ConfigFileStorage();
+        // open a connection to the database
+        //$db = NewADOConnection('mysql');
+        $db = PDb::getDriver('mysql');
+        if ( $selectDatabase ) {
+            $res = $db->Connect($config->getValue( "db_host" ), $config->getValue( "db_username" ), $config->getValue( "db_password" ), $config->getValue( "db_database" ));
+        } else {
+            $res = $db->Connect($config->getValue( "db_host" ), $config->getValue( "db_username" ), $config->getValue( "db_password" ));
+        }
+
+        if( DB_WIZARD_DEBUG )
+            $db->debug = true;
+
+        // return error
+        if( $ignoreError )
+            return $db;
+
+        if( !$res )
+            return false;
+
+        return $db;
+    }
+
+    /**
+     * Returns the database prefix
+     */
+    function getDbPrefix()
+    {
+        $config = new ConfigFileStorage();
+        return $config->getValue( "db_prefix" );
+    }
+
+    /**
+     * some useful little functions
+     */
+    class WizardTools extends Object
+    {
+       /**
+        * returns true if plog has already been installed before or
+        * false otherwise
+        */
+       function isNewInstallation()
+       {
+           $configFile = new ConfigFileStorage();
+           // if plog hasn't been installed, this file will have empty settings
+           if( $configFile->getValue( "db_host") == "" && $configFile->getValue( "db_username") == "" &&
+               $configFile->getValue( "db_database") == "" && $configFile->getValue( "db_prefix" ) == "" &&
+               $configFile->getValue( "db_password" ) == "" )
+               $isNew = true;
+           else
+               $isNew = false;
+
+           return( $isNew );
+       }
+    }
+
+    /**
+     * Renders a template file.
+     */
+    class WizardView extends View
+    {
+
+        var $_templateName;
+
+        function WizardView( $templateName )
+        {
+            $this->View();
+            $this->_templateName = $templateName;
+        }
+
+        function render()
+        {
+            // build the file name
+            $templateFileName = "wizard/".$this->_templateName.".template";
+
+            //$t = new Template( $templateFileName, "" );
+            $t = new Smarty();
+            $v = new Version();
+            $this->_params->setValue( "version", $v->getVersion());
+            $this->_params->setValue( "projectPage", $v->getProjectPage());
+            $this->_params->setValue( "safeMode", ini_get("safe_mode"));
+            $t->assign( $this->_params->getAsArray());
+            $t->template_dir    = "./templates";
+            $t->compile_dir     = TEMP_FOLDER;
+            $t->cache_dir       = TEMP_FOLDER;
+            $t->use_sub_dirs    = false;
+            $t->caching = false;
+
+            print $t->fetch( $templateFileName );
+        }
+    }
+
+    /**
+     * Gets the information about the database from the user.
+     */
+    class WizardIntro extends Action
+    {
+        function WizardIntro( $actionInfo, $request )
+        {
+            $this->Action( $actionInfo, $request );
+        }
+
+        function perform()
+        {
+            // we can detect whether plog is already installed or not and direct users to the right
+            // place
+            if( WizardTools::isNewInstallation())
+                $this->_view = new WizardView( "intro" );
+            else {
+                Controller::setForwardAction( "Update1" );
+                return false;
+            }
+
+            $this->setCommonData();
+            return true;
+        }
+    }
+
+    /**
+     *
+     * Saves data to the configuration file
+     *
+     */
+    class WizardStepOne extends Action
+    {
+
+        var $_dbServer;
+        var $_dbUser;
+        var $_dbPassword;
+        var $_dbName;
+        var $_dbPrefix;
+
+        function WizardStepOne( $actionInfo, $request )
+        {
+            $this->Action( $actionInfo, $request );
+
+            // data validation
+            $this->registerFieldValidator( "dbServer", new StringValidator());
+            $this->registerFieldValidator( "dbUser", new StringValidator());
+            $this->registerFieldValidator( "dbPassword",  new StringValidator(), true );
+            $this->registerFieldValidator( "dbName", new StringValidator());
+            $this->registerFieldValidator( "dbPrefix", new StringValidator(), true );
+            $errorView = new WizardView( "intro" );
+            $errorView->setErrorMessage( "Some data was incorrect or missing." );
+            $this->setValidationErrorView( $errorView );
+        }
+
+        function perform()
+        {
+            // fetch the data needed from the request
+            $this->_dbServer   = $this->_request->getValue( "dbServer" );
+            $this->_dbUser     = $this->_request->getValue( "dbUser" );
+            $this->_dbPassword = $this->_request->getValue( "dbPassword" );
+            $this->_dbName     = $this->_request->getValue( "dbName" );
+            $this->_skipThis   = $this->_request->getValue( "skipDbInfo" );
+            $this->_dbPrefix   = $this->_request->getValue( "dbPrefix", DEFAULT_DB_PREFIX );
+
+            // we should now save the data to the configuration file, just before
+            // we read it
+            $configFile = new ConfigFileStorage();
+
+            // we expect everything to be fine
+            $errors = false;
+
+            // before doing anything, we should check of the configuration file is
+            // writable by this script, or else, throw an error and bail out gracefully
+            $configFileName = $configFile->getConfigFileName();
+            if( !File::exists( $configFileName )) {
+                if (! File::touch( $configFileName ) ) {
+                    $this->_view = new WizardView( "intro" );
+                    $message = "Could not create the pLog configuration file $configFileName. Please make sure
+                                that the file can be created by the user running the webserver. It is needed to
+                                store the database configuration settings.";
+                    $this->_view->setErrorMessage( $message );
+                    $this->setCommonData( true );
+                    return false;
+                } else {
+                    ConfigFileStorage::createConfigFile( $configFileName );
+                }
+            }
+            if( File::exists( $configFileName ) && !File::isWritable( $configFileName )) {
+                $this->_view = new WizardView( "intro" );
+                $message = "Please make sure that the file $configFileName can be written by this script during
+                            the installation process. It is needed to store the database configuration settings. Once the
+                            installation is complete, please revert the permissions to no writing possible.";
+                $this->_view->setErrorMessage( $message );
+                $this->setCommonData( true );
+                return false;
+            }
+
+            // continue if everything went fine
+            if( !$configFile->saveValue( "db_username", $this->_dbUser ) ||
+                !$configFile->saveValue( "db_password", $this->_dbPassword ) ||
+                !$configFile->saveValue( "db_host", $this->_dbServer ) ||
+                !$configFile->saveValue( "db_database", $this->_dbName ) ||
+                !$configFile->saveValue( "db_prefix", $this->_dbPrefix )) {
+                $errors = true;
+            }
+
+            if( $errors ) {
+                $message = "Could not save values to the configuration file. Please make sure it is available and
+                            that has write permissions for the user under your web server is running.";
+                $this->_view = new WizardView( "intro" );
+                $this->_view->setErrorMessage( $message );
+
+                return( false );
+            }
+            else {
+                $this->_view = new WizardView( "step1" );
+
+                // now we better read the information from the config file to make sure that
+                // it has been correctly saved
+                $this->setCommonData( true );
+
+                return true;
+            }
+        }
+    }
+
+    /**
+     *
+     * Second step where we connect to the database and create the tables.
+     *
+     */
+    class WizardStepTwo extends Action
+    {
+
+        var $_db;
+        var $_database;
+        var $_createDatabase;
+
+        function setDbConfigValues( &$view )
+        {
+            $configFile = new ConfigFileStorage();
+            $configFile->reload();
+            $view->setValue( "dbUser", $configFile->getValue( "db_username" ));
+            $view->setValue( "dbPassword", $configFile->getValue( "db_password" ));
+            $view->setValue( "dbServer", $configFile->getValue( "db_host" ));
+            $view->setValue( "dbName", $configFile->getValue( "db_database" ));
+            $view->setValue( "dbPrefix", $configFile->getValue( "db_prefix" ));
+            return true;
+        }
+
+        function perform()
+        {
+            global $Tables;
+            global $Inserts;
+
+            $createDb = $this->_request->getValue( "createDatabase" );
+
+            // only check for errors in case the database table should already exist!
+            if( !$createDb ) {
+                $connectionEsablished = false;
+
+                // Lets check the 'everything is fine' case first..
+                $this->_db = connectDb();
+                if( $this->_db ) {
+                     $connectionEsablished = true;
+                } else {
+                     $connectionEsablished = false;
+                     $message = "There was an error selecting the database. Please verify the database was already created or check the 'Create database' checkbox.";
+                }
+
+                // We were unable to connect to the db and select the right db.. lets try
+                // just to connect.. maybe the database needs to be created (even though the
+                // user did not check the appropriate box).
+                if ( !$connectionEsablished ) {
+                    $this->_db = connectDb( true, false );
+                    if( !$this->_db ) {
+                         $message = "There was an error connecting to the database. Please check your settings.";
+                    }
+                }
+
+                if ( !$connectionEsablished ) {
+                    $this->_view = new WizardView( "step1" );
+                    $this->setDbConfigValues( $this->_view );
+                    $this->_view->setErrorMessage( $message );
+                    $this->setCommonData( true );
+                    return false;
+                }
+            }
+
+            $config = new ConfigFileStorage();
+            $this->_database = $config->getValue( "db_database" );
+            $this->_dbPrefix = $config->getValue( "db_prefix" );
+
+            // create the database
+            if( $createDb ) {
+                $this->_db = connectDb( false, false );
+                if( !$this->_db->Execute( "CREATE DATABASE ".$this->_database )) {
+                    $message = "Error creating the database: ".$this->_db->ErrorMsg();
+                    $this->_view = new WizardView( "step1" );
+                    $this->setDbConfigValues( $this->_view );
+                    $this->_view->setErrorMessage( $message );
+                    $this->setCommonData( true );
+                    return false;
+                } else {
+                    $message = "Database created successfully.<br/>";
+                }
+            }
+
+            // reconnect using the new database.
+            $config = new ConfigFileStorage();
+            $this->_db->Connect($config->getValue( "db_host" ), $config->getValue( "db_username" ), $config->getValue( "db_password" ), $config->getValue( "db_database" ));
+
+            // create the tables
+            $errors = false;
+            foreach( $Tables as $table ) {
+                $query = str_replace( "{dbprefix}", $this->_dbPrefix, $table["code"] );
+                if( $this->_db->Execute( $query ))
+                    $message .= "Table <strong>".$table["desc"]."</strong> created successfully.<br/>";
+                else {
+                    $message .= "Error creating table: ".$this->_db->ErrorMsg()."<br/>";
+                    $errors = true;
+                }
+            }
+
+            if( $errors ) {
+                $message = "There was an error creating the tables in the database. Please make sure that the user chosen to connect to the database has enough permissions to create tables.<br/><br/>$message";
+                $this->_view = new WizardView( "step1" );
+                $this->_view->setErrorMessage( $message );
+                $this->setDbConfigValues( $this->_view );
+                $this->setCommonData();
+                return false;
+            }
+
+            // try to guess the url where plog is running
+             // try to guess the url where plog is running
+             $httpProtocol = (array_key_exists("HTTPS", $_SERVER) && $_SERVER["HTTPS"] == "on") ? "https://" : "http://";
+             $httpHost = $_SERVER["HTTP_HOST"];
+             $requestUrl = $_SERVER["REQUEST_URI"];
+             $requestUrl = str_replace( "/wizard.php", "", $requestUrl );
+             $plogUrl = $httpProtocol.$httpHost.$requestUrl;
+
+            // Find some of the tools we are going to need (last one is for os x, with fink installed)
+            // TBD: support for Windows specific directories
+            $folders = Array( "/bin/", "/usr/bin/", "/usr/local/bin/", "/sw/bin/" );
+            $finder = new FileFinder();
+            $pathToUnzip = $finder->findBinary( "unzip", $folders );
+            $pathToTar = $finder->findBinary( "tar", $folders);
+            $pathToGzip = $finder->findBinary( "gzip", $folders);
+            $pathToBzip2 = $finder->findBinary( "bzip2", $folders);
+            $pathToConvert = $finder->findBinary( "convert", $folders);
+
+            // and execute some insert's
+            foreach( $Inserts as $insert ) {
+                $query = str_replace( "{dbprefix}", $this->_dbPrefix, $insert );
+                $query = str_replace( "{plog_base_url}", $plogUrl, $query );
+                // replace also the placeholders for the paths to the tools
+                $query = str_replace( "{path_to_tar}", $pathToTar, $query );
+                $query = str_replace( "{path_to_unzip}", $pathToUnzip, $query );
+                $query = str_replace( "{path_to_bz2}", $pathToBzip2, $query );
+                $query = str_replace( "{path_to_gzip}", $pathToGzip, $query );
+                $query = str_replace( "{path_to_convert}", $pathToConvert, $query );
+                $query = str_replace( "{path_to_convert}", $pathToConvert, $query );
+                if( !$this->_db->Execute( $query )) {
+                    $message .= "Error executing code: ".$this->_db->ErrorMsg()."<br/>";
+                    $errors = true;
+                }
+            }
+
+            //
+            // show some information regarding the helper tools we're going to need
+            // and wether they were found or not
+            //
+            $message .= "<br/><b>-- Helper tools --</b><br/>";
+            if( $pathToTar == "" )
+                $message .= "The helper tool 'tar' was not found<br/>";
+            else
+                $message .= "The helper tool 'tar' was found in $pathToTar<br/>";
+            if( $pathToGzip == "" )
+                $message .= "The helper tool 'gzip' was not found<br/>";
+            else
+                $message .= "The helper tool 'gzip' was found in $pathToGzip<br/>";
+            if( $pathToUnzip == "" )
+                $message .= "The helper tool 'unzip' was not found<br/>";
+            else
+                $message .= "The helper tool 'unzip' was found in $pathToUnzip<br/>";
+            if( $pathToBzip2 == "" )
+                $message .= "The helper tool 'bzip2' was not found<br/>";
+            else
+                $message .= "The helper tool 'bzip2' was found in $pathToTar<br/>";
+            if( $pathToConvert == "" )
+                $message .= "The helper tool 'convert' (from the ImageMagick package) was not found<br/>";
+            else
+                $message .= "The helper tool 'convert' (from the ImageMagick package) was found in $pathToConvert<br/>";
+
+            if( $errors ) {
+                $this->_view = new WizardView( "step1" );
+                $this->setDbConfigValues( $this->_view );
+                $message = "There was an error initializing some of the tables. Please make sure that the user chosen to connect to the database has enough permissions to add records to the database.<br/><br/>$message";
+                $this->_view->setErrorMessage( $message );
+                $this->setCommonData();
+            }
+            else {
+                $this->_view = new WizardView( "step2" );
+                $this->_view->setValue( "message", $message );
+            }
+
+            // Scan for locales
+            $locales = new Locales();
+            // find all the new locales that we have not yet stored
+            $f = new LocaleFinder();
+            $newLocaleCodes = $f->find();
+
+            foreach( $newLocaleCodes as $newLocaleCode ) {
+                $res = $locales->addLocale( $newLocaleCode );
+            }
+
+            return true;
+        }
+    }
+
+    /**
+     *
+     * this action only shows some feedback
+     *
+     */
+    class WizardStepThree extends Action
+    {
+        function perform()
+        {
+            $this->_view = new WizardView( "step3" );
+            $this->setCommonData();
+        }
+    }
+
+    /**
+     *
+     * Create the first user in the database
+     *
+     */
+    class WizardStepFour extends Action
+    {
+
+        var $_userName;
+        var $_userPassword;
+        var $_confirmPassword;
+        var $_userEmail;
+        var $_userFullName;
+
+        function WizardStepFour( $actionInfo, $request )
+        {
+            $this->Action( $actionInfo, $request );
+
+            $this->registerFieldValidator( "userName", new StringValidator());
+            $this->registerFieldValidator( "userPassword", new PasswordValidator());
+            $this->registerFieldValidator( "userPasswordCheck", new PasswordValidator());
+            $this->registerFieldValidator( "userEmail", new EmailValidator());
+            $this->registerField( "userFullName" );
+            $view = new WizardView( "step3" );
+            $view->setErrorMessage( "Some data is missing or incorrect" );
+            $this->setValidationErrorView( $view );
+        }
+
+        // creates the user
+        function perform()
+        {
+            $this->_userName = $this->_request->getValue( "userName" );
+            $this->_userPassword = $this->_request->getValue( "userPassword" );
+            $this->_confirmPassword = $this->_request->getValue( "userPasswordCheck" );
+            $this->_userEmail = $this->_request->getValue( "userEmail" );
+            $this->_userFullName = $this->_request->getValue( "userFullName" );
+
+            $db = connectDb();
+
+            if( !$db ) {
+                $this->_view = new WizardView( "step3" );
+                $this->_view->setErrorMessage( "There was an error connecting to the database. Please check your settings." );
+                $this->setCommonData();
+                return false;
+            }
+
+            if( $this->_confirmPassword != $this->_userPassword ) {
+                $this->_view = new WizardView( "step3" );
+                $this->_form->setFieldValidationStatus( "userPasswordCheck", false );
+                $this->setCommonData( true );
+                return false;
+            }
+
+            $dbPrefix = Db::getPrefix();
+
+            $users = new Users();
+            $user = new UserInfo( $this->_userName,
+                                  $this->_userPassword,
+                                  $this->_userEmail,
+                                  "",
+                                  $this->_userFullName);
+            $userId = $users->addUser( $user );
+            if( !$userId ) {
+                $this->_view = new WizardView( "step3" );
+                $message = "There was an error adding the user. Make sure that the user does not already exist in the database (".$users->DbError().")";
+                $this->_view->setErrorMessage( $message );
+                $this->setCommonData();
+                return false;
+            }
+
+            // we also have to execute the code to give administrator privileges to this user
+            $query = "INSERT INTO {$dbPrefix}users_permissions(user_id,blog_id,permission_id) VALUES( $userId, 0, 1 );";
+            $db->Execute( $query );
+
+            $this->_view = new Wizardview( "step4" );
+            $this->_view->setValue( "ownerid", $userId );
+            $this->_view->setValue( "siteLocales", Locales::getLocales());
+            $this->_view->setValue( "defaultLocale", Locales::getDefaultLocale());
+            $ts = new TemplateSets();
+            $this->_view->setValue( "siteTemplates", $ts->getGlobalTemplateSets());
+            $this->setCommonData();
+            return true;
+        }
+
+    }
+
+    class WizardStepFive extends Action
+    {
+
+        var $_blogName;
+        var $_ownerId;
+        var $_blogProperties;
+
+        function WizardStepFive( $actionInfo, $request )
+        {
+              $this->Action( $actionInfo, $request );
+
+              $this->registerFieldValidator( "blogName", new StringValidator());
+              $this->registerFieldValidator( "ownerid", new IntegerValidator());
+              $this->registerFieldValidator( "blogTemplate", new StringValidator());
+              $this->registerFieldValidator( "blogLocale", new StringValidator());
+              $view = new WizardView( "step4" );
+              $view->setErrorMessage( "Some data is missing or incorrect" );
+              $view->setValue( "siteLocales", Locales::getLocales());
+              $ts = new TemplateSets();
+              $view->setValue( "siteTemplates", $ts->getGlobalTemplateSets());
+              $this->setValidationErrorView( $view );
+        }
+
+        function perform()
+        {
+            // retrieve the values from the view
+            $this->_blogName = $this->_request->getValue( "blogName" );
+            $this->_ownerId  = $this->_request->getValue( "ownerid" );
+            $this->_blogProperties = $this->_request->getValue( "properties" );
+            $this->_blogTemplate = $this->_request->getValue( "blogTemplate" );
+            $this->_blogLocale = $this->_request->getValue( "blogLocale" );
+
+            // configure the blog
+            $blogs = new Blogs();
+            $blog = new BlogInfo( $this->_blogName, $this->_ownerId, "", "" );
+            $blog->setProperties( $this->_blogProperties );
+            $blog->setStatus( BLOG_STATUS_ACTIVE );
+            $blogSettings = $blog->getSettings();
+            $blogSettings->setValue( "locale", $this->_blogLocale );
+            $blogSettings->setValue( "template", $this->_blogTemplate );
+            $blog->setSettings( $blogSettings );
+
+            // and now save it to the database
+            $newblogId = $blogs->addBlog( $blog );
+            if( !$newblogId ) {
+                $this->_view = new WizardView( "step4" );
+                $this->_view->setValue( "siteLocales", Locales::getLocales());
+                $ts = new TemplateSets();
+                $this->_view->setValue( "siteTemplates", $ts->getGlobalTemplateSets());
+                $this->_view->setErrorMessage( "There was an error creating the new blog" );
+                $this->setCommonData( true );
+                return false;
+            }
+
+            // if the blog was created, we can add some basic information
+            // add a category
+            $articleCategories = new ArticleCategories();
+            $articleCategory = new ArticleCategory( "General", "", $newblogId, true );
+            $catId = $articleCategories->addArticleCategory( $articleCategory );
+
+            // load the right locale
+            $locale =& Locales::getLocale( $this->_blogLocale );
+            // and load the right text
+            $articleTopic = $locale->tr( "register_default_article_topic" );
+            $articleText  = $locale->tr( "register_default_article_text" );
+            $article = new Article( $articleTopic, $articleText, Array( $catId ), $this->_ownerId, $newblogId, POST_STATUS_PUBLISHED, 0, Array(), "welcome" );
+            $t = new Timestamp();
+            $article->setDateObject( $t );
+            $articles = new Articles();
+            $articles->addArticle( $article );
+
+            // save a few things in the default configuration
+            $config =& Config::getConfig();
+            // default blog id
+            $config->saveValue( "default_blog_id", (int)$newblogId );
+            // default locale
+            $config->saveValue( "default_locale", $this->_blogLocale );
+            // and finally, the default template
+            $config->saveValue( "default_template", $this->_blogTemplate );
+
+            //
+            // detect wether we have GD available and set the blog to use it
+            //
+            if( GdDetector::detectGd()) {
+                $config->saveValue( "thumbnail_method", "gd" );
+                $message = "GD has been detected and set as the backend for dealing with images.";
+            }
+            else {
+                $pathToConvert = $config->getValue( "path_to_convert" );
+                if( $pathToConvert ) {
+                    $config->saveValue( "thumbnail_method", "imagemagick" );
+                    $message = "ImageMagick has been detected and set as the backend for dealing with images.";
+                }
+                else {
+                    // nothing was found, so we'll have to do away with the 'null' resizer...
+                    $config->saveValue( "thumbnail_method", "null" );
+                    $message = "Neither GD nor ImageMagick have been detected in this host so it will not be possible to generate thumbnails from images.";
+                }
+            }
+
+            $this->_view = new WizardView( "step5" );
+            $this->_view->setValue( "message", $message );
+            return true;
+        }
+    }
+
+    //
+    // The following classes take care of updating the database to the last release
+    //
+    // Things that need to be done when going from 0.3.x to 1.0:
+    //
+    // - add the new tables:
+    //     plog_article_categories_link
+    //     plog_custom_fields_definition
+    //     plog_custom_fields_values
+    //
+    // - make modifications to some of the old tables:
+    //     plog_articles
+    //          normalized_text: TEXT
+    //          normalized_topic: TEXT
+    //          mangled_topic: TEXT
+    //          category_id: DROP
+    //          FULLTEXT(normalized_text)
+    //          FULLTEXT(normalized_topic)
+    //          FULLTEXT(normalized_text, normalized_topic)
+    //     plog_articles_categories
+    //          parent_id: INTEGER
+    //          mangled_name: TEXT
+    //          properties: TEXT
+    //     plog_articles_comments
+    //          normalized_text: TEXT
+    //          normalized_topic: TEXT
+    //          FULLTEXT(normalized_text)
+    //          FULLTEXT(normalized_topic)
+    //          FULLTEXT(normalized_text, normalized_topic)
+    //     plog_blogs
+    //          mangled_blog: TEXT
+    //          properties: TEXT
+    //     plog_gallery_albums
+    //          normalized_name: VARCHAR
+    //          normalized_description: TEXT
+    //          mangled_name: VARCHAR
+    //          FULLTEXT(normalized_name)
+    //          FULLTEXT(normalized_description)
+    //          FULLTEXT(normalized_name, normalized_description)
+    //     plog_gallery_resources
+    //          normalized_description: TEXT
+    //          FULLTEXT(normalized_description)
+    //     plog_mylinks
+    //          properties: TEXT
+    //     plog_mylinks_categories
+    //          properties: TEXT
+    //     plog_users
+    //          properties: TEXT
+    //          full_name: VARCHAR
+    //
+    // - for all the articles in the db, fill in the normalized_text, normalized_topic and mangled_topic
+    //   fields using the TextFilter class
+    //
+    // - for all articles in the db, change the status from a string ('published', 'draft', 'deleted') to
+    // an integer (POST_STATUS_{PUBLISHED|DELETED|DRAFT}
+    //
+    // - for all articles and categories, arrange the plog_article_categories_link table so that everything works
+    //   as before
+    //
+    // - for all article categories, fill in the mangled_name field
+    //
+    // - for all comments, fill in the normalized_text and normalized_topic fields
+    //
+    // - for all blogs, fill in the mangled_blog field
+    //
+    // - for all albums, fill in the normalized_name, normalized_description and mangled_name fields
+    //
+    // - for all resources, fill in the normalized_description field
+
+
+    class UpdateStepOne extends Action
+    {
+
+        function perform()
+        {
+            $this->_view = new WizardView( "update1" );
+            WizardStepTwo::setDbConfigValues( $this->_view );
+            $this->setCommonData();
+        }
+    }
+
+    class UpdateStepTwo extends Action
+    {
+
+        var $_db;
+        var $_dbPrefix;
+
+        function validate()
+        {
+            $configFile = new ConfigFileStorage();
+            $this->_dbPrefix = $configFile->getValue( "db_prefix" );
+
+            return true;
+        }
+
+        function perform()
+        {
+            // we need to create the new tables here
+            $newTables = Array( 21, 22, 23, 24 );
+
+            global $Tables;
+            global $Changes;
+            global $Inserts;
+
+            // connect to the db
+            $this->_db = connectDb();
+
+            // store error messages in this var
+            $message = "";
+
+            if( !$this->_db ) {
+                $this->_view = new WizardView( "update1" );
+                WizardStepTwo::setDbConfigValues( $this->_view );
+                $this->_view->setErrorMessage( "There was an error connecting to the database. Please check your settings." );
+                return false;
+            }
+
+            // ---
+            // create the new tables in 1.0
+            // ---
+            // loop only through the new tables
+            foreach( $newTables as $tableId ) {
+                // get info about the table we'd like to use
+                $table = $Tables[$tableId];
+                // and run the query
+                $query = str_replace( "{dbprefix}", $this->_dbPrefix, $table["code"] );
+                if( $this->_db->Execute( $query ))
+                    $message .= "New table <strong>".$table["desc"]."</strong> created successfully.<br/>";
+                else {
+                    $message .= "Error creating table: ".$this->_db->ErrorMsg()."<br/>";
+                    $errors = true;
+                }
+            }
+            if( !$errors ) {
+                $message .= "** New tables created successfully **<br/><br/>";
+            }
+
+            // ---
+            // make changes to the tables that need changes
+            // ---
+            foreach( $Changes as $tableId => $changeTable) {
+                $errorMessage = "";            
+                foreach( $changeTable as $changeCode ) {
+                    // and run the query
+                    $query = str_replace( "{dbprefix}", $this->_dbPrefix, $changeCode );
+                    if( !$this->_db->Execute( $query )) {
+                        $errors = true;                    
+                        $errorMessage .= $this->_db->ErrorMsg()."<br/>";
+                    }
+                }
+
+                if( !$errors )
+                    $message .= "Changes to table <strong>$tableId</strong> executed successfully.<br/>";
+                else {
+                    $message .= "Error modifying table $tableId: ".$errorMessage;
+                }
+            }
+
+            if( !$errors ) {
+                $message .= "** Modifications to old tables carried out successfully **<br/><br/>";
+            }
+
+            // ---
+            // add the new configuration settings that were added for 1.0
+            // ---
+            $newSettings = range( 71, 112 );
+            foreach( $newSettings as $settingId ) {
+                $setting = $Inserts[$settingId];
+                $query = str_replace( "{dbprefix}", $this->_dbPrefix, $setting );
+                if( !$this->_db->Execute( $query )) {
+                    $message .= "There was an error executing: ".$this->_db->ErrorMsg()."<br/>";
+                    $errors = true;
+                }
+            }
+
+            //
+            // there's nothing left to do so we can quit now!!
+            //
+            if( !$errors ) {
+                $this->_view = new WizardView( "update2" );
+                $this->_view->setValue( "message", $message );
+            }
+            else {
+                $this->_view = new WizardView( "update1" );
+                WizardStepTwo::setDbConfigValues( $this->_view );
+                $this->_view->setErrorMessage( $message );
+            }
+
+            return true;
+        }
+    }
+
+    /**
+     * this is the first step of the transformations to some of the fields in the tables.
+     * Precisely, it is in this step where we regenerate the indexes for the search engine... However, it
+     * could take it a while...
+     */
+    class UpdateStepThree extends Action
+    {
+        function UpdateStepThree( $actionInfo, $httpRequest )
+        {
+            $this->Action( $actionInfo, $httpRequest );
+
+            // load the current step, if any
+            $this->_curStep = $this->_request->getValue( "curStep" );
+            $this->_numPosts = $this->_request->getValue( "numPosts" );
+
+            //print("cur step = ".$this->_curStep." - num posts = ".$this->_numPosts."<br/>");
+        }
+
+        function getStatusId( $statusStr )
+        {
+            if( $statusStr == 'published' ) return POST_STATUS_PUBLISHED;
+            if( $statusStr == 'draft' ) return POST_STATUS_DRAFT;
+            if( $statusStr == 'deleted' ) return POST_STATUS_DELETED;
+
+            return false;
+        }
+
+       function perform()
+       {
+            // get a connection to the db
+            $db = connectDb();
+            $dbPrefix = getDbPrefix();
+            $db->debug=false;
+
+            // no errors here
+            $errors = false;
+
+            // see how many records we have
+            $queryCount = "SELECT COUNT(*) AS total FROM {$dbPrefix}articles";
+            $result = $db->Execute( $queryCount );
+            $row = $result->FetchRow();
+            $numRecords = $row["total"];
+            $this->_totalPosts = $numRecords;
+            // check whether we should use multiple steps
+            $multipleSteps = ( $numRecords > WIZARD_MAX_RECORDS_THRESHOLD );
+            if( $multipleSteps ) {
+                // how many steps do we need?
+                $numSteps = ceil( $numRecords / WIZARD_MAX_RECORDS_PER_STEP );
+                $this->_numSteps = $numSteps;
+                //print("using different steps! numSteps = $numSteps<br/>");
+            }
+
+            // run the query and loop through the results
+            $query = "SELECT * FROM {$dbPrefix}articles";
+            if( $multipleSteps ) {
+                // generate the LIMIT condition for this page
+                $query .= " LIMIT ".$this->_curStep*WIZARD_MAX_RECORDS_PER_STEP.", ".WIZARD_MAX_RECORDS_PER_STEP;
+            }
+
+            //print("query = $query<br/>");
+
+            $result = $db->Execute( $query );
+
+            $tf = new TextFilter();
+
+            $numPosts = $result->RowCount();
+
+            while( $row = $result->FetchRow()) {
+                // for each one of the articles, fill in the mangled_topic, normalized_text and normalized_value
+                $normalizedTopic = Db::qstr($tf->normalizeText( $row["topic"] ));
+                $postTopic       = Db::qstr($row["topic"]);
+                $normalizedText  = Db::qstr($tf->normalizeText( $row["text"] ));
+                $postText        = Db::qstr($row["text"]);
+                $mangledTopic    = Db::qstr($tf->urlize( $row["topic"] ));
+                $status          = $this->getStatusId( $row["old_status"] );
+                $artId           = $row["id"];
+                $catId           = $row["category_id"];
+
+                $query = "UPDATE {$dbPrefix}articles SET slug = '$mangledTopic', date = date, status = $status
+                          WHERE id = $artId";
+
+                $query2= "INSERT INTO {$dbPrefix}article_categories_link(article_id, category_id)
+                          VALUES ( $artId, $catId )";
+
+                $query3= "INSERT INTO {$dbPrefix}articles_text (article_id,text,topic,normalized_text,normalized_topic,mangled_topic)
+                          VALUES('$artId','$postText','$postTopic','$normalizedTopic','$normalizedText','$mangledTopic')";
+
+
+                // execute the two queries
+                $res  = $db->Execute( $query );
+                $res2 = $db->Execute( $query2 );
+                $res3 = $db->Execute( $query3 );
+
+                /*if( !$res || !$res2 || !$res3 )
+                    $errors = true;*/
+            }
+
+            // check whether we've already done the last step or not
+            $lastStepDone = ( $this->_curStep >= $this->_numSteps );
+
+            // if error
+            if( $errors ) {
+                $this->_view = new WizardView( "update2" );
+                $this->_view->setErrorMessage( "There was an error updating the articles table." );
+                $this->setCommonData();
+                return false;
+            }
+
+            //$query1 = "ALTER TABLE {$dbPrefix}articles DROP COLUMN old_status, DROP COLUMN category_id";
+            //$db->Execute( $query1 );
+
+            // if everyhting's fine, say so...
+            if( !$multipleSteps || $lastStepDone ) {
+                $this->_view = new WizardView( "update3" );
+                $this->_view->setValue( "totalPosts", $this->_totalPosts );
+            }
+            else {
+                // if we're using multiple steps, show the same page
+                $this->_view = new WizardView( "update2" );
+                $this->_view->setValue( "numPosts", $numPosts );
+                $this->_view->setValue( "curStep", $this->_curStep+1 );
+                $this->_view->setValue( "totalPosts", $this->_totalPosts );
+                $this->_view->setValue( "numSteps", $this->_numSteps );
+                $this->_view->setValue( "multipleSteps", true );
+            }
+
+            return true;
+        }
+
+    }
+
+    // ---
+    // this action will do the same as before but for the rest of the tables that need some data to
+    // be normalized/mangled
+    // ---
+    class UpdateStepFour extends Action
+    {
+
+        var $dbPrefix;
+        var $db;
+        var $t;
+
+        function validate()
+        {
+            $this->db = connectDb();
+            $this->dbPrefix = getDbPrefix();
+            $this->t = new TextFilter();
+
+            return true;
+        }
+
+        //
+        // process the article categories
+        //
+        function updateArticleCategories()
+        {
+            $dbPrefix = $this->dbPrefix;
+            $query = "SELECT * FROM {$dbPrefix}articles_categories";
+            $result = $this->db->Execute( $query );
+
+            while( $row = $result->FetchRow()) {
+                $catId = $row["id"];
+                $mangledName = $this->t->urlize( $row["name"] );
+                $query = "UPDATE {$dbPrefix}articles_categories
+                          SET mangled_name = '$mangledName', last_modification = last_modification
+                          WHERE id = $catId";
+
+                $res = $this->db->Execute( $query );
+
+                // this is not very nice to see but it works... :)
+                if( !$res ) {
+                    $this->message .= "There was an error updating the article categories table.<br/>";
+                    return false;
+                }
+            }
+
+            $this->message .= "Article Categories table updated successfully!<br/>";
+
+            return true;
+        }
+
+        //
+        // process the comments
+        //
+        function updateArticleComments()
+        {
+            $dbPrefix = $this->dbPrefix;
+            $query = "SELECT * FROM {$dbPrefix}articles_comments";
+            $result = $this->db->Execute( $query );
+
+            while( $row = $result->FetchRow()) {
+                $commentId = $row["id"];
+                $normText = Db::qstr($this->t->normalizeText( $row["text"] ));
+                $normTopic = Db::qstr($this->t->normalizeText( $row["topic"] ));
+                $query = "UPDATE {$dbPrefix}articles_comments
+                          SET normalized_text = '$normText', normalized_topic = '$normTopic', date = date
+                          WHERE id = $commentId";
+
+                $res = $this->db->Execute( $query );
+
+                if( !$res ) {
+                    $this->message .= "There was an error updating the comments table.<br/>";
+                    return false;
+                }
+            }
+
+            $this->message .= "Comments table updated successfully!<br/>";
+
+            return true;
+        }
+
+        //
+        // process the blogs
+        //
+        function updateBlogs()
+        {
+            $dbPrefix = $this->dbPrefix;
+            $query = "SELECT * FROM {$dbPrefix}blogs";
+            $result = $this->db->Execute( $query );
+
+            while( $row = $result->FetchRow()) {
+                $blogId = $row["id"];
+                $mangledBlog = $this->t->urlize( $row["blog"] );
+                $query = "UPDATE {$dbPrefix}blogs
+                          SET mangled_blog = '$mangledBlog' WHERE id = $blogId";
+
+                $res = $this->db->Execute( $query );
+
+                if( !$res ) {
+                    $this->message .= "There wasn an error updaing the blogs table.<br/>";
+                    return false;
+                }
+            }
+
+            $this->message .= "Blogs table updated successfully!<br/>";
+
+            return true;
+        }
+
+        //
+        // process the albums
+        //
+        function updateAlbums()
+        {
+            $dbPrefix = $this->dbPrefix;
+            $query = "SELECT * FROM {$dbPrefix}gallery_albums";
+            $result = $this->db->Execute( $query );
+
+            while( $row = $result->FetchRow()) {
+                $albumId = $row["id"];
+                $mangledName = Db::qstr($this->t->urlize( $row["name"] ));
+                $normName = Db::qstr($this->t->normalizeText( $row["name"] ));
+                $normDescription = Db::qstr($this->t->normalizeText( $row["description"] ));
+                $query = "UPDATE {$dbPrefix}gallery_albums
+                          SET mangled_name = '$mangledName', normalized_name = '$normName',
+                          normalized_description = '$normDescription', date = date
+                          WHERE id = $albumId";
+
+                $res = $this->db->Execute( $query );
+
+                if( !$res ) {
+                    $this->message .= "There was an error updating the albums table.<br/>";
+                    return false;
+                }
+            }
+
+            $this->message .= "Resource Albums table updated successfully!<br/>";
+
+            return true;
+        }
+
+        //
+        // and finally, the resources...
+        //
+        function updateResources()
+        {
+            $dbPrefix = $this->dbPrefix;
+            $query = "SELECT * FROM {$dbPrefix}gallery_resources";
+            $result = $this->db->Execute( $query );
+
+            while( $row = $result->FetchRow()) {
+                $resId = $row["id"];
+                //$normName = $this->t->normalizeText( $row["name"] );
+                $normDescription = Db::qstr($this->t->normalizeText( $row["description"] ));
+                $query = "UPDATE {$dbPrefix}gallery_resources
+                          SET normalized_description = '$normDescription', date = date
+                          WHERE id = $resId";
+
+                $res = $this->db->Execute( $query );
+                if( !$res ) {
+                    $this->message .= "There was an error updating the resources table.<br/>";
+                    return false;
+                }
+            }
+
+            $this->message .= "Resources table updated successfully!<br/>";
+
+            return true;
+
+        }
+
+        //
+        // process the articles' text
+        //
+        function updateArticleText()
+        {
+            $dbPrefix = $this->dbPrefix;
+            // drop unneeded columns from articles table
+            $alter_query[] = "ALTER TABLE ".$dbPrefix."articles DROP COLUMN text";
+            $alter_query[] = "ALTER TABLE ".$dbPrefix."articles DROP COLUMN topic";
+
+            foreach ($alter_query as $value) {
+                $this->db->Execute($value);
+            }
+
+
+            $this->message .= "articles_text table updated successfully!<br/>";
+
+            return true;
+        }
+
+        function perform()
+        {
+            $updaters = Array( "updateArticleCategories", "updateArticleComments",
+                               "updateBlogs", "updateAlbums", "updateResources", "updateArticleText" );
+
+            // loop through each one of the methods to take care of updating one of the tables
+            foreach( $updaters as $method ) {
+                $result = $this->$method();
+
+                if( !$result ) {
+                    $this->_view = new WizardView( "update3" );
+                    $this->_view->setErrorMessage( $this->message );
+                    return false;
+                }
+            }
+
+            // everything went fine so we can show the final page!
+            $this->_view = new WizardView( "update4" );
+            $this->_view->setValue( "message", $this->message );
+
+            return true;
+        }
+
+    }
+
+    // check if the "./tmp" folder is writable by us, otherwise
+    // throw an error before the user gets countless errors
+    // from Smarty
+    if( !File::isWritable( TEMP_FOLDER ) || !File::isDir( TEMP_FOLDER )) {
+        print("<span style=\"color:red; font-size: 14px;\">Error</span><br/><br/>This wizard needs the ".TEMP_FOLDER." folder to be writable by the web server user.<br/><br/>Please correct that and try again.");
+        die();
+    }
+
+    //// main part ////
+    $controller = new Controller( $_actionMap, "nextStep" );
+    $controller->process( HttpVars::getRequest());
+?>




More information about the pLog-svn mailing list