<?php

    /**
     * @package dao
     */


	 include_once( PLOG_CLASS_PATH.'class/object/object.class.php' );
	 include_once( PLOG_CLASS_PATH.'class/dao/articles.class.php' );
	 include_once( PLOG_CLASS_PATH.'plugins/linktracker/class/dao/linktrackerresult.class.php' );

    /**
	 * Implements a link tracker, an object which scans the database
	 * searching for all the links in the posts so that they can
	 * be seen/explored/analyzed together
	 */
	class LinkTracker extends Object 
	{

    	/**
         * Constructor
         */
		function LinkTracker()
		{
        	$this->Object();
		}

		/**
		 * Using a regular expression, extracts all the <a href="...">...</a>
		 * anchors from a given string, and returns an array with the results
		 */
		function _extractAnchorsFromString( $string )
		{
			preg_match_all("|<a href=\"(.+)\">(.+)</a>|U", $string, $out, PREG_PATTERN_ORDER);

			$result = Array();

			for( $i = 0; $i < count($out[1]); $i++ ) {
				$urls[$i] = $out[1][$i];
				$descs[$i] = $out[2][$i];

				if( $urls[$i] != "" && $descs[$i] != "" ) {
					$result[$i] = new LinkTrackerResult( $urls[$i], $descs[$i] );

					//print( "res-->url:".$result[$i]->getUrl()." desc:".$result[$i]->getDesc()."<br/>");
				}
			}

			return $result;
		}

		/**
		 * Scans all the post from the user and returns an array of
		 * LinkTrackerResult objects that contain all the necessary
		 * information for the link, namely the url and the description.
		 * Returns false and/or an empty array on error.
		 */
		function getLinks( $blogId )
		{
        	$articles = new Articles();
            $blogPosts = $articles->getBlogArticles( $blogId, -1, -1, 0, 1 );

			$result = Array();

			if( !$blogPosts )
				return false;

			foreach( $blogPosts as $post ) {
				$res = $this->_extractAnchorsFromString( $post->getText());

				// store the results in the array
				if( $res != false ) {
					foreach( $res as $linkinfo ) {
						$linkinfo->setRelatedPost( $post );
						array_push( $result, $linkinfo );
					}
				}
			}

			return $result;
		}
	}
?>
