<?php
// Pull in the NuSOAP code
	require_once('lib/nusoap.php');
// Create the server instance
	$server = new soap_server();
// Initialize WSDL support
	$server->configureWSDL('PubML', 'urn:pubmlwsdl');
	
// Authenticate	the users from server with License key
	function doAuthenticate(){    
		if(isset($_SERVER['PHP_AUTH_USER']) and isset($_SERVER['PHP_AUTH_PW']) ){
			if($_SERVER['PHP_AUTH_USER']=="pubml" and $_SERVER['PHP_AUTH_PW']=="123456" )
				return true;
			else
				return  false;         
		}
	}	

	$server->wsdl->addComplexType(
		'Chapter',
		'complexType',
		'struct',
		'all',
		'',
		array(
			'url' 		=> array('name' => 'url', 'type' => 'xsd:string'),
			'title' 	=> array('name' => 'title', 'type' => 'xsd:string'),
			'heading' 	=> array('name' => 'heading', 'type' => 'xsd:string'),
			'type' 	=> array('name' => 'type', 'type' => 'xsd:string'),
			'css_class' 	=> array('name' => 'css_class', 'type' => 'xsd:string')
		)
	);

	$server->wsdl->addComplexType(
		'TOCArray',    	  // Name
		'complexType',    // Type Class
		'array',          // PHP Type
		'',               // Compositor
		'SOAP-ENC:Array', // Restricted Base
		array(),
		array(
			array('ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:Chapter[]')
		),
		'tns:Chapter'
	);

// Register the method to expose
	$server->register(
			'getTocData',                          	// method name
			array('license' => 'xsd:string', 'bookid' => 'xsd:string', 'item_name'=>'xsd:string', 'site_url'=>'xsd:string' , 'show_badge'=>'xsd:boolean','content' => 'tns:TOCArray', ), 									   // input parameters
			array('return' => 'xsd:string'), 		// output parameters
			'urn:pubmlwsdl',                  	   	// namespace
			'urn:pubmlwsdl#getTocData',           	// soapaction
			'rpc',                                	// style
			'encoded',                            	// use
			'Return an array of TOC'           		// documentation
	);

	function getTocData($license, $bookid, $item_name, $site_url, $showBadge, $tocData){	
	
		// Can query database and any other complex operation
		if (!doAuthenticate()){
			$tocarray =  array( 'status' =>'false', 'license' => 'invalid' , 'bookid' => $bookid, 'error'=>'authentication_failed', 'message' =>'You are not authorized to access this service' );	
			return json_encode($tocarray); 			
		}
		// Function to check license Authentication check_license_Authentication($license, $item_name, $site_url)	
		$license_status = check_license_Authentication($license, $item_name, $site_url );
	
		if($license_status == 'expired'){
			$tocarray =  array( 'status' =>'false', 'license' => 'invalid' , 'bookid' => $bookid, 'error'=>$license_status, 'message' => 'Your PubML subscription has expired. Please renew your license to update saved books or publish new ones.');	
			return json_encode($tocarray);
			
		} else if( $license_status != 'valid'){
			$tocarray =  array( 'status' =>'false', 'license' => 'invalid' , 'bookid' => $bookid, 'error'=>$license_status, 'message' => 'Please register your PubML plugin to enable previewing, embedding, and exporting.');	
			return json_encode($tocarray); 
		}			
		
		//return $bookid;
		if(!is_array($tocData)){
			$tocarray =  array( 'status' =>'false', 'license' => 'invalid' , 'bookid' => $bookid, 'error'=>'not_an_array', 'message' =>'Not an array' );	
			return json_encode($tocarray); 
		}

		$chapterArray = array();		 
			foreach($tocData as $key=>$val){
				$chapterArray[] = $val;
			}		
		$badge_path = $showBadge ? 'https://render.pubml.com/images/pubml_license_badge.png'  : 'https://render.pubml.com/images/blank_bedge.png' ;	
		$tocarray =  array('status' =>'true', 'license' => 'valid' ,'bookid' => $bookid, 'badge_path' => $badge_path , 'file' => '/data/toc.json', 'contents' =>$chapterArray, 'message' => 'Thanks for supporting PubML. Render successful!' );	
		return json_encode($tocarray);
	}
	
	
	// Register the function for the medialist.js array.
	$server->register(
			'getMediaListData',               		// method name
			array('license' => 'xsd:string', 'bookid' => 'xsd:string', 'item_name'=>'xsd:string', 'site_url'=>'xsd:string' , 'mediadata' => 'xsd:string' ), 									   // input parameters
			array('return' => 'xsd:string'), 		// output parameters
			'urn:pubmlwsdl',                  	   	// namespace
			'urn:pubmlwsdl#getMediaListData',      	// soapaction
			'rpc',                                	// style
			'encoded',                            	// use
			'Return all the media lists and the footnotes data'   // documentation
	);

	// Get the MediaList Array and return the data accordingly
	function getMediaListData($license, $bookid='0', $item_name, $site_url, $mediadata=''){	
		
		// Can query database and any other complex operation
		if (!doAuthenticate()){
			$med_array =  array( 'status' =>'false', 'license' => 'invalid' , 'bookid' => $bookid, 'error'=>'authentication_failed', 'message' =>'You are not authorized to access this service' );	
			return json_encode($med_array); 			
		}
		// Function to check license Authentication check_license_Authentication($license, $item_name, $site_url)	
		$license_status = check_license_Authentication($license, $item_name, $site_url );
				
		if($license_status == 'expired'){
			$med_array =  array( 'status' =>'false', 'license' => 'invalid' , 'bookid' => $bookid, 'error'=>$license_status, 'message' => 'Your PubML subscription has expired. Please renew your license to update saved books or publish new ones.');	
			return json_encode($med_array);
			
		} else if( $license_status != 'valid'){
			$med_array =  array( 'status' =>'false', 'license' => 'invalid' , 'bookid' => $bookid, 'error'=>$license_status, 'message' => 'Please register your PubML plugin to enable previewing, embedding, and exporting.');	
			return json_encode($med_array); 
		}
			
		// return $license." - ".$bookid." - ".$item_name." - ".$site_url." - ".$mediadata;
		$media_array = unserialize($mediadata);		
		
		// if(!is_array($media_array)){
			// $med_array =  array( 'status' =>'false', 'license' => 'invalid' , 'bookid' => $bookid, 'message' =>'Not an array' );	
			// return json_encode($med_array); 
		// }
					
				$mediaJsContent = "\n";
				$mediaJsContent = "// JavaScript File Generated for the medialist Array, Footnotes for a Valid licensed plugin.\n";				
				
				$footnoteArray .= "\n\n\n";
				$footnoteArray .= "// JavaScript Media for Footnotes array \n";
				$footnoteArray .= "var footnoteArray = new Array();\n";	

				$mapArray = "\n\n\n";
				$mapArray .= "//-----maps-----\n//https://maps.google.com/maps/ms?\n";
				$mapArray .= "var mapArray = new Array();\n";	
				
				$flickrSet = "\n\n\n";
				$flickrSet .= "//-----flickr set ids-----\n//http://www.flickr.com/photos/davebricker/sets/\n";
				$flickrSet .= "var flickrSet = new Array();\n";
				
				$movieArray = "\n\n\n";
				$movieArray .= "//-----youtube playlist ids-----\n //https://www.youtube.com/playlist?list=\n";
				$movieArray .= "var movieArray = new Array();\n";	
				
				$defaultMedia = "\n\n\n";
				$defaultMedia .= "//-----Wordpress images and other listings-----\n";
				$defaultMedia .= "var defaultMedia = new Array();\n";				
				
				$testArray = "\n\n\n";
				$testArray .= "//----- testArray for images and other listings-----\n";
				$testArray .= "var testArray = new Array();\n";
				
				$titleArray = "\n\n\n";
				$titleArray .= "//-----window titles-----\n";
				$titleArray .= "var titleArray = new Array();\n";	
				
			if(is_array($media_array)){
				foreach($media_array as  $med_type => $med_value){	
					if(!empty($med_value)){
						foreach($med_value as $m_key=> $m_val){
							// $array_data =  implode('","', $m_val);
							$array_data = is_array($m_val) ? implode('","', $m_val) : $m_val;
							
							switch ($med_type) {
								case 'map':					
										$mapArray .= "mapArray[\"$m_key\"] = [\"$array_data\"];\n" ;
										break;
								case 'youtube':
										$movieArray .= "movieArray[\"$m_key\"] = [\"$array_data\"];\n" ;
										break;
								case 'flickr':
										$flickrSet .= "flickrSet[\"$m_key\"] = [\"$array_data\"];\n" ;
										break;
								case 'wordpress':
										$defaultMedia .= "defaultMedia[\"$m_key\"] = [\"$array_data\"];\n" ;
										break;
								case 'title':
										$array_data = urldecode($array_data);	
										$titleArray .= "titleArray[\"$m_key\"] = [\"$array_data\"];\n" ;
										break;
								case 'footnotes':									
										$footnoteArray .= "footnoteArray[\"$m_key\"] = \"$array_data\";\n";
										break;	
								default:
										$defaultMedia .= "defaultMedia[\"$m_key\"] = [\"$array_data\"];\n" ;
							}									
						}
					}
				}	
			}
		$medialist = $mediaJsContent.$footnoteArray.$titleArray. $mapArray.$movieArray.$flickrSet.$defaultMedia; 
		$med_array =  array( 'status' =>'true', 'license' => 'valid' , 'bookid' => $bookid,  'mediadata' =>$medialist, 'message' => 'Thanks for supporting PubML. Render successful!' );	
		return json_encode($med_array); 
	}
	
	
	// Register the function for the check validate the data on the server.
	$server->register(
			'getPluginStatus',                    	// method name
			array('license' => 'xsd:string', 'bookid' => 'xsd:string', 'item_name'=>'xsd:string', 'site_url'=>'xsd:string' ),	// input parameters
			array('return' => 'xsd:string'), 		// output parameters
			'urn:pubmlwsdl',                  	   	// namespace
			'urn:pubmlwsdl#getPluginStatus',      	// soapaction
			'rpc',                                	// style
			'encoded',                            	// use
			'Validate the data on the server'   	// documentation
	);

	// Get the Plugin Status Array and return the status accordingly
	function getPluginStatus($license, $bookid='0', $item_name, $site_url){
	
		// Can query database and any other complex operation
		if (!doAuthenticate()){
			$status_arr =  array( 'status' =>'false', 'license' => 'invalid' , 'bookid' => $bookid, 'error'=>'authentication_failed', 'message' =>'You are not authorized to access this service' );	
			return json_encode($status_arr); 			
		}
		// Function to check license Authentication check_license_Authentication($license, $item_name, $site_url)	
		$license_status = check_license_Authentication($license, $item_name, $site_url );
			
		if($license_status == 'expired'){
			$status_arr =  array( 'status' =>'false', 'license' => 'invalid' , 'bookid' => $bookid, 'error'=>$license_status, 'message' => 'Your PubML subscription has expired. Please renew your license to update saved books or publish new ones.');	
			return json_encode($status_arr);			
		} else if( $license_status != 'valid'){
			$status_arr =  array( 'status' =>'false', 'license' => 'invalid' , 'bookid' => $bookid, 'error'=>$license_status, 'message' => 'Please register your PubML plugin to enable previewing, embedding, and exporting.');	
			return json_encode($status_arr); 
		}
		//return $bookid;		
		$status_arr = array('status' =>'true', 'license' => 'valid' ,'bookid' => $bookid, 'error'=>'', 'message' => 'Thanks for supporting PubML. Render successful!');
		return json_encode($status_arr);
	}
	
	// Register the function for the check validate the data on the server.
	$server->register(
			'getOPFData',                    		// method name
			array('license' => 'xsd:string', 'item_name'=>'xsd:string', 'site_url'=>'xsd:string', 'content'=>'xsd:string', 'content_type'=>'xsd:string' ),	// input parameters 
			array('return' => 'xsd:string'), 		// output parameters
			'urn:pubmlwsdl',                  	   	// namespace
			'urn:pubmlwsdl#getOPFData',      		// soapaction
			'rpc',                                	// style
			'encoded',                            	// use
			'validate opf Data for the epub Books'  		// documentation
	);
	
	// Get the Plugin Status Array and return the status accordingly
	function getOPFData($license, $item_name, $site_url, $content, $content_type = 'opf'  ){
	
		// Can query database and any other complex operation
		if (!doAuthenticate()){
			$status_arr =  array( 'status' =>'false', 'license' => 'invalid', 'error'=>'authentication_failed', 'message' =>'You are not authorized to access this service' );	
			return json_encode($status_arr); 			
		}
		// Function to check license Authentication check_license_Authentication($license, $item_name, $site_url)	
		$license_status = check_license_Authentication($license, $item_name, $site_url );
			
		if($license_status == 'expired'){
			$status_arr =  array( 'status' =>'false', 'license' => 'invalid' ,'error'=>$license_status, 'message' => 'Your PubML subscription has expired. Please renew your license to update saved books or publish new ones.');	
			return json_encode($status_arr);			
		} else if( $license_status != 'valid'){
			$status_arr =  array( 'status' =>'false', 'license' => 'invalid', 'error'=>$license_status, 'message' => 'Please register your PubML plugin to enable previewing, embedding, and exporting.');	
			return json_encode($status_arr); 
		}
		//return $bookid;	
		$xmlelm = new SimpleXMLElement($content);
		
			if($content_type == 'opf'){	
				$meta = $xmlelm->metadata->addChild('meta'); // uses the metadata tag
					$meta['name']= 'license';
					$meta['content']= 'valid';

				$meta = $xmlelm->metadata->addChild('meta'); // uses the metadata tag
					$meta['name']= 'render';
					$meta['content']= 'Thanks for supporting PubML. Render successful!';
			
			} else if($content_type == 'ncx'){
				$meta = $xmlelm->head->addChild('meta'); // uses the head tag
					$meta['name']= 'license';
					$meta['content']= 'valid';

				$meta = $xmlelm->head->addChild('meta'); // uses the head tag
					$meta['name']= 'render';
					$meta['content']= 'Thanks for supporting PubML. Render successful!';
			
			}	
		
		$new_opfdata = $xmlelm->asXML();
			
		$status_arr = array('status' =>'true', 'license' => 'valid', 'content' => $new_opfdata, 'message' => 'Thanks for supporting PubML. Render successful!');
		return json_encode($status_arr);
	}
	
	// Function to check license Authentication check_license_Authentication($license, $plugin_name, $site_url)	
	function check_license_Authentication($license_key, $plugin_name, $site_url){
		
			if(!trim($license_key)){
				return 'empty_license_key';				
			}
			if(!trim($plugin_name)){
				return 'empty_plugin_name';				
			}
			if(!trim($site_url)){
				return 'empty_domain_name';				
			}
						
			// $site_url = urlencode('http://bma.in/pubml/'); 	// user the  ex: http://www.myserver.com 
			$plugin_name = urlencode($plugin_name);				// $plugin_name = 'PubML eBook Publisher Plugin';
									
				$ch = curl_init();				
				// $license_key= 'dd4d480c412d4e7688a1f13251f3351f';				
				curl_setopt($ch, CURLOPT_URL, "http://pubml.com/?edd_action=check_license&license=$license_key&item_name=$plugin_name&url=$site_url");
				curl_setopt($ch, CURLOPT_PORT, 80);
				curl_setopt($ch, CURLOPT_VERBOSE, 0); 
				curl_setopt($ch, CURLOPT_HEADER, 0); 
				curl_setopt($ch, CURLOPT_POST, 0); 
				curl_setopt($ch, CURLOPT_REFERER, $site_url); // USE CURLOPT_REFERER to set the referer 
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
				//curl_setopt($ch, CURLOPT_POSTFIELDS, $data); 
				
			$ans_xml = curl_exec($ch);
			$resultData = json_decode($ans_xml, true);
			
			if(empty($resultData['license'])){
				return 'invalid';
			}
		return $resultData['license'];
	}

// Use the request to (try to) invoke the service
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>