php and mysql

Download php and mysql

If you can't read please download the document

Upload: vuonghanh

Post on 08-Dec-2016

216 views

Category:

Documents


0 download

TRANSCRIPT

PHP.AND.MYSQL, 2e/examples/chapter0/freight.htm

DistanceCost

505

10010

15015

20020

25025

PHP.AND.MYSQL, 2e/examples/chapter0/freight.php

DistanceCost

\n $distance

\n"; echo " ". $distance / 10 ."

\n\n"; $distance += 50; }?>

PHP.AND.MYSQL, 2e/examples/chapter0/orderfor.htm

ItemQuantity

Tires

Oil

Spark Plugs

PHP.AND.MYSQL, 2e/examples/chapter0/processo.php

Bob's Auto Parts

Order Results

PHP.AND.MYSQL, 2e/examples/chapter01/freight.html

DistanceCost

505

10010

15015

20020

25025

PHP.AND.MYSQL, 2e/examples/chapter01/freight.php

DistanceCost

\n $distance

\n"; echo " ". $distance / 10 ."

\n\n"; $distance += 50; }?>

PHP.AND.MYSQL, 2e/examples/chapter01/orderform.html

ItemQuantity

Tires

Oil

Spark Plugs

PHP.AND.MYSQL, 2e/examples/chapter01/processorder.php

Bob's Auto Parts

Order Results

PHP.AND.MYSQL, 2e/examples/chapter02/orderform.html

Bob's Auto Parts

Order Form

ItemQuantity

Tires

Oil

Spark Plugs

Shipping Address

PHP.AND.MYSQL, 2e/examples/chapter02/orders.txt15:42, 20th April 4 tires 1 oil 6 spark plugs $434.00 22 Short St, Smalltown15:43, 20th April 1 tires 0 oil 0 spark plugs $100.00 33 Main Rd, Newtown15:43, 20th April 0 tires 1 oil 4 spark plugs $26.00 127 Acacia St, Springfield

PHP.AND.MYSQL, 2e/examples/chapter02/processorder.php

Bob's Auto Parts - Order Results

Bob's Auto PartsOrder Results

PHP.AND.MYSQL, 2e/examples/chapter02/vieworders.php

Bob's Auto Parts - Customer Orders

Bob's Auto PartsCustomer Orders

PHP.AND.MYSQL, 2e/examples/chapter03/bobs_front_page.php

Bob's Auto Parts

Bob's Auto Parts

PHP.AND.MYSQL, 2e/examples/chapter03/vieworders.php

PHP.AND.MYSQL, 2e/examples/chapter03/vieworders2.php

Bob's Auto Parts - Customer Orders

Bob's Auto PartsCustomer Orders

PHP.AND.MYSQL, 2e/examples/chapter25/admin_fns.php

Price:


Old password: New password: Repeat new password:
_products; }

function totalResults() { return $this->_totalResults; }

function getProduct($i) { if(isset($this->_products[$i])) return $this->_products[$i] ; else return false; }

// Perform a query to get a page full of products from a browse node // Switch between XML/HTTP and SOAP in constants.php // Returns an array of Products function browseNodeSearch($browseNode, $page, $mode) { if(METHOD=='SOAP') { // the NuSOAP class generates a lot of notices. Turn them off. error_reporting(error_reporting() & ~E_NOTICE); $soapclient = new soapclient( 'http://soap.amazon.com/schemas2/AmazonWebServices.wsdl', 'wsdl'); $soap_proxy = $soapclient->getProxy(); $parameters['mode']=$mode; $parameters['page']=$page; $parameters['type']='heavy'; $parameters['tag']=$this->_assocID; $parameters['devtag']=$this->_devTag; $parameters['sort']='+salesrank'; $parameters['browse_node'] = $browseNode; // perform actual soap query $result = $soap_proxy->BrowseNodeSearchRequest($parameters); if(isSOAPError($result)) return false; $this->_totalResults = $result['TotalResults']; $counter = 0; foreach($result['Details'] as $product) { $this->_products[$counter] = new Product; $this->_products[$counter]->soap = $result['Details'][$counter]; $counter++; } unset($soapclient); unset($soap_proxy); } else { // form URL and call parseXML to download and parse it $this->_type = 'browse'; $this->_browseNode = $browseNode; $this->_page = $page; $this->_mode = $mode; $this->_url = 'http://xml.amazon.com/onca/xml2?t='.ASSOCIATEID .'&dev-t='.DEVTAG.'&BrowseNodeSearch=' .$this->_browseNode.'&mode='.$this->_mode .'&type=heavy&page='.$this->_page.'&sort=+salesrank&f=xml'; $this->parseXML(); } return $this->_products; } // Given an ASIN, get the URL of the large image // Returns a string function getImageUrlLarge($ASIN, $mode) { if( $this->_products[0]->imageURLLarge()) return $this->_products[0]->imageURLLarge(); $this->ASINSearch($ASIN, $mode); return $this->_products[0]->imageURLLarge(); } // Perform a query to get a products with specified ASIN // Switch between XML/HTTP and SOAP in constants.php // Returns a Products object function ASINSearch($ASIN, $mode = 'books') { $this->_type = 'ASIN'; $this->_ASIN=$ASIN; $this->_mode = $mode; $ASIN = padASIN($ASIN);

if(METHOD=='SOAP') { error_reporting(E_ALL & ~E_NOTICE); $soapclient = new soapclient ( 'http://soap.amazon.com/schemas2/AmazonWebServices.wsdl', 'wsdl') ; $soap_proxy = $soapclient->getProxy(); $parameters['asin']=$ASIN; $parameters['mode']=$mode; $parameters['type']="heavy"; $parameters['tag']=$this->_assocID; $parameters['devtag']=$this->_devTag; $result = $soap_proxy->AsinSearchRequest($parameters); if(isSOAPError($result)) { print_r($result); return false; } $this->_products[0] = new Product; $this->_products[0]->soap = $result['Details'][0]; $this->_totalResults=1; unset($soapclient); unset($soap_proxy); } else { // form URL and call parseXML to download and parse it $this->_url = 'http://xml.amazon.com/onca/xml2?t='.ASSOCIATEID .'&dev-t='.DEVTAG.'&AsinSearch=' .$this->_ASIN .'&type=heavy&f=xml'; $this->parseXML(); } return $this->_products[0]; } // Perform a query to get a page full of products with a keyword search // Switch between XML/HTTP and SOAP in index.php // Returns an array of Products function keywordSearch($search, $page, $mode = 'books') { if(METHOD=='SOAP') { error_reporting(E_ALL & ~E_NOTICE); $soapclient = new soapclient( 'http://soap.amazon.com/schemas2/AmazonWebServices.wsdl','wsdl'); $soap_proxy = $soapclient->getProxy(); $parameters['mode']=$mode; $parameters['page']=$page; $parameters['type']="heavy"; $parameters['tag']=$this->_assocID; $parameters['devtag']=$this->_devTag; $parameters['sort']='+salesrank'; $parameters['keyword'] = $search; // perform actual soap request $result = $soap_proxy->KeywordSearchRequest($parameters); if(isSOAPError($result) ) return false; $counter = 0; foreach($result['Details'] as $product) { $this->_products[$counter] = new Product; $this->_products[$counter]->soap = $result['Details'][$counter]; $counter++; } $this->_totalResults = $result['TotalResults'] ; unset($soapclient); unset($soap_proxy); } else { $this->_type = 'search'; $this->_search=$search; $this->_page = $page; $search = urlencode($search); $this->_mode = $mode; $this->_url = 'http://xml.amazon.com/onca/xml2?t='.ASSOCIATEID .'&dev-t='.DEVTAG.'&KeywordSearch=' .$search.'&mode='.$this->_mode .'&type=heavy&page=' .$this->_page .'&sort=+salesrank&f=xml'; $this->parseXML(); } return $this->_products; } // Parse the XML into Product object(s) function parseXML() { $xml_parser = xml_parser_create(); xml_parser_set_option($xml_parser,XML_OPTION_SKIP_WHITE,1); xml_set_object($xml_parser, $this); xml_set_element_handler($xml_parser, "startElementHandler", "endElementHandler"); xml_set_character_data_handler($xml_parser, 'cdataHandler');

if (!($fp = fopen($this->_url, "r"))) { die("could not open XML input"); } while ($data = fread($fp, 4096)) { if (!xml_parse($xml_parser, $data, feof($fp))) { die(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser))); } } xml_parser_free($xml_parser) ; }

// function to catch callbacks when the XML parser reaches the start // of a new element function startElementHandler($parser, $name, $attributes) { array_push($this->_names, $name); if($name=='DETAILS') { $this->_currentProduct = new Product(); } if($name == 'BROWSENODE') { $this->_currentProduct->_currentBrowseName++; } if($name == 'CUSTOMERREVIEW') { $this->_currentProduct->_currentReview++; } } // function to catch callbacks when the XML parser has data from // an element function cdataHandler($parser, $cdata) { $this->_currentName = array_slice($this->_names, -1, 1); $this->_currentName = $this->_currentName[0] ; switch($this->_currentName) { case 'TOTALRESULTS' : $this->_totalResults = $cdata; break; case 'DETAILS' : break; case 'AUTHOR' : $this->_currentProduct->authors[] = $cdata; break; case 'RATING' : case 'SUMMARY' : case 'COMMENT' : @$this->_currentProduct-> customerReviews[$this->_currentProduct->_currentReview] [$this->_currentName] .= $cdata; // fields that may contain returns and &s need to be concatenated // concatenation will give a notice if they are enabled - // hence the @ break; case 'LISTID' : $this->_currentProduct->listIDs[] = $cdata; break; case 'BROWSENAME' : @$this->_currentProduct->browseNames[$this->_currentProduct->_ currentBrowseName] .= $cdata; // fields that may contain returns and &s need to be concatenated // concatenation will give a notice if they are enabled - // hence the @ break; case 'PRODUCT' : $this->_currentProduct->similarProducts[] = $cdata; break; // there are certain keys we are dealing with the // children of separately so can ignore case 'CUSTOMERREVIEW' : case 'AUTHORS' : case 'BROWSELIST' : case 'BROWSENODE' : case 'LISTS' : case 'REVIEWS' : case 'SIMILARPRODUCTS' : //do nothing break; default : @$this->_currentProduct->nodes[$this->_currentName] .= $cdata; break; } }

// function to get callbacks when the XML parser reaches an end of element function endElementHandler($parser, $name) { if($name=='DETAILS') { //these are no longer required unset($this->_currentProduct->_currentReview); unset($this->_currentProduct->_currentBrowseName); array_push($this->_products, $this->_currentProduct); } array_pop($this->_names); }}? >

PHP.AND.MYSQL, 2e/examples/chapter25/bookdisp.php

PHP.AND.MYSQL, 2e/examples/chapter25/data_valid_fns.php

PHP.AND.MYSQL, 2e/examples/chapter25/db_fns.php

PHP.AND.MYSQL, 2e/examples/chapter25/delete_book.php

PHP.AND.MYSQL, 2e/examples/chapter25/delete_category.php

PHP.AND.MYSQL, 2e/examples/chapter25/edit_book.php

PHP.AND.MYSQL, 2e/examples/chapter25/edit_book_form.php

PHP.AND.MYSQL, 2e/examples/chapter25/edit_category.php

PHP.AND.MYSQL, 2e/examples/chapter25/edit_category_form.php

PHP.AND.MYSQL, 2e/examples/chapter25/images/0672317842.jpg

PHP.AND.MYSQL, 2e/examples/chapter25/images/0672318040.jpg

PHP.AND.MYSQL, 2e/examples/chapter25/images/0672319241.jpg

PHP.AND.MYSQL, 2e/examples/chapter25/images/add-to-cart.gif

PHP.AND.MYSQL, 2e/examples/chapter25/images/addtocar.gif

PHP.AND.MYSQL, 2e/examples/chapter25/images/admin-menu.gif

PHP.AND.MYSQL, 2e/examples/chapter25/images/back.gif

PHP.AND.MYSQL, 2e/examples/chapter25/images/Book-O-Rama.gif

PHP.AND.MYSQL, 2e/examples/chapter25/images/bookmark.gif

PHP.AND.MYSQL, 2e/examples/chapter25/images/cart.gif

PHP.AND.MYSQL, 2e/examples/chapter25/images/checkout.gif

PHP.AND.MYSQL, 2e/examples/chapter25/images/continue-shopping.gif

PHP.AND.MYSQL, 2e/examples/chapter25/images/continue.gif

PHP.AND.MYSQL, 2e/examples/chapter25/images/delete.gif

PHP.AND.MYSQL, 2e/examples/chapter25/images/details.gif

PHP.AND.MYSQL, 2e/examples/chapter25/images/edit-category.gif

PHP.AND.MYSQL, 2e/examples/chapter25/images/edit-item.gif

PHP.AND.MYSQL, 2e/examples/chapter25/images/emptycar.gif

PHP.AND.MYSQL, 2e/examples/chapter25/images/go-to-checkout.gif

PHP.AND.MYSQL, 2e/examples/chapter25/images/halfstar.gif

PHP.AND.MYSQL, 2e/examples/chapter25/images/log-out.gif

PHP.AND.MYSQL, 2e/examples/chapter25/images/outofcar.gif

PHP.AND.MYSQL, 2e/examples/chapter25/images/place_order.gif

PHP.AND.MYSQL, 2e/examples/chapter25/images/purchase.gif

PHP.AND.MYSQL, 2e/examples/chapter25/images/save-changes.gif

PHP.AND.MYSQL, 2e/examples/chapter25/images/searchno.gif

PHP.AND.MYSQL, 2e/examples/chapter25/images/star.gif

PHP.AND.MYSQL, 2e/examples/chapter25/images/tahuayo.gif

PHP.AND.MYSQL, 2e/examples/chapter25/images/view-cart.gif

PHP.AND.MYSQL, 2e/examples/chapter25/index.php

PHP.AND.MYSQL, 2e/examples/chapter25/insert_book.php

PHP.AND.MYSQL, 2e/examples/chapter25/insert_book_form.php

PHP.AND.MYSQL, 2e/examples/chapter25/insert_category.php

PHP.AND.MYSQL, 2e/examples/chapter25/insert_category_form.php

PHP.AND.MYSQL, 2e/examples/chapter25/listin10.txt// For a particular browsenode, display a page of productsfunction showBrowseNode($browseNode, $page, $mode){ $ars = getARS('browse', array('browsenode'=>$browseNode, 'page' => $page, 'mode'=>$mode)); showSummary($ars->products(), $page, $ars->totalResults(), $mode, $browseNode);}

PHP.AND.MYSQL, 2e/examples/chapter25/listin11.txt// Get an AmazonResultSet either from cache or a live query// If a live query add it to the cachefunction getARS($type, $parameters){ $cache = cached($type, $parameters); if($cache) // if found in cache { return $cache; } else { $ars = new AmazonResultSet; if($type == 'asin') $ars->ASINSearch(padASIN($parameters['asin']), $parameters['mode']); if($type == 'browse') $ars->browseNodeSearch($parameters['browsenode'], $parameters['page'], $parameters['mode']); if($type == 'search') $ars->keywordSearch($parameters['search'], $parameters['page'], $parameters['mode']); cache($type, $parameters, $ars); } return $ars;}

PHP.AND.MYSQL, 2e/examples/chapter25/listin12.txt// Perform a query to get a page full of products from a browse node// Switch between XML/HTTP and SOAP in constants.php// Returns an array of Productsfunction browseNodeSearch($browseNode, $page, $mode){ if(METHOD=='SOAP') { // the NuSOAP class generates a lot of notices. Turn them off. error_reporting(error_reporting() & ~E_NOTICE); $soapclient = new soapclient( 'http://soap.amazon.com/schemas2/AmazonWebServices.wsdl', 'wsdl'); $soap_proxy = $soapclient->getProxy(); $parameters['mode']=$mode; $parameters['page']=$page; $parameters['type']='heavy'; $parameters['tag']=$this->_assocID; $parameters['devtag']=$this->_devTag; $parameters['sort']='+salesrank'; $parameters['browse_node'] = $browseNode; // perform actual soap query $result = $soap_proxy->BrowseNodeSearchRequest($parameters) ; if(isSOAPError($result)) return false; $this->_totalResults = $result['TotalResults']; $counter = 0; foreach($result['Details'] as $product) { $this->_products[$counter] = new Product; $this->_products[$counter]->soap = $result['Details'][$counter]; $counter++; } unset($soapclient); unset($soap_proxy); } else { // form URL and call parseXML to download and parse it $this->_type = 'browse'; $this->_browseNode = $browseNode; $this->_page = $page; $this->_mode = $mode; $this->_url = 'http://xml.amazon.com/onca/xml2?t='.ASSOCIATEID .'&dev-t='.DEVTAG.'&BrowseNodeSearch=' .$this->_browseNode.'&mode='.$this->_mode .'&type=heavy&page='.$this->_page.'&sort=+salesrank&f=xml'; $this->parseXML(); } return $this->_products;}

PHP.AND.MYSQL, 2e/examples/chapter25/listing25.10.txtfunction display_cart($cart, $change = true, $images = 1){ // display items in shopping cart // optionally allow changes (true or false) // optionally include images (1 - yes, 0 - no)

global $HTTP_SESSION_VARS;

echo ' Item PriceQuantity Total';

//display each item as a table row foreach ($cart as $isbn => $qty) { $book = get_book_details($isbn); echo ''; if($images ==true) { echo ''; if (file_exists("images/$isbn.jpg")) { $size = GetImageSize('images/'.$isbn.'.jpg'); if($size[0]>0 && $size[1]>0) { echo ''; } } else echo ''; echo ''; } echo ''; echo ''.$book['title']. ' by '.$book['author']; echo '$'.number_format($book['price'], 2); echo ''; // if we allow changes, quantities are in text boxes if ($change == true) echo ''; else echo $qty; echo '$'.number_format($book['price']*$qty,2). '\n'; } // display total row echo ' '.$HTTP_SESSION_VARS['items'].' $'..number_format($HTTP_SESSION_VARS['total_price'], 2). ' '; // display save change button if($change == true) { echo ' '; } echo '';}

PHP.AND.MYSQL, 2e/examples/chapter25/listing25.11.txtfunction calculate_price($cart){ // sum total price for all items in shopping cart $price = 0.0; if(is_array($cart)) { $conn = db_connect(); foreach($cart as $isbn => $qty) { $query = "select price from books where isbn='$isbn'"; $result = mysql_query($query); if ($result) { $item_price = mysql_result($result, 0, 'price'); $price +=$item_price*$qty; } } } return $price;}

PHP.AND.MYSQL, 2e/examples/chapter25/listing25.12.txtfunction calculate_items($cart){ // sum total items in shopping cart $items = 0; if(is_array($cart)) { foreach($cart as $isbn => $qty) { $items += $qty; } } return $items;}

PHP.AND.MYSQL, 2e/examples/chapter25/listing25.15.txtfunction insert_order($order_details){ global $HTTP_SESSION_VARS;

//extract order_details out as variables extract($order_details);

//set shipping address same as address if(!$ship_name&&!$ship_address&&!$ship_city&& !$ship_state&&!$ship_zip&&!$ship_country) { $ship_name = $name; $ship_address = $address; $ship_city = $city; $ship_state = $state; $ship_zip = $zip; $ship_country = $country; }

$conn = db_connect(); //insert customer address $query = "select customerid from customers where name = '$name' and address = '$address' and city = '$city' and state = '$state' and zip = '$zip' and country = '$country'"; $result = mysql_query($query); if(mysql_numrows($result)>0) { $customer_id = mysql_result($result, 0, 'customerid'); } else { $query = "insert into customers values ('', '$name','$address','$city','$state','$zip','$country')"; $result = mysql_query($query); if (!$result) return false; } $query = "select customerid from customers where name = '$name' and address = '$address' and city = '$city' and state = '$state' and zip = '$zip' and country = '$country'"; $result = mysql_query($query); if(mysql_numrows($result)>0) $customerid = mysql_result($result, 0, 'customerid'); else return false; $date = date('Y-m-d'); $query = "insert into orders values ('', $customerid, ".$HTTP_SESSION_VARS['total_price']. ", '$date', 'PARTIAL', '$ship_name', '$ship_address','$ship_city','$ship_state','$ship_zip', '$ship_country')"; $result = mysql_query($query); if (!$result) return false;

$query = "select orderid from orders where customerid = $customerid and amount > ".$HTTP_SESSION_VARS['total_price']."-.001 and amount < ".$HTTP_SESSION_VARS['total_price']."+.001 and date = '$date' and order_status = 'PARTIAL' and ship_name = '$ship_name' and ship_address = '$ship_address' and ship_city = '$ship_city' and ship_state = '$ship_state' and ship_zip = '$ship_zip' and ship_country = '$ship_country'"; $result = mysql_query($query); if(mysql_numrows($result)>0) $orderid = mysql_result($result, 0, 'orderid'); else return false;

// insert each book foreach($HTTP_SESSION_VARS['cart'] as $isbn => $quantity) { $detail = get_book_details($isbn); $query = "delete from order_items where orderid = '$orderid' and isbn = '$isbn'"; $result = mysql_query($query); $query = "insert into order_items values ('$orderid', '$isbn', ".$detail['price'].", $quantity)"; $result = mysql_query($query); if(!$result) return false; }

return $orderid;}

PHP.AND.MYSQL, 2e/examples/chapter25/listing25.19.txtfunction display_book_form($book = '')// This displays the book form.// It is very similar to the category form.// This form can be used for inserting or editing books.// To insert, don't pass any parameters. This will set $edit// to false, and the form will go to insert_book.php.// To update, pass an array containing a book. The// form will be displayed with the old data and point to update_book.php.// It will also add a "Delete book" button.{ // if passed an existing book, proceed in "edit mode" $edit = is_array($book);

// most of the form is in plain HTML with some // optional PHP bits throughout?> Price: soap) return count($this->soap['SimilarProducts']); else return count($this->similarProducts); }

PHP.AND.MYSQL, 2e/examples/chapter25/listing7.txt// check if Amazon data is in the cache// if it is, return it// if not, return falsefunction cached($type, $parameters){ if($type == 'browse') $filename = CACHE.'/browse.'.$parameters['browsenode'].'. '.$parameters['page'].'.'.$parameters['mode'].'.dat'; if($type == 'search') $filename = CACHE.'/search.'.$parameters['search'].'. '.$parameters['page'].'.'.$parameters['mode'].'.dat'; if($type == 'asin') $filename = CACHE.'/asin.'.$parameters['asin'].' .'.$parameters['mode'].'.dat'; // is cached data missing or > 1 hour old? if(!file_exists($filename) || ((mktime() - filemtime($filename)) > 60*60)) { return false; } $data = file($filename); $data = join($data, ''); return unserialize($data);}

// add Amazon data to the cachefunction cache($type, $parameters, $data){ if($type == 'browse') $filename = CACHE.'/browse.'.$parameters['browsenode'].'.' .$parameters['page'].'.'.$parameters['mode'].'.dat'; if($type == 'search') $filename = CACHE.'/search.'.$parameters['search'].'.' .$parameters['page'].'.'.$parameters['mode'].'.dat'; if($type == 'asin') $filename = CACHE.'/asin.'.$parameters['asin'].'.' .$parameters['mode'].'.dat'; $data = serialize($data); $fp = fopen($filename, 'wb'); if(!$fp||(fwrite($fp, $data)==-1) ) { echo ('Error, could not store cache file'); } fclose($fp);}

PHP.AND.MYSQL, 2e/examples/chapter25/listing8.txt

0060518057 your-associate-id heavy your-dev-tag

PHP.AND.MYSQL, 2e/examples/chapter25/listing9.txt//display a starting list of popular categoriesfunction showCategories($mode){ global $categoryList; echo 'Selected Categories'; if($mode == 'books') { asort($categoryList); $categories = count($categoryList); $columns = 4; $rows = ceil($categories/$columns); echo ''; reset($categoryList); for($col = 0; $col $v){$atts .= " $k=\"$v\"";}} // serialize if an xsd built-in primitive type if($type != '' && isset($this->typemap[$this->XMLSchemaVersion][$type])){ return "$val"; }// detect type and serialize$xml = '';$atts = '';switch(true) {case ($type == '' && is_null($val)):$xml .= "";break;case (is_bool($val) || $type == 'boolean'):if(!$val){ $val = 0;}$xml .= "$val";break;case (is_int($val) || is_long($val) || $type == 'int'):$xml .= "$val";break;case (is_float($val)|| is_double($val) || $type == 'float'):$xml .= "$val";break;case (is_string($val) || $type == 'string'):if($this->charencoding){ $val = htmlspecialchars($val, ENT_QUOTES); }$xml .= "$val";break;case is_object($val):break;break;case (is_array($val) || $type):// detect if struct or array $keyList = array_keys($val);$valueType = 'arraySimple';foreach($keyList as $keyListValue){if(!is_int($keyListValue)){$valueType = 'arrayStruct';}} if($valueType=='arraySimple' || ereg('^ArrayOf',$type)){foreach($val as $v){ if(is_object($v) && get_class($v) == 'soapval'){ $tt = $v->type; } else {$tt = gettype($v); }$array_types[$tt] = 1;$xml .= $this->serialize_val($v,'item');$i = 0;if(is_array($v) && is_numeric(key($v))){$i += sizeof($v);} else {$i += 1;}}if(count($array_types) > 1){$array_typename = 'xsd:ur-type';} elseif(isset($this->typemap[$this->XMLSchemaVersion][$tt])) {$array_typename = 'xsd:'.$tt;} elseif($tt == 'array' || $tt == 'Array'){$array_typename = 'SOAP-ENC:Array';} else {$array_typename = $tt;}if(isset($array_types['array'])){$array_type = $i.",".$i;} else {$array_type = $i;}$xml = "".$xml."";} else {// got a structif(isset($type) && isset($type_prefix)){$type_str = " xsi:type=\"$type_prefix:$type\"";} else {$type_str = '';}$xml .= "";foreach($val as $k => $v){$xml .= $this->serialize_val($v,$k);}$xml .= "";}break;default:$xml .= 'not detected, got '.gettype($val).' for '.$val;break;}return $xml;}

/** * serialize message * * @param string body * @param string headers * @param array namespaces * @return string message * @access public */ function serializeEnvelope($body,$headers=false,$namespaces=array()){// serialize namespaces $ns_string = '';foreach(array_merge($this->namespaces,$namespaces) as $k => $v){$ns_string .= " xmlns:$k=\"$v\"";}// serialize headersif($headers){$headers = "".$headers."";}// serialize envelopereturn'debug('xmlschema class instantiated, inside constructor');// files$this->schema = $schema;$this->xml = $xml;

// parse schema fileif($schema != ''){$this->debug('initial schema file: '.$schema);$this->parseFile($schema);}

// parse xml fileif($xml != ''){$this->debug('initial xml file: '.$xml);$this->parseFile($xml);}

}

/** * parse an XML file * * @param string $xml, path/URL to XML file * @param string $type, (schema | xml)* @return boolean * @access public */function parseFile($xml,$type){// parse xml fileif($xml != ""){$this->debug('parsing $xml');$xmlStr = @join("",@file($xml));if($xmlStr == ""){$this->setError('No file at the specified URL: '.$xml);return false;} else {$this->parseString($xmlStr,$type);return true;}}return false;}

/*** parse an XML string** @param string $xml path or URL * @param string $type, (schema|xml)* @access private*/function parseString($xml,$type){// parse xml stringif($xml != ""){

// Create an XML parser. $this->parser = xml_parser_create(); // Set the options for parsing the XML data. xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0);

// Set the object for the parser. xml_set_object($this->parser, $this);

// Set the element handlers for the parser.if($type == "schema"){ xml_set_element_handler($this->parser, 'schemaStartElement','schemaEndElement'); xml_set_character_data_handler($this->parser,'schemaCharacterData');} elseif($type == "xml"){xml_set_element_handler($this->parser, 'xmlStartElement"','xmlEndElement'); xml_set_character_data_handler($this->parser,'xmlCharacterData');}

// Parse the XML file. if(!xml_parse($this->parser,$xml,true)){// Display an error message.$errstr = sprintf('XML error on line %d: %s',xml_get_current_line_number($this->parser),xml_error_string(xml_get_error_code($this->parser)));$this->debug('XML parse error: '.$errstr);$this->setError('Parser error: '.$errstr); } xml_parser_free($this->parser);} else{$this->debug('no xml passed to parseString()!!');$this->setError('no xml passed to parseString()!!');}}

/*** start-element handler** @param string $parser XML parser object* @param string $name element name* @param string $attrs associative array of attributes* @access private*/function schemaStartElement($parser, $name, $attrs) {// position in the total number of elements, starting from 0$pos = $this->position++;$depth = $this->depth++;// set self as current value for this depth$this->depth_array[$depth] = $pos;

// get element prefixif($prefix = $this->getPrefix($name)){// get unqualified name$name = $this->getLocalPart($name);} else { $prefix = ''; } // loop thru attributes, expanding, and registering namespace declarations if(count($attrs) > 0){ foreach($attrs as $k => $v){ // if ns declarations, add to class level array of valid namespacesif(ereg("^xmlns",$k)){ //$this->xdebug("$k: $v"); //$this->xdebug('ns_prefix: '.$this->getPrefix($k)); if($ns_prefix = substr(strrchr($k,':'),1)){$this->namespaces[$ns_prefix] = $v;} else {$this->namespaces['ns'.(count($this->namespaces)+1)] = $v;}if($v == 'http://www.w3.org/2001/XMLSchema' || $v == 'http://www.w3.org/1999/XMLSchema'){$this->XMLSchemaVersion = $v;$this->namespaces['xsi'] = $v.'-instance';}} // expand each attribute $k = strpos($k,':') ? $this->expandQname($k) : $k; $v = strpos($v,':') ? $this->expandQname($v) : $v; $eAttrs[$k] = $v; } $attrs = $eAttrs; } else { $attrs = array(); }// find status, register dataswitch($name){case ('all'|'choice'|'sequence')://$this->complexTypes[$this->currentComplexType]['compositor'] = 'all';$this->complexTypes[$this->currentComplexType]['compositor'] = $name;if($name == 'all'){$this->complexTypes[$this->currentComplexType]['phpType'] = 'struct';}break;case 'attribute': //$this->xdebug("parsing attribute $attrs[name] $attrs[ref] of value: ".$attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']); if(isset($attrs['name'])){$this->attributes[$attrs['name']] = $attrs;$aname = $attrs['name'];} elseif($attrs['ref']){$aname = $attrs['ref']; $this->attributes[$attrs['ref']] = $attrs;} if(isset($this->currentComplexType)){$this->complexTypes[$this->currentComplexType]['attrs'][$aname] = $attrs;} elseif(isset($this->currentElement)){$this->elements[$this->currentElement]['attrs'][$aname] = $attrs;}// arrayType attributeif($this->getLocalPart($aname) == 'arrayType'){ $this->complexTypes[$this->currentComplexType]['phpType'] = 'array';if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])){$v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'];} else {$v = '';} if(strpos($v,'[,]')){ $this->complexTypes[$this->currentComplexType]['multidimensional'] = true; } $v = substr($v,0,strpos($v,'[')); // clip the [] if(!strpos($v,':') && isset($this->typemap[$this->XMLSchemaVersion][$v])){ $v = $this->XMLSchemaVersion.':'.$v; } $this->complexTypes[$this->currentComplexType]['arrayType'] = $v;}break;case 'complexType':if(isset($attrs['name'])){$this->currentElement = false;$this->currentComplexType = $attrs['name'];$this->complexTypes[$this->currentComplexType] = $attrs;$this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType';if(isset($attrs['base']) && ereg(':Array$',$attrs['base'])){$this->complexTypes[$this->currentComplexType]['phpType'] = 'array';} else {$this->complexTypes[$this->currentComplexType]['phpType'] = 'struct';}$this->xdebug('processing complexType '.$attrs['name']);}break;case 'element':if(isset($attrs['type'])){$this->xdebug("processing element ".$attrs['name']);$this->currentElement = $attrs['name'];$this->elements[ $attrs['name'] ] = $attrs;$this->elements[ $attrs['name'] ]['typeClass'] = 'element';$ename = $attrs['name'];} elseif(isset($attrs['ref'])){$ename = $attrs['ref'];} else {$this->xdebug('adding complexType '.$attrs['name']);$this->currentComplexType = $attrs['name'];$this->complexTypes[ $attrs['name'] ] = $attrs;$this->complexTypes[ $attrs['name'] ]['element'] = 1;$this->complexTypes[$this->currentComplexType]['phpType'] = 'struct';}if(isset($ename) && $this->currentComplexType){$this->complexTypes[$this->currentComplexType]['elements'][$ename] = $attrs;}break;case 'restriction':$this->xdebug("in restriction for ct: $this->currentComplexType and ce: $this->currentElement");if($this->currentElement){$this->elements[$this->currentElement]['type'] = $attrs['base'];} elseif($this->currentComplexType){$this->complexTypes[$this->currentComplexType]['restrictionBase'] = $attrs['base'];if(strstr($attrs['base'],':') == ':Array'){$this->complexTypes[$this->currentComplexType]['phpType'] = 'array';}}break;case 'schema':$this->schema = $attrs;$this->schema['schemaVersion'] = $this->getNamespaceFromPrefix($prefix);break;case 'simpleType':$this->currentElement = $attrs['name'];$this->elements[ $attrs['name'] ] = $attrs;$this->elements[ $attrs['name'] ]['typeClass'] = 'element';break;}}

/*** end-element handler** @param string $parser XML parser object* @param string $name element name* @access private*/function schemaEndElement($parser, $name) {// position of current element is equal to the last value left in depth_array for my depthif(isset($this->depth_array[$this->depth])){ $pos = $this->depth_array[$this->depth]; }// bring depth down a notch$this->depth--;// move on...if($name == 'complexType'){$this->currentComplexType = false;$this->currentElement = false;}if($name == 'element'){$this->currentElement = false;}}

/*** element content handler** @param string $parser XML parser object* @param string $data element content* @access private*/function schemaCharacterData($parser, $data){$pos = $this->depth_array[$this->depth];$this->message[$pos]['cdata'] .= $data;}

/*** serialize the schema** @access public*/function serializeSchema(){

$schemaPrefix = $this->getPrefixFromNamespace($this->XMLSchemaVersion);$xml = '';// complex typesforeach($this->complexTypes as $typeName => $attrs){$contentStr = '';// serialize child elementsif(count($attrs['elements']) > 0){foreach($attrs['elements'] as $element => $eParts){if(isset($eParts['ref'])){$contentStr .= "";} else {$contentStr .= "";}}}// attributesif(count($attrs['attrs']) >= 1){foreach($attrs['attrs'] as $attr => $aParts){$contentStr .= '';}}// if restrictionif( isset($attrs['restrictionBase']) && $attrs['restrictionBase'] != ''){$contentStr = "".$contentStr."";}// "all" compositor obviates complex/simple contentif(isset($attrs['compositor']) && $attrs['compositor'] == 'all'){$contentStr = "".$contentStr."";}// complex or simple contentelseif( count($attrs['elements']) > 0 || count($attrs['attrs']) > 0){$contentStr = "".$contentStr."";}// compositorsif(isset($attrs['compositor']) && $attrs['compositor'] != '' && $attrs['compositor'] != 'all'){$contentStr = "".$contentStr."";}// finalize complex typeif($contentStr != ''){$contentStr = "".$contentStr."";} else {$contentStr = "";}$xml .= $contentStr;}// elementsif(isset($this->elements) && count($this->elements) > 0){foreach($this->elements as $element => $eParts){$xml .= "";}}// attributesif(isset($this->attributes) && count($this->attributes) > 0){foreach($this->attributes as $attr => $aParts){$xml .= "";}}// finish 'er up$xml = "".$xml."";return $xml;}

/*** expands a qualified name** @param string $string qname* @returnstring expanded qname* @access private*/function expandQname($qname){// get element prefixif(strpos($qname,':') && !ereg('^http://',$qname)){// get unqualified name$name = substr(strstr($qname,':'),1);// get ns prefix$prefix = substr($qname,0,strpos($qname,':'));if(isset($this->namespaces[$prefix])){return $this->namespaces[$prefix].':'.$name;} else {return $qname;}} else {return $qname;}}

/*** adds debug data to the clas level debug string** @param string $string debug data* @access private*/function xdebug($string){$this->debug(' xmlschema: '.$string);}

/** * get the PHP type of a user defined type in the schema * PHP type is kind of a misnomer since it actually returns 'struct' for assoc. arrays * returns false if no type exists, or not w/ the given namespace * else returns a string that is either a native php type, or 'struct' * * @param string $type, name of defined type * @param string $ns, namespace of type * @return mixed * @access public */function getPHPType($type,$ns){global $typemap;if(isset($typemap[$ns][$type])){//print "found type '$type' and ns $ns in typemap
";return $typemap[$ns][$type];} elseif(isset($this->complexTypes[$type])){//print "getting type '$type' and ns $ns from complexTypes array
";return $this->complexTypes[$type]['phpType'];}return false;}

/** * returns the local part of a prefixed string * returns the original string, if not prefixed * * @param string * @return string * @access public */function getLocalPart($str){if($sstr = strrchr($str,':')){// get unqualified namereturn substr( $sstr, 1 );} else {return $str;}}

/** * returns the prefix part of a prefixed string * returns false, if not prefixed * * @param string * @return mixed * @access public */function getPrefix($str){if($pos = strrpos($str,':')){// get prefixreturn substr($str,0,$pos);}return false;}

/** * pass it a prefix, it returns a namespace* returns false if no namespace registered with the given prefix * * @param string * @return mixed * @access public */function getNamespaceFromPrefix($prefix){if(isset($this->namespaces[$prefix])){return $this->namespaces[$prefix];}//$this->setError("No namespace registered for prefix '$prefix'");return false;}

/** * returns the prefix for a given namespace (or prefix) * or false if no prefixes registered for the given namespace * * @param string * @return mixed * @access public */function getPrefixFromNamespace($ns){foreach($this->namespaces as $p => $n){if($ns == $n || $ns == $p){ $this->usedNamespaces[$p] = $ns;return $p;}}return false;}

/** * returns an array of information about a given type * returns false if no type exists by the given name ** typeDef = array(* 'elements' => array(), // refs to elements array*'restrictionBase' => '',*'phpType' => '',*'order' => '(sequence|all)',*'attrs' => array() // refs to attributes array*) * * @param string * @return mixed * @access public */function getTypeDef($type){if(isset($this->complexTypes[$type])){return $this->complexTypes[$type];} elseif(isset($this->elements[$type])){return $this->elements[$type];} elseif(isset($this->attributes[$type])){return $this->attributes[$type];}return false;}

/** * returns a sample serialization of a given type, or false if no type by the given name * * @param string $type, name of type * @return mixed * @access public */ function serializeTypeDef($type){ //print "in sTD() for type $type
";if($typeDef = $this->getTypeDef($type)){$str .= 'debug('Write error');}$this->debug('wrote data to socket');// get response $this->incoming_payload = '';//$strlen = 0;while( $data = fread($fp, 32768) ){$this->incoming_payload .= $data;//$strlen += strlen($data); }$this->debug('received '.strlen($this->incoming_payload).' bytes of data from server');// close filepointerfclose($fp);$this->debug('closed socket');// connection was closed unexpectedlyif($this->incoming_payload == ''){$this->setError('no response from server');return false;}$this->debug('received incoming payload: '.strlen($this->incoming_payload));$data = $this->incoming_payload."\r\n\r\n\r\n\r\n";// remove 100 headerif(ereg('^HTTP/1.1 100',$data)){if($pos = strpos($data,"\r\n\r\n") ){$data = ltrim(substr($data,$pos));} elseif($pos = strpos($data,"\n\n") ){$data = ltrim(substr($data,$pos));}}//// separate content from HTTP headersif( $pos = strpos($data,"\r\n\r\n") ){$lb = "\r\n";} elseif( $pos = strpos($data,"\n\n") ){$lb = "\n";} else {$this->setError('no proper separation of headers and document');return false;}$header_data = trim(substr($data,0,$pos));$header_array = explode($lb,$header_data);$data = ltrim(substr($data,$pos));$this->debug('found proper separation of headers and document');$this->debug('cleaned data, stringlen: '.strlen($data));// clean headersforeach($header_array as $header_line){$arr = explode(':',$header_line);if(count($arr) >= 2){$headers[trim($arr[0])] = trim($arr[1]);}}//print "headers: $header_data
";//print "data: $data
";// decode transfer-encodingif(isset($headers['Transfer-Encoding']) && $headers['Transfer-Encoding'] == 'chunked'){//$timer->setMarker('starting to decode chunked content');if(!$data = $this->decodeChunked($data)){$this->setError('Decoding of chunked data failed');return false;}//$timer->setMarker('finished decoding of chunked content');//print "\nde-chunked:\n---------------\n$data\n\n---------------\n";}// decode content-encodingif(isset($headers['Content-Encoding']) && $headers['Content-Encoding'] != ''){if($headers['Content-Encoding'] == 'deflate' || $headers['Content-Encoding'] == 'gzip'){ // if decoding works, use it. else assume data wasn't gzencoded if(function_exists('gzinflate')){//$timer->setMarker('starting decoding of gzip/deflated content');if($headers['Content-Encoding'] == 'deflate' && $degzdata = @gzinflate($data)){ $data = $degzdata;} elseif($headers['Content-Encoding'] == 'gzip' && $degzdata = gzinflate(substr($data, 10))){$data = $degzdata;} else {$this->setError('Errors occurred when trying to decode the data');}//$timer->setMarker('finished decoding of gzip/deflated content');//print "\nde-inflated:\n---------------\n$data\n-------------\n"; } else {$this->setError('The server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');}}}if(strlen($data) == 0){$this->debug('no data after headers!');$this->setError('no data present after HTTP headers');return false;}$this->debug('end of send()');return $data;}

/*** send the SOAP message via HTTPS 1.0 using CURL** @param string $msg message data* @param integer $timeout set timeout in seconds* @returnstring data* @access public*/function sendHTTPS($data, $timeout=0) { global $t;$t->setMarker('inside sendHTTPS()');$this->debug('entered sendHTTPS() with data of length: '.strlen($data));// init CURL$ch = curl_init();$t->setMarker('got curl handle');// set proxyif($this->proxyhost && $this->proxyport){$host = $this->proxyhost;$port = $this->proxyport;} else {$host = $this->host;$port = $this->port;}// set url$hostURL = ($port != '') ? "https://$host:$port" : "https://$host";// add path$hostURL .= $this->path;curl_setopt($ch, CURLOPT_URL, $hostURL);// set other optionscurl_setopt($ch, CURLOPT_HEADER, 1);curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);// encodeif(function_exists('gzinflate')){curl_setopt($ch, CURLOPT_ENCODING, 'deflate');}// set timeoutif($timeout != 0){curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);}$credentials = '';if($this->username != '') {$credentials = 'Authorization: Basic '.base64_encode("$this->username:$this->password").'\r\n';}if($this->encoding != ''){if(function_exists('gzdeflate')){$encoding_headers = "Accept-Encoding: $this->encoding\r\n"."Connection: close\r\n";set_magic_quotes_runtime(0);}}if($this->proxyhost && $this->proxyport){$this->outgoing_payload = "POST $this->url HTTP/$this->protocol_version\r\n";} else {$this->outgoing_payload = "POST $this->path HTTP/$this->protocol_version\r\n";}$this->outgoing_payload .="User-Agent: $this->title v$this->version\r\n"."Host: ".$this->host."\r\n".$encoding_headers.$credentials."Content-Type: text/xml\r\nContent-Length: ".strlen($data)."\r\n"."SOAPAction: \"$this->soapaction\""."\r\n\r\n".$data;

// set payloadcurl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->outgoing_payload);$t->setMarker('set curl options, executing...');// send and receive$this->incoming_payload = curl_exec($ch);$t->setMarker('executed transfer');$data = $this->incoming_payload;

$cErr = curl_error($ch);

if($cErr != ''){ $err = 'cURL ERROR: '.curl_errno($ch).': '.$cErr.'
';foreach(curl_getinfo($ch) as $k => $v){$err .= "$k: $v
";}$this->setError($err);curl_close($ch); return false;} else {echo '';var_dump(curl_getinfo($ch));echo '';}// close curlcurl_close($ch);$t->setMarker('closed curl');// remove 100 headerif(ereg('^HTTP/1.1 100',$data)){if($pos = strpos($data,"\r\n\r\n") ){$data = ltrim(substr($data,$pos));} elseif($pos = strpos($data,"\n\n") ){$data = ltrim(substr($data,$pos));}}//// separate content from HTTP headersif( $pos = strpos($data,"\r\n\r\n") ){$lb = "\r\n";} elseif( $pos = strpos($data,"\n\n") ){$lb = "\n";} else {$this->setError('no proper separation of headers and document');return false;}$header_data = trim(substr($data,0,$pos));$header_array = explode($lb,$header_data);$data = ltrim(substr($data,$pos));$this->debug('found proper separation of headers and document');$this->debug('cleaned data, stringlen: '.strlen($data));// clean headersforeach($header_array as $header_line){$arr = explode(':',$header_line);$headers[trim($arr[0])] = trim($arr[1]);}if(strlen($data) == 0){$this->debug('no data after headers!');$this->setError('no data present after HTTP headers.');return false;}// decode transfer-encodingif($headers['Transfer-Encoding'] == 'chunked'){//$timer->setMarker('starting to decode chunked content');if(!$data = $this->decodeChunked($data)){$this->setError('Decoding of chunked data failed');return false;}//$timer->setMarker('finished decoding of chunked content');//print "\nde-chunked:\n---------------\n$data\n\n---------------\n";}// decode content-encodingif($headers['Content-Encoding'] != ''){if($headers['Content-Encoding'] == 'deflate' || $headers['Content-Encoding'] == 'gzip'){ // if decoding works, use it. else assume data wasn't gzencoded if(function_exists('gzinflate')){//$timer->setMarker('starting decoding of gzip/deflated content');if($headers['Content-Encoding'] == 'deflate' && $degzdata = @gzinflate($data)){ $data = $degzdata;} elseif($headers['Content-Encoding'] == 'gzip' && $degzdata = gzinflate(substr($data, 10))){$data = $degzdata;} else {$this->setError('Errors occurred when trying to decode the data');}//$timer->setMarker('finished decoding of gzip/deflated content');//print "\nde-inflated:\n---------------\n$data\n-------------\n"; } else {$this->setError('The server sent deflated data. Your php install must have the Zlib extension compiled in to support this.');}}}// set decoded payload$this->incoming_payload = $header_data."\r\n\r\n".$data;return $data;}function setEncoding($enc='gzip, deflate'){$this->encoding = $enc;$this->protocol_version = '1.1';}// This function will decode "chunked' transfer encoding // as defined in RFC2068 19.4.6function decodeChunked($buffer){// length := 0$length = 0;$new = '';// read chunk-size, chunk-extension (if any) and CRLF// get the position of the linebreak$chunkend = strpos($buffer,"\r\n") + 2;$temp = substr($buffer,0,$chunkend);$chunk_size = hexdec( trim($temp) );$chunkstart = $chunkend;// while (chunk-size > 0) {while ($chunk_size > 0) {$chunkend = strpos( $buffer, "\r\n", $chunkstart + $chunk_size); // Just in case we got a broken connection if ($chunkend == FALSE) { $chunk = substr($buffer,$chunkstart);// append chunk-data to entity-body $new .= $chunk; $length += strlen($chunk); break;} // read chunk-data and CRLF $chunk = substr($buffer,$chunkstart,$chunkend-$chunkstart); // append chunk-data to entity-body $new .= $chunk; // length := length + chunk-size $length += strlen($chunk); // read chunk-size and CRLF $chunkstart = $chunkend + 2; $chunkend = strpos($buffer,"\r\n",$chunkstart)+2;if ($chunkend == FALSE) {break; //Just in case we got a broken connection}$temp = substr($buffer,$chunkstart,$chunkend-$chunkstart);$chunk_size = hexdec( trim($temp) );$chunkstart = $chunkend;} // Update headers //$this->Header['content-length'] = $length; //unset($this->Header['transfer-encoding']);return $new;}}

?>