<?php

/**
 * Drupal module for passing data to flash frontends through XML-RPC
 *
 * @author roger.lopez
 * @package defaultPackage
 */

/**
 * _help hook implementation
 *
 * @param string $section
 * @return string
 */
function flashxmlrpc_help($section=''){
	$output = '';
	switch ($section) {
		case "admin/modules#description":
			$output = t("XML-RPC server for flash photo gallery");
			break;
	}
	return $output;
}

/**
 * _perm hook implementation
 *
 * @return array
 */
function flashxmlrpc_perm() {
	return array('access content');
}

/**
 * _xmlrpc hook implementaion
 *
 * @return array	XMLRPC function names
 */
function flashxmlrpc_xmlrpc() {
	return array('flashxmlrpc.getNodes'	=> 'flashxmlrpc_getNodes',
               'flashxmlrpc.getFullNode' => 'flashxmlrpc_getFullNode',
               'flashxmlrpc.getView' => 'flashxmlrpc_getView');
}

/**
 * Helper function to return an array of populated node objects
 * by searching on type and title
 *
 * @param string $type	Node type to search for, if specified
 * @param string $title	Title to search for, if specified
 * @return array		Node objects populated by node_load()
 */
function _flashxmlrpc_getNodeByTitle($type=NULL, $title=NULL )
{
	$sql = "SELECT n.nid FROM {node} n WHERE n.status=1 ";
	if($type && (strtolower($type) != 'all')){
		$sql .= "AND n.type='{$type}' ";
	}
	if($title){
		$sql .= "AND n.title='{$title}' ";
    }else{
    	return array();
    }
    $sql .= "ORDER BY n.sticky DESC, n.created DESC";

	$result = db_query_range(db_rewrite_sql($sql), 0, 1);
	
	while($node = db_fetch_object($result)) {
		$nodes[] = node_load(array('nid'=>$node->nid));
	}
	
	return $nodes;
}

/**
 * Helper function to return an array of populated node objects
 * by searching on type and tag id
 *
 * @param string $type	Node type to search for, if specified
 * @param int $tid		tag id (Taxonomy) to search for, if specified
 * @param int $limit	limit search to this many records
 * @return array		Node objects populated by node_load()
 */
function _flashxmlrpc_getNodesByTagId($type=NULL, $tid=NULL, $limit=0 )
{
  if($tid){
    $sql = "SELECT n.nid FROM {term_node} t INNER JOIN {node} n ON t.nid=n.nid "
         . "WHERE n.status=1 ";
  }else{
    $sql = "SELECT n.nid FROM {node} n WHERE n.status=1 ";
  }
  if($type && (strtolower($type) != 'all')){
    $sql .= "AND n.type='{$type}' ";
  }
  if($tid){
    $sql .= "AND t.tid={$tid} ";
  }
  $sql .= "ORDER BY n.sticky DESC, n.created DESC";

	if($limit){
		$result = db_query_range(db_rewrite_sql($sql), 0, $limit);
	}else{
		$result = db_query(db_rewrite_sql($sql));
	}
	
	while($node = db_fetch_object($result)) {
		$nodes[] = node_load(array('nid'=>$node->nid));
	}
	
	return $nodes;
}

/**
 * Helper function to return an array of populated node objects
 * by searching on type and tag name
 *
 * @param string $type	Node type to search for, if specified
 * @param string $tag	tag (Taxonomy) to search for, if specified
 * @param int $limit	limit search to this many records
 * @return array		Node objects populated by node_load()
 */
function _flashxmlrpc_getNodesByTagName($type=NULL, $tag=NULL, $limit=0 )
{
	$sql = "SELECT n.nid FROM {term_node} t INNER JOIN {node} n ON t.nid=n.nid "
	     . "WHERE n.status=1 ";
	if($type && (strtolower($type) != 'all')){
		$sql .= "AND n.type='{$type}' ";
	}
	if($tag){
		$tid = _flashxmlrpc_getTid($tag);		
		$sql .= "AND t.tid={$tid} ";
    }
    $sql .= "ORDER BY n.sticky DESC, n.created DESC";

	if($limit){
		$result = db_query_range(db_rewrite_sql($sql), 0, $limit);
	}else{
		$result = db_query(db_rewrite_sql($sql));
	}
	
	while($node = db_fetch_object($result)) {
		$nodes[] = node_load(array('nid'=>$node->nid));
	}

	return $nodes;
}

/**
 * Helper function to get the tag id (tid) from the tag name
 *
 * @param string $tag
 * @return int
 */
function _flashxmlrpc_getTid($tag)
{
	$sql = "SELECT t.tid "
	     . "FROM {term_data} t "
	     . "WHERE t.name = '{$tag}' ";
	$result = db_query($sql);
	if($row = db_fetch_object($result)) {
		return $row->tid;
	}else{
		return -1;
	}
	$term = taxonomy_get_term_by_name($tag);
	return $term->tid;
	
}

/**
 * XMLRPC callback function for returning a list of nodes
 *
 * @param string $type
 * @param string $searchMethod
 * @param mixed $searchValue
 * @param int $limit
 * @return array
 */
function flashxmlrpc_getNodes($type='all', $searchMethod='all', $searchValue='', $limit=0)
{
  $debug = false;
	$flashxmlrpc_nodetypes = array( 'default'	=> array('nid'		=> 'nid',
    	     				                             'title'	=> 'title',
        	                			                 'body'		=> 'body'),
            	         			'story'	=> array(''),
                	     			'page'	=> array(''));
             
  if($debug) watchdog('flashxmlrpc', "flashxmlrpc_getNodes('$type', '$searchMethod', '$searchValue', $limit);");	
	switch(strtolower($searchMethod)){
		case 'tagname':
			$nodes = _flashxmlrpc_getNodesByTagName($type, $searchValue, $limit);
			break;
		case 'tagid':
			$nodes = _flashxmlrpc_getNodesByTagId($type, $searchValue, $limit);
			break;
		case 'title':
			$nodes = _flashxmlrpc_getNodeByTitle($type, $searchValue, $limit);
			break;
		case 'all':
			$nodes = _flashxmlrpc_getNodesByTagId($type, NULL, $limit);
			break;
		default:
			$nodes = array();
			break;
	}
  if($debug) watchdog('flashxmlrpc', '<pre>$nodes = '.print_r($nodes,true).'</pre>'); 
	if(empty($nodes)){return 'No Nodes Returned';}
	foreach($nodes as $node){
		$temp_node = array();
		foreach($flashxmlrpc_nodetypes['default'] as $key=>$val){
			if(is_array($val)){
				$temp_node[$key] = flashxmlrpc_tags($node->{$val[0]}[$val[1]]);
			}else{
				$temp_node[$key] = flashxmlrpc_tags($node->$val);
			}
		}
		// Event Handling
		if(isset($node->event_start)){
			$temp_node['start_date_long'] = format_date($node->event_start,'long');
			$temp_node['start_date_medium'] = format_date($node->event_start,'medium');
			$temp_node['start_date_short'] = format_date($node->event_start,'short');			
		}
		if(isset($node->event_end)){
			$temp_node['end_date_long'] = format_date($node->event_end,'long');
			$temp_node['end_date_medium'] = format_date($node->event_end,'medium');
			$temp_node['end_date_short'] = format_date($node->event_end,'short');			
		}
		// Image Handling
		if(isset($node->images)){
			foreach($node->images as $key=>$val){
				if($key=='_original'){
					$temp_node['fullsize'] = $val;
				}else{
					$temp_node[$key] = $val;
				}
			}
		}
    if(isset($node->iid)){
      $img = node_load($node->iid);
      $temp_node['attached_image'] = $img->images;
      $temp_node['attached_image']['fullsize'] = $img->images['_original'];  
    }
		if(key_exists($node->type, $flashxmlrpc_nodetypes)){
			foreach($flashxmlrpc_nodetypes[$node->type] as $key=>$val){
				if(is_array($val)){
					$temp_node[$key] = $node->{$val[0]}[$val[1]];
				}else{
					$temp_node[$key] = $node->$val;
				}
			}
		}elseif(preg_match('/^content[_-]/', $node->type)){
			foreach(array_keys((array)$node) as $key){
				if(preg_match('/^field_(.*)$/', $key, $matches)){
					$temp_node[$matches[1]] = flashxmlrpc_tags($node->{$key}[0]['value']);
				}
			}
		}
		$return_nodes[] = $temp_node;
	}
  if($debug) watchdog('flashxmlrpc', '<pre>$return_nodes = '.print_r($return_nodes,true).'</pre>'); 
	return $return_nodes;
}

function flashxmlrpc_tags($str){
  $search = array('<em>','</em>');
  $replace = array('<i>','</i>');
  $safe_str = str_replace($search, $replace, $str);
  return $safe_str;
}

function flashxmlrpc_getFullNode($nid)
{
	return node_load($nid);
}

function flashxmlrpc_getView($name, $load=false, $args=NULL){
  if(!module_exist('views')){
    return false;
  }
  $view = views_get_view($name);
  $info = views_build_view('items', $view, $args);
  if($load){
    foreach($info['items'] as $node){
      $items[] = theme('flashxmlrpc_view_results',$name,node_load($node->nid));
    }
    return $items;
  }else{
    return $info['items'];
  }
}

function theme_flashxmlrpc_view_results($viewname,$node){
  return $node;
}
  
/*** Deprecated functions below ***/
function flashxmlrpc_getImages($tag, $limit=0)
{
	$nodes = _flashxmlrpc_getNodesByTagName('image',$tag, $limit);
	
	foreach($nodes as $node)
	{
		$images[] = array('nid'			=> $node->nid,
    					  'title'		=> $node->title,
						  'fullsize'	=> 'files/'.$node->images['_original'],
						  'preview'		=> 'files/'.$node->images['preview'],
						  'thumbnail'	=> 'files/'.$node->images['thumbnail']);
	}
	
	return $images;
}

function flashxmlrpc_getMP3s($tag, $limit=0)
{
	$nodes = _flashxmlrpc_getNodesByTagName('node_mp3', $tag, $limit);
	
	foreach($nodes as $node)
	{
		$mp3s[] = array('nid'		=> $node->nid,
    			  	    'title'		=> $node->title,
						'mp3file'	=> $node->mp3file);
	}
	
	return $mp3s;
}

function flashxmlrpc_getStories($tag, $limit=0)
{
	$nodes = _flashxmlrpc_getNodesByTagName('story', $tag, $limit);
	
	foreach($nodes as $node)
	{
		$stories[] = array('nid'	=> $node->nid,
						   'title'	=> $node->title,
						   'body'	=> $node->body);
	}
	
	return $stories;
}

function flashxmlrpc_getPages($tag, $limit=0)
{
	$nodes = _flashxmlrpc_getNodesByTagName('story', $tag, $limit);
	
	foreach($nodes as $node)
	{
		$pages[] = array('nid'		=> $node->nid,
						 'title'	=> $node->title,
						 'body'		=> $node->body);
	}
	
	return $pages;
}

