We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 39287
    • 13 Posts
    Hi all,

    I'm trying to write a small script that would import posts from a WP-based discussion board into the Discuss forum (1.1.1, under Revo 2.2.6pl).

    The code of the snippet is

    require_once('tmp/wp.php');

    if (!$modx->addPackage('discuss','core/components/discuss/model/')) {
    print 'Error occured while adding the package!';
    }

    $parser = new wpParser('tmp/iiko.xml', 100);

    And the function that saves the disPost ($wpParser->savePost):
    	
    function savePost($post, $type='disPost') {
    
    		global $modx;	
    		
    		$myPost = $this->getPostByExternalId($post['integrated_id'], $type);
    		
    		if (!$myPost) {
    			$this->log(30, 'Creating new '.$type);
    			
    			//			
    			$myPost = $modx->newObject($type, $post);
    			echo '<pre>';print_r($post);echo '</pre>';
    			$ok = $myPost->save();
    			if (!$ok) {
    				$this->log(0, 'Could not create a new '.$type);
    				return false;
    			} else $this->log(30, 'Created a '.$type.' with id '.$myPost->get('id'));
    		
    		} else 
    		
    		{ 	
    			$this->log(30, $type.' with external id '.$post['integrated_id'].' already exists. Updating '.$type.' '.$myPost->get('id') );
    			foreach ($post as $key=>$val) 
    				$myPost->set($key, $val);
    		}
    		
    		return $myPost;
    	
    	}
    


    It quits with a fatal error:

    Fatal error: Call to a member function loadSearch() on a non-object in .../core/components/discuss/model/discuss/dispost.class.php on line 237

    the line there is:

    if ($this->xpdo->discuss->loadSearch()) {


    So I guess, the $this->xpdo (which is generally the $modx, right?) does not have the discuss property. How can it be assigned?


    PS: The does save the post to the database though, but the post can not be seen in the forums.
    PPS: The native Discuss functions work perfectly, i.e. I can create threads and posts in the forums.

    This question has been answered by m.engel. See the first response.

    • discuss.answer
      • 40706
      • 128 Posts
      You need getService instead of addPackage

      hope the classname and path are correct:
      $modx->getService('discuss','Discuss','core/components/discuss/');
      [ed. note: m.engel last edited this post 13 years, 6 months ago.]
        • 39287
        • 13 Posts
        Thanks, Michael, I have just figured it out myself.

        Update: all works fine, thanks again.
        [ed. note: afterdark last edited this post 13 years, 6 months ago.]
          • 44167
          • 1 Posts
          hello please can tell me how you solved the problem
            • 39287
            • 13 Posts
            Hi,

            It was just a one-time task for me and a while ago, so I don't quite remember what was the issue. Please see the whole script that worked for me. Hope this helps.

            PS: Please don't blame my code: I know it's crap, it was quick and dirty, but it solved my task. ))




            <?
            
            /*
            
            A simle class that parses Wordpress export XML and creates a modx Discuss topics and threads based on it. 
            Authors are syncronized by email, if Modx author with corresponding email does not exist, wpParser creates one.
            
            Usage in snippet: 
            
            require_once('../path/to/file/wpParser.class.php');
            $parser = new wpParser('/path/to/file/wp.xml');
            return $parser->printLog();
            
            */
            
            
            class wpParser {
            	
            	protected $output;
            	
            	
            	function __construct($filename, $loglevel = 100) {
            		
            		global $modx;
            		
            		if ($this->checkFile($filename)) {
            		
            		
            			$this->setLogLevel($loglevel);
            		
            			$this->xml = $this->loadFile($filename); 
            			if (is_object($this->xml))
            				$this->log(20, 'Loaded XML');
            			else 
            				$this->log(0, 'Can\'t open the file');
            			
            			$this->namespaces = $this->xml->getNamespaces(true);
            		
            		
            			$this->initialize();
            			
            				
            			// process authors and create ModX and Discuss authors
            			$this->processAuthors();
            			
            
            			$posts = $this->xml->channel->item;
            			
            			// process posts			
            			$i=0;
            			foreach ($posts as $wpPost)
            			{
            				
            				
            				$this->log(30, 'Post '.$i++ );
            				
            				if ((string)$wpPost->title == '') {
            					
            					$this->log(30, 'No title, skipping' ); continue;
            					
            				}
            				
            				$dc = $wpPost->children($this->namespaces['dc']);
            				$wp = $wpPost->children($this->namespaces['wp']);
            				$content = $wpPost->children($this->namespaces['content']);
            				
            				if ((string)$wp->status != 'publish' || (string)$wpPost->title == '') {
            					
            					$this->log(10, 'Post not published, skipping' ); continue;
            					
            				}
            				
            
            				
            				$this->log(30, (string)$wpPost->title );
            				
            				
            				if (isset($this->authors[(string)$dc->creator])) {
            					
            					$authorId = $this->authors[(string)$dc->creator]['discussId'];
            					
            				} 
            					
            					
            								
            				
            				$postArray = 
            					
            					array(
            				
            						'board' => 7,
            						'title' => (string)$wpPost->title,
            						'message' => strip_tags((string)$content->encoded),
            						'author' => $authorId,
            						'createdon' => strtotime((string)$wp->post_date),
            						'editedby' => 0,
            						'editedon' => null,
            						'icon' => '',
            						'allow_replies' => 0,
            						'ip' => '127.0.0.1',
            						'integrated_id' => (string)$wp->post_id,
            						'comments' => array()
            	
            					);
            					
            
            				if (isset($wp->comment)) {
            					$this->log(20, 'Comments found'); 
            					$replies = 0;
            					
            					
            					foreach($wp->comment as $comment) {
            						
            						$this->log(30, 'Comment: '.$comment->comment_content); 
            						
            						// get rank of the parent comment if it exists
            						$email = (string)$comment->comment_author_email;
            						$disUser = $modx->getObject('disUser', array('email' => $email));
            						$commentAuthorId = $disUser->get('id');
            							
            						
            						$commentArray = array(
            							
            							'board' => 7,
            							'parent' => (string)$comment->comment_parent, 
            							'title' => 'RE: '.(string)$wpPost->title,
            							'message' => (string)$comment->comment_content,
            							'author' => $commentAuthorId, 
            							'createdon' => strtotime((string)$comment->comment_date),
            							'editedby' => 0,
            							'editedon' => null,
            							'icon' => '',
            							'allow_replies' => 0,
            							'ip' => '127.0.0.1',
            							'integrated_id' => (string)$wp->post_id.'000'.(string)$comment->comment_id,
            							'answer' => 0							
            						
            						);
            						
            						
            						$postArray['comments'][(string)$wp->post_id.'000'.(string)$comment->comment_id] = $commentArray;
            						
            
            					}
            				}		
            					
            					
            			// create Discuss thread
            					
            					$threadArray = array(
            					
            						'class_key' => 'disThreadDiscussion',
            						'board' => 7, 
            						'title' => (string)$wpPost->title,
            						'post_first' => 0,
            						'post_last' => 0,
            						'post_last_on' => strtotime((string)$wp->post_date),
            						'author_first' => $authorId,
            						'author_last' => '',
            						'replies' => 0,
            						'views' => 0,
            						'locked' => 1,
            						'answered' => 0,
            						'sticky' => (string)$wp->is_sticky, 
            						'private' => 0,
            						'users' => '',
            						'last_view_ip' => '',
            						'integrated_id' => (string)$wp->post_id,
            						'participants' => '',
            						'post' => $postArray
            					
            					);					
            					
            					
            					$this->threads[(string)$wp->post_id] = $threadArray;					
            					
            								
            			}
            			
            			
            				
            			$this->log(10, 'Processed '.$this->threadCount.' threads and '.$this->postCount.' posts');
            			
            			$output .= '<div class="row"><div class="span8">title</div><div class="span2">date</div><div class="span2">author</div></div><hr/>';
            			
            			foreach ($this->threads as $thread) {
            				
            
            							
            							
            				$disThread = $this->savePost($thread, 'disThread');
            				if ($disThread) {
            					
            					$thread['post']['thread'] = $disThread->get('id');
            					$disPost = $this->savePost($thread['post'], 'disPost');
            					
            					$disThread->set('post_first', $disPost->get('id'));
            					$disThread->save();
            
            					$output = '<div class="row">
            								<div class="span6">'.$disThread->get('title').'</div>
            								<div class="span1">'.$disThread->get('id').'</div>
            								<div class="span1">'.$disThread->get('post_first').'</div>
            								<div class="span2">'.$thread['createdon'].'</div>
            								<div class="span2">'.$thread['author'].'</div>
            							</div>';
            								
            					$this->log(20, $output);
            					
            					$i = 1; $iid = array();
            					
            					foreach ($thread['post']['comments'] as $id => $comment) {
            	
            				
            						$comment['thread'] = $disThread->get('id');
            						
            						$disComment = $this->savePost($comment, 'disPost');
            						
            					$output = '<div class="row">
            								<div class="span1">'.$i++.'</div>
            								<div class="span7">'.$comment['title'].'</div>
            								<div class="span2">'.$comment['createdon'].'</div>
            								<div class="span2">'.$comment['author'].'</div>
            							</div>';
            							
            					$this->log(20, $output);
            							
            											
            					}
            				}
            				
            			}
            			
            			$this->output .= $output;
            			
            			
            			
            		} else $this->log(0, 'File not found!');
            		
            		
            		
            
            		
            	}
            	
            	
            	
            	function getPostByExternalId($id, $type = 'disPost') {
            		global $modx;
            		$postArray = $modx->getObject($type,array(
            											    'integrated_id' => $id
            											));
            											
            		return $postArray;
            		
            		return false;									
            
            	}
            	
            	function savePost($post, $type='disPost') {
            
            		global $modx;	
            		
            		$this->log(20, 'Got a '.$type.': id='.$post['integrated_id'].' title='.$post['title']);
            		
            		$myPost = $this->getPostByExternalId($post['integrated_id'], $type);
            		
            		if (!$myPost) {
            			$this->log(20, 'Creating new '.$type);
            			
            			//			
            			$myPost = $modx->newObject($type, $post);
            
            			$ok = $myPost->save();
            			if (!$ok) {
            
            				$this->log(0, 'Could not create a new '.$type);
            				return false;
            			} else $this->log(20, 'Created a '.$type.' with id '.$myPost->get('id'));
            		
            		} else 
            		
            		{ 	
            			
            			$this->log(20, $type.' with external id '.$myPost->get('integrated_id').' already exists. Updating '.$type.' '.$myPost->get('id') );
            			foreach ($post as $key=>$val) 
            				$myPost->set($key, $val);
            				
            			//  Comment the next line to run the script without changing any data. 
            			
            			$myPost->save();	
            			
            			//
            			
            			
            			$this->log(20, $type.' with external id '.$myPost->get('integrated_id').' updated '.$type.' '.$myPost->get('id') );
            		}
            		
            		return $myPost;
            	
            	}
            	
            
            	
            	
            	function checkFile($filename) { return true; }
            	
            	function loadFile($filename) {
            		
            		return simplexml_load_file($filename);		
            	}
            	
            	function initialize() {
            		
            		$this->authors = array();
            		$this->threads = array();
            		$this->posts = array();
            		
            		$this->output = 'Import from WordPress<hr/>';
            		$this->postCount = 0;
            		$this->threadCount = 0;		
                    
                     $this->errType = array(
                            0 => 'FATAL ERROR',
                    		5 => 'ERROR', 
                    		10 => 'WARNING', 
                    		20 => 'NOTICE',
                    		30 => 'INFO'
                     );        
            		
            		
            		
            	}
            	
            	
            	// ****************** Authors **********************//
            	
            	function authorEmailExists($email) {
            		
            		foreach ($this->authors as $author) 
            			if ($author['email'] == $email) 
            				return true;  
            		
            		return false;
            		
            	}
            	
            	
            	function getAuthorByEmail($email, $userData = false) {
            		global $modx;
            
            		$userArray = $modx->getCollection('modUserProfile',array(
            											    'email' => $email
            											));
            											
            		foreach ($userArray as $user) return $user->User; 
            		
            		$this->log(5, 'author with email '.$email.' not found!');
            		
            		if ($userData) {
            			
            			$this->log(10, 'User data is provided, trying to create a user: '.$userData['name']);
            			return $this->addUser($userData);
            			
            		}
            		
            		return false;	
            	}
            	
            	
            	function addUser($userData) {
            		global $modx; 
            		
            		$output = false;
            		$user = $modx->newObject('modUser', array ('username'=>'__'.$userData['email']));
            		$userProfile = $modx->newObject('modUserProfile');
            		$userProfile->set('fullname',$userData['name']);
            		$userProfile->set('email', $userData['email']);
            		$success = $user->addOne($userProfile);
            		if ($success) {
            		    $OK = $user->save();
            		     if ($OK) { 
            		     	$output= $user;
            		     	$this->log(20, 'Created a user with id: '.$user->get('id'));
            		     } else 
                         	$this->log(5, 'Could not save a user: '.$userData['email']);
            		} else {
            		     $this->log(5, 'Could not create a user..'); return false;
            		}	
            		
            		return $output;	
            		
            	}
            		
            	
            	
            	function processAuthors() {
            			global $modx;
            			// get authors
            			$wp = $this->xml->channel->children($this->namespaces['wp']);
            			
            			$i = 0;
            			
            			foreach ($wp->author as $author)
            			{
            				
            				$this->authors[(string)$author->author_login] = array(
            				
            					'email' => (string)$author->author_email,
            					'name' => $author->author_first_name.' '.$author->author_last_name,
            					'discussId' => 0, 
            					'modxId' => 0
            					
            				);
            					
            				
            			}
            			
            			
            			$posts = $this->xml->channel->item;
            			
            			foreach ($posts as $post) {
            				
            				$wp = $post->children($this->namespaces['wp']);
            				
            				if (isset($wp->comment)) 
            					foreach($wp->comment as $comment) 						
            						if (!$this->authorEmailExists((string)$comment->comment_author_email)) 
            							$this->authors['_'.$comment->comment_author_email] = array(
            								'email' => (string)$comment->comment_author_email,
            								'name' => $comment->comment_author,
            								'discussId' => 0, 
            								'modxId' => 0							
            							);	
            				
            			}
            			
            			
            			$this->log(20, 'Found '.count($this->authors).' authors');
            		
            			$arr = array();
            		
            			foreach ($this->authors as $login => $author) {
            				
            				$modxUser = $this->getAuthorByEmail($author['email'], $author);
            				
            
            				$disUser = $modx->getObject('disUser',array(
            											    'user' => $modxUser->get('id')
            											));				
            											
            				if (!disUser) {
            				
            	
            						$disUser = $modx->newObject('disUser', array (
            																'user' => $modxUser->get('id'), 
            																'username' => $modxUser->get('username'), 
            																'email' => $author['email'],
            																'display_name' => $author['name'],
            																'use_display_name' => 1
            																
            															 ));				
            															 
            															 
            						$disUser->save();
            				
            				}
            				
            				
            				$author['discussId'] = $disUser->get('id');
            				$author['modxId'] = $modxUser->get('id');											 
            				
            				$arr[$login] = $author;
            				
            			}
            			
            			$this->authors = $arr;
            				
            		
            	}
            	
            	
            	
            	
            	
            	
            	
            	
            	
            	// ****************** Logging **********************//
            	
            	
            	function log($type, $message) {
            
            		global $errType;
            		
            		if ($type <= $this->logLevel) $this->writeLog($this->errType[$type].': '.$message);
            	}
            	
            	function writeLog($message) {
            		
            		$this->output .= $message.'<br/>';
            	
            	}
            	
            	function setLogLevel($level) {
            		
            		$this->logLevel = $level;
            		
            	}
            	
            	function printLog() {
            		
            		return $this->output;
            		
            	}
            	
            	
            }
            
            ?>