administrator/components/com_virtuemart/classes/ 40755 0 0 0 11265155011 17647 5ustar 0 0 administrator/components/com_virtuemart/classes/Log/ 40755 0 0 0 11242221770 20371 5ustar 0 0 administrator/components/com_virtuemart/classes/PEAR/ 40755 0 0 0 11263443355 20407 5ustar 0 0 administrator/components/com_virtuemart/classes/PEAR/Table/ 40755 0 0 0 11046633453 21435 5ustar 0 0 administrator/components/com_virtuemart/classes/currency/ 40755 0 0 0 11260665051 21506 5ustar 0 0 administrator/components/com_virtuemart/classes/nusoap/ 40755 0 0 0 11254654303 21162 5ustar 0 0 administrator/components/com_virtuemart/classes/payment/ 40755 0 0 0 11263443355 21335 5ustar 0 0 administrator/components/com_virtuemart/classes/pdf/ 40755 0 0 0 11220414326 20416 5ustar 0 0 administrator/components/com_virtuemart/classes/pdf/font/ 40755 0 0 0 11046633456 21401 5ustar 0 0 administrator/components/com_virtuemart/classes/phpInputFilter/ 40755 0 0 0 11046633463 22635 5ustar 0 0 administrator/components/com_virtuemart/classes/shipping/ 40755 0 0 0 11263443356 21502 5ustar 0 0 administrator/components/com_virtuemart/classes/shipping/fedex/ 40755 0 0 0 11046633454 22574 5ustar 0 0 administrator/components/com_virtuemart/classes/shipping/minixml/ 40755 0 0 0 11046633454 23156 5ustar 0 0 administrator/components/com_virtuemart/classes/shipping/minixml/classes/ 40755 0 0 0 11046633454 24613 5ustar 0 0 administrator/components/com_virtuemart/html/ 40755 0 0 0 11264704112 17157 5ustar 0 0 administrator/components/com_virtuemart/sql/ 40755 0 0 0 11254653135 17021 5ustar 0 0 administrator/components/com_virtuemart/2checkout_notify.php100644 0 0 1626 10717123254 22311 0ustar 0 0 administrator/components/com_virtuemart/CHANGELOG.php100644 0 0 507661 11265424577 20406 0ustar 0 0
This is a non-exhaustive (but still near complete) changelog for
VirtueMart, including beta and release candidate versions.
Our thanks to all those people who've contributed bug reports and code fixes.

Legend:

#	Bug Fix
+	Addition
^	Change
-	Removed
!	Note

--------------------------------------------------------------------------------------------------------------


VirtueMart 1.1.x
*************************************
14.10.2009 aravot
# Fix for review form.

08.10.2009 soeren
# Task #2719 - Deprecated error message when using php 5.3 
# Admin Folder Blocked Via Htacess | Update Account "Save" Image comes from Admin [topic=61258]
# Task #2722 - 3 Bugs in product.folders.php 

30.09.2009 soeren
# Task #2719 - Deprecated error message when using php 5.3 

26.09.2009 soeren
# Task #2692 - Rounding issue in step 4 of checkout 
# Task #2702 - Count of Parameters of Product Type at front page 
# small fix to resized image display [http://forum.virtuemart.net/index.php?topic=59990.0]

24.09.2009 soeren
# Task #2711 - Undefined variable when review is modified by store owner.
# Task #2651 - EU VAT ID tax handling with dynamic EU VAT ID field name
# Task #2703 - convertECB error in localhost 

23.09.2009 mauri
# Fixed EU VAT ID in ps_product.php and ps_checkout.php
# Fixed undefined index in ps_order_chenge.php

21.09.2009 soeren
# fixed voting on edit vote (http://forum.virtuemart.net/index.php?topic=60287.0)

21.09.2009 aravot
# Switched width and height in ps_product.php
# Fixed case in ps_product_files.php

20.09.2009 thepisu
^ updated Persian (farsi) language (thanks to Mohoammad Hosien Fazeli)
^ updated Bulgarian language (thanks to Todor Iliev)

18.09.2009 soeren
- removed prototype.js
- removed unnecessary nusoap class files
^ using file_put_contents to write the configuration file in ps_config.php (instead of fputs)
- removed old "all-one-module"


14.09.2009 soeren
# small fix to make VirtueMart compatible to PHP 5.3

11.09.2009 soeren
# Task #2683 - Attribute List price modification not honored in add to cart  
# added the fix for order tax calculation when coupon discounts are used (http://www.nandebayo.org/blog/?p=80)

01.09.2009 soeren
# Task #2555 - Searching for child products is not possible 

28.08.2009 thepisu
^ updated Persian (farsi) language (thanks to Mohoammad Hosien Fazeli)
^ updated Hungarian language (thanks to pedrohsi)
^ updated Swedish language (thanks to sgagner)

25.08.2009 soeren

^ added new "init" function to the currency converter module, to check wether currency conversion can be initialized
# when currency conversion was not possible, the currency was still changed, but no conversion was calculated!

22.08.2009 thepisu
^ updated Persian (farsi) language (thanks to Mohoammad Hosien Fazeli)

19.08.2009 soeren
# Task #2690 - impossible to delete a credit card

17.08.2009 soeren
# Task #2687 - mod_virtuemart vm_JSCook.php error 
# Task #2689 - shop.feed.php SEF URL Bug Fix
 
09.08.2009 mauri
# Task #2688 - Page Title shows wrong in checkout, if uncheck some steps.

31.07.2009 aravot
# Fixed - SQL error caused by function get_name_by_catid($catid) (http://forum.virtuemart.net/index.php?topic=58641.0)

29.07.2009 soeren
# Task #2686 - Problem with ps_authorize.php on checkout if more than one ps_authorize payment method exists

23.07.2009 soeren
# Task #2679 - Authorize.net current configuration will not connect to the testing server.

22.07.2009 soeren
# Task #2563 - Wrong credit card expiration date in user Account Maintenance.
# Task #2310 - Stock levels not maintained correctly when selling downloadable products.
  
21.07.2009 aravot
# Task #2677 - Tax rate should not be rounded. 
! Modified tax.tax_list.php file to use 5 decimals for the tax rate 

20.07.2009 soeren
# Task #2677 - Tax rate should not be rounded. 
! Table Structure Change: Table "jos_vm_tax_rate", using 5 decimals for the tax rate now
! ALTER TABLE `jos_vm_tax_rate` CHANGE `tax_rate` `tax_rate` DECIMAL( 10, 5 ) NULL DEFAULT NULL 

# Task #2676 - Notice: Undefined index: order_status in ps_order.php on line 296 when Resend Download ID is clicked.
 
15.07.2009 aravot
+ Task #2663 - One Title option in billing form (Ms)

15.07.2009 mauri
# Task #2672 - Notice: Undefined index: unit in product_type.tpl.php on line 44

14.07.2009 soeren
# Task #2668 - Mail contents is broken on OSX server. 
# Task #1972 - Tax added even when product has no tax assign to it 
# Task #2584 - Image upload displays errors and thumbnail creation is not possible when open_basedir does not include PHP's upload_tmp_dir directory 

12.07.2009 mauri
# Task #2549 - When 'Virtual Tax' is unchecked, 'Show "(including XX% tax)" when applicable?' it not shown for all products. 

11.07.2009 mauri
# Fixed Order Dates incorrect ps_order_change, reverted changes.

10.07.2009 aravot
# Fixed Warning: Call-time pass-by-reference has been deprecated in payment/ps_eway.php on line 511

02.07.2009 thepisu
^ updated Simplified Chinese language, now utf-8 (thanks to joomladz)
+ added Estonian language (thanks to Eraser)

30.06.2009 soeren
# Task #2548 - When Dynamic Thumbnail Resizing is off (unchecked) additional images show big image instead of thumbnail
# Task #2507 - In category removing a thumbnail doesn't check if the file is used by other categories

26.06.2009 aravot
#BUG #2498 - Order Dates incorrect, reverted changes.
^ Update CA tax rate

29.06.2009 soeren
# Task #2658 - The page title of product details pages gets truncated when use national product names
# Task #2647 - Product could not be unpublished from the product list page if this product has different vendor other then the default one.
# Task #2659 - Super Adminisrtaor has right to publish/unpublish only default vendor products (should have permission to all) 
# Task #2665 - Price converted twice when attributes with prices are set up 
# Task #2662 - Only variable references should be returned in ps_country
# Task #2655 - CC month in Admin panel differs from Email Invoice 

28.06.2009 soeren
# Task #2660 - little enhancement for addtocart_advanced_attribute.tpl.php
# Task #2661 - Notice: Undefined variable: resultmm in ps_authorize 

27.06.2009 mauri
# Clean unnecessary comments in ps_product
# Fixed Standard_Shipping_module, Currency convert in shipping rates.
# Fixed Divided by zero in ps_order_change, when all orders are deleted.
# BUG #2657 - Undefined variable: order_id when viewing order.
# Fixed Undefined variables in ps_order_change.
# Fixed Order Dates incorrect in ps_order_change.
# Fixed Undefined variable rate in ps_product.
# BUG #2502 - Wrong tax, when update price in backend order.

26.06.2009 aravot
#BUG #2498 - Order Dates incorrect (thank you Scott)

24.06.2009 sobers_2002
# Fixed the shipping tax calculation in the standard shipping module
# Fixed the sh404sef issues in transmenu with submenus

24.06.2009 aravot
# Corrected PHP short tags.

24.06.2009 soeren
^ TSK-2620 -  Do not save login cookies by default 
# Task #2624 - Credit card type now showing 
# Task #1489 - PDF Output won't add product image
 
23.06.2009 soeren
# Task #2630 - Undefined index message in Store Edit 
# Task #2631 - prep4SQL renames field names
# Task #2652 - Wrapper Url traced wrrong 
# Task #2653 - arguments for str_replace () are swapped 
# Task #2654 - Problem with email registration 

23.06.2009 aravot
# Fixed landscape/portrait issue http://forum.virtuemart.net/index.php?topic=55201.0 Thank you Phil
# Fixed Bug in template.class.php http://forum.virtuemart.net/index.php?topic=54394.0 Thank you Phil

22.06.2009 soeren
# Task #2015 - The Value of the Coupon is greater than the current Order Total, coupon value displayed with no tax 
# Fixed VAT based on Shipping Address (http://forum.virtuemart.net/index.php?topic=56983.msg186554)
^ added Slovak Language Files (utf-8)
# Task #2053 - Resend Download ID, lower order status update buttons do not send emails 
# when updating a downloadable product file any references to ordered downloadable files are updated as well when necessary
# Task #2643 - Title setting is done by different function, integrity of code requires virtumart defined function 

 
17.06.2009 aravot
# BUG #2649 - Username & Password required when updating address with "No Account Creation"
# BUG #2648 - Product name in Call for Pricing message promt is wrong, if product name have special characters.

12.06.2009 soeren
# Task #2373 - Customers comments sripts slashes and I m getting rn in the enter of users. 
# Task #2646 - New usergroup with admin rights can't see administration in in frontend
^ adapted rewritten ps_session::url function from here: http://forum.virtuemart.net/index.php?topic=56664.0, thanks!

02.06.2009 soeren
# Task #2637 - Credit card type now showing for No Account creation method 
# Task #2638 - flypage_images.tpl.php has function protoPop() which is outdated
# Task #2495 - Order Print View, Inc Tax & Coupon Discount
 
29.05.2009 soeren
# partly fixed linkpoint class

28.05.2009 soeren
# Task #2547 - "'" instead of "apostrophe" in breadcrumb (mainframe.class.php) 

27.05.2009 soeren
# Task #2634 - Can not register user 
# corrected Serbian/Yugoslavia currency

24.05.2009 thepisu
# updated Croatian-Hrvatski language (thanks to dac3d)
# updated Spanish language (thanks to Blogapeuta)
# updated Bulgarian language (thanks to Imago)
# updated Swedish language (thanks to mauri)
# updated Traditional Chinese language (thanks to SimonSimon)
+ added Lithuanian translation (thanks to no0n3)

15.05.2009 macallf
# BUG #1345/#1598 - Out of stock children displayed in drop down

15.05.2009 aravot
# BUG #1348 - Functions not showing in admin

13.05.2009 aravot
# Fixed Notice Undefined variable total in shop.basket_short.php

11.05.2009 soeren
# Task #2590 - Attributes are not calculated 
# Task #2595 - Frontend edit icon should not have a hard-coded dimension
# Task #2566 - Notify button not working 
# Task #2599 - Product attributes with a '0' value are blank in orders [PATCH] 
# Task #2602 - Multiple price table (tier pricing) conversion bug

10.05.2009 aravot
# BUG #2611 - Changed _PSHOP_ADMIN to _VM_IS_BACKEND
# Fixed The Vendor Category and Vendoer Image Path fields can't be updated (Thank you Phil)
# Fixed 'Error: A value for the field "vendor_category_name" is missing' (Thank you Phil)

06.05.2009 aravot
# Fixed TransMenu Call to a member function setQuery() on a non-object error message
# Fixed TigraTree Call to a member function query() on a non-object error message
# BUG #2592 - Fix for Authorize.net status code 4 (good trans but produces error in VM)

03.05.2009 aravot
^ Changed Authorize.net Login ID to Authorize.net API ID

02.05.2009 rolandd
# BUG #2016 € is displayed in info message The Value of the Coupon is greater than the current Order Total,
# suppres getimagesize warning if file does not exist

01.05.2009
# BUG #2583 - Fixed to show shipping rate tax for all tax modes

01.05.2009 rolandd
# Unknown column 'file_is_image=0'
# PSHOP_SHIPPING_MODULES not defined
# Product type not adding for a single product

27.04.2009 aravot
# Fixed typo in product.product_product_type_list.php

26.04.2009 rolandd
^ FRQ #2582  shop.browse - optimize to lower nubmer of DB queries.

23.04.2009 rolandd
# BUG #2356 Billing information will be overwritten if sento information is saved
# BUG #2573 ps_cashondel.php contains a couple of short tags 

22.04.2009 aravot
# Fixed recently viewed items when a product or category is unpublished it is still shown (thank you Phil)
# Fixed number of recently viewed products to display (thank you Phil)

21.04.2009 aravot
# BUG #2550 - Child product price is shown wrong for users other than default group

16.04.2009 aravot
# Task #2536 - Incomplete php tag with a duplicated table closure'
# Task #2537 - Default currency plugin not set!
# Fixed delete child product from cart when child product has apostrophe in product name. 

15.04.2009 aravot
# Fixed Kenya, Somali and Tanzania currency
 
07.04.2009 macallf
# Bug - Fix problems with slimbox not init after AJAX pageload & addtocart confirmation box only working once.

05.04.2009 aravot
^ Update CA tax rate

05.04.2009 macallf
# BUG - 0 quantity deletes product from cart on product page and browse page. Should only happen on update or single add to cart button child list

31.03.2009 rolandd
# BUG #2410 Making a File a "downloadable product file" resets existing downloadable product files 

30.03.2009 aravot
^ Changed PayPal test account link in notify.php
+ Added Continue Shopping link when cart is empty
 
23.03.2009 soeren
# Task #2536 - Incomplete php tag with a duplicated table closure' 
# Task #2537 - Default curency plugin not set!

20.03.2009 macallf
# Bug #2543

19.03.2009 aravot
# Review message fixed. 

15.03.2009 rolandd
# Bug #2539 missing in conditional expression in mod_virtuemart TigraTree
# CSV Improved not correctly detected
# Bug #2526 Open Account Maintenance in a GreyBox does not work.
# Bug #2538 Ext is undefined
# Open Checkout in Greybox (revisited)
^ Updated DTD for modules for J1.5

13.03.2009 macallf
# Task #2532 Fixed adding multiple products to product_type

12.03.2009 aravot
# Fixed - Fatal error: Class 'ps_order_change' not found in ps_order_change.php

08.03.2009 macallf
^ Changed product_types to template control. Template file product_types.tpl.php added to /common

08.03.2009 aravot
^ Changed Parameters of Category to Parameters of Product

04.03.2009 aravot
# Fixed - Open Checkout in Greybox

04.03.2009 soeren
# Task #1921 - Shipper notice is empty

03.03.2009 macallf
# Task #2509 Current fix saves fields correctly but does not allow for adding new fields.

28.02.2009 aravot
# Task #2374 - Bug in product type flypage path for Joomla 1.5 / VM 1.1.2
^ Compliance issue in classes/ps_userfield.php (http://forum.virtuemart.net/index.php?topic=44940.0)

28.02.2009 tkahl
# Task #2517 - VirtueMart installation fails 

25.02.2009 aravot
# Fixed Failed to open stream error when product image is missing (http://forum.virtuemart.net/index.php?topic=52081.0)
# Fixed Bug in Product Type Parameter processing (http://forum.virtuemart.net/index.php?topic=44445.0)

25.02.2009 soeren
# Task #2489 - Customer review comment length error message
# Task #2509 - Saving exisintg custom user field multiplies values - with fix
24.02.2009 soeren
# Task #2513 - Taxes ids higher than 127 cannot be used on products

22.02.2009 macallf
# Task #2511 Extra ID's doesn't work for all products, it only works for child products. Edited logic in ps_product_attribute.php

19.02.2009 macallf
# Task #2510 Altered ps_product.php to allow aplhanumeric chars in the child_class_suffix field

17.02.2009 soeren
# Task #2506 - Subtotal rounding error in savebasket
# fixed the IE "Operation Aborted" error in the frontend, when "Open Product Images in a LightBox?" is enabled (which is the default)
# fixed the IE "Operation Aborted" error in Extended Layout in the backend's product form
 
11.02.2009 aravot
^ Fixed comment typo in SQL file

05.02.2009 soeren
# Task #2490 - Add to cart issues when javascript disabled 
# fixed: no value assigned to $DescOrderBy

05.02.2009 aravot
# Task #2486 - Loading Edit Store and other administrative pages under MSIE <= 7.0 results in Operation Aborted error and unable to view.

02.02.2009 aravot
# Task #2491 - Broken links on pathway
^ Fixed Configuration table alignment in admin.show_cfg.php
^ Corrected langauge files (thank you Phil)

01.02.2009 soeren
# Task #2486 - Loading Edit Store and other administrative pages under MSIE <= 7.0 results in Operation Aborted error and unable to view.
# Task #2481 - Changes to class_currency_display.php course currency symbol to be displayed as currency type.

24.01.2009 aravot
# in Extended Layout view, menu icons are shown twice
  
24.01.2009 thepisu
# Task #2496 - Standard Shipping Module saving problem in DB (fix in ps_shipping - adding a new carrier)

22.01.2009 thepisu
# Task #2473 - Untranslated language string in checkout_register_form.php 
# added translation for strings in ps_shopper_group

--- VirtueMart 1.1.3 released (Rev. 1611 2009-01-22) ---

19.01.2009 soeren
# Task #2471 - Wrong bill_to address in email confirmation Text mail.

17.01.2009 thepisu
+ added Serbian Latin translation (serbian_lat, UTF-8); by Vlada_bgd; not yet fully translated

15.01.2009 aravot
^ updated Turkish Lira from "New Turkish Lira" to "Turkish Lira" in installation sql

14.01.2009 thepisu
^ converted Italian language to UTF-8
^ fixed French language encoding - converted to UTF-8

12.01.2009 soeren
# Task #2470 - Quantity Box JavaScript validation code fails XHTML validation 
# fixed paymenow module (login information was missing on payment processing) 

10.01.2009 aravot
# Fixed PHP5 Call-time pass-by-reference message

10.01.2009 thepisu
^ updated Finnish language (by Mauri)
^ updated Italian language

08.01.2009 soeren
# Task #2458 - order search function in account maintenance now searches for order item names/sku and order number
# Task #2469 - tax_rate problem in checkout
# Task #2434 - Modules need a statment if to check if the product has items so not to show add to cart. 
# Task #2457 - Error: CheckOut needs a valid Step! (currency switcher module)
 
06.01.2009 soeren
# Task #2455 -  Problems with sort function "Order by"
# Task #2250 - Products that contain more than one download file only have one download link listed on invoice
# merged patches for compatibility with SecurityImages 5 (http://www.waltercedric.com/joomla-mainmenu-247/304-securityimages/1364-virtuemart-112-and-securityimages-5.html), thanks Cedric for providing these!

05.01.2009 soeren
# Task #2463 - pageNavigation problem
# Task #2317 - Submit button on shop ask page is not working

24.12.08 thepisu
# address formatting:  {statename} not converted; config tip wrong
# sql update script from 1.0.x: some chars wrongly encoded; updated version info to 1.1.2 stable; missing function records
# sql sample data: removed HTML entities from shipping rates
# checkout confirmation tpl: not "make safe" old shipping sample data (cointaining ">"); that was "maked safe" twice

20.12.08 thepisu
# fix in Language Manager
^ updated Swedish language (by sgagner)
^ fix in Italian language

19.12.2008 soeren
# Task #2453 - Problem with Tax State

17.12.2008 soeren
# Task #2451 - Additional downloadable files missing in account maintenance
 
15.12.2008 soeren
# Task #2448 - stock levels not reduced when order confirmed
# Task #2446 - adding custom user fields causes inability to see orders in order list 
# Task #2450 - Weekly Sales report only lists products sold on first day of week
 
10.12.2008 aravot
# Cant disable Keep Product Stock Level on Purchase (http://forum.virtuemart.net/index.php?topic=42901 - thank you patjun)

08.12.2008 soeren
# Task #2440 - Zone Shipping on checkout page shows zone value rather than zone name. 
# Task #2443 - Save button for additional file/images not working in IE (missing ajax_request var) 
# Task #2197 - Parent price shown for Child items when user is member of a shopper group other than default 
# Task #2445 - hidden user_id present 2 times in a form 
# removed additional user_id parameter from admin.user_address_form
^updated Turkish Lira to "New Turkish Lira" in installation sql
# undefined variables in ro_basket.php

08.12.2088 aravot
# Compliance issue in classes/htmlTools.class.php (Thank you Phil)

05.12.2008 aravot
# Fixed shipvalue (http://forum.virtuemart.net/index.php?topic=39883.0 Thank you chaliet)

04.12.2008 aravot
# Removed affiliate reference from configuration and language file

04.12.2008 soeren
^ Task #2441 - Updated Slimbox to latest version (1.54)
# usps.php - fatal error on curl_error
# shop.feed.php - fatal error when JoomFish is enabled
# Task #2439 - Dynamic Image Resizing ( PSHOP_IMG_RESIZE_ENABLE ) can not be switched off casuing broken thumb images on Category display
^ show_image_in_imgtag.php: changed max height+width to 600px and min to 40px;
# no resized images will be created when "Enable Dynamic Thumbnail Resizing?" is disabled; added a check for the existance of the GD library

02.12.2008 soeren
# better HTTPS detection;
#Task #2438 - fixed mod_virtuemart_manufacturers.php PHP notice

30.11.08 soeren
#Task #2437 - Undefined variable: coupon_display;
#Task #2436 - Error when trying to view order in Account Maintenance

30.11.08 aravot
# Task #2414 - Shipping zone display error

29.11.08 aravot
#2314 - Add Item MISSING in 1.1.2

29.11.2008 soeren
# fixed some security-related issues.

28.11.2008 soeren
# Task #2429 - Undefined variable: tax_display
# fix for removed affiliate module

28.11.08 aravot
# Task #2366 - Missing info message "The selected quantity exceeds quantity available in stock." with EASY FIX (Thank you Danny)
# Task #2394 - Selecting orders in the back-end causes a major slow-down with large number of orders

27.11.08 aravot
# Task #2412 - Child Products do not Display in IE7 AJAX Cart
# Task #2406 - Too many escape characters are added when writing virtuemart.cfg.php

26.11.08 aravot
Fixed missing Checkout Bar image using Joomla 1.5.8

19.11.08 thepisu
^ updated Hungarian language (by pedrohsi)
^ updated Finnish language (by mauri)
^ updated Dutch language (by Tonslag)
^ updated Spanish language (by adancer)
^ fix in Italian language

10.11.08 mainly Danny with help by Max Milbers and committed by Max Milbers
+ showing state name instead of state-2-code in order details

06.11.2008 aravot
Added missing User Group List icon

23.10.2008 aravot
Added missing forum icon

13.10.2008 aravot
# Task #2305 - VM1.1.2 frontend order layout broken

04.10.2008 by RolandD committed by Max Milbers
fix for displaying child products in a list. In IE7 and IE6 the page collapses because of a missing span tag. IE then places all subsequent child products in the previous span. This works fine unless you have more than let's say 15 child products. 

02.10.2008 aravot
Added missing product navigation link parameters to theme.xml file

19.09.2008 soeren
# Task #2371 - Moving up/down doesn't work in admin lists
# Task #2368 - order date not local language 
+ added pathway + page title to registration page
^ changed basket + ro_basket to read the basket templates using the vmtemplateClass::fetch method

15.09.2008 soeren
# Task #2331 - search_date hidden field doesn't get a value in admin product listing on backend after
# Task #2335 - mod_virtuemart_login.php contains unescaped ampersand characters
# Task #2336 - HTML entities in product name are not always escaped leading to XHTML validation errors.
# Task #2337 - Labels for the user fields 'title' and 'state' do not match the ids used on the select tags.
# Task #2338 - Option values for dropdown lists allow unescaped HTML entities leading to XHTML validation errors.
# Task #2339 - The vendor image requires the alt attribute for XHTML validation
# Task #2340 - pageNavigation.class.php specifies nowrap="true" causing XHTML validation errors.
# Task #2341 - writeSearchHeader function in htmlTools.class.php generates invalid HTML
# Task #2342 - The dropdown list of downloadable filenames for a product should exclude system files such as .htaccess and index.html etc.
# Task #2345 - Rogue double quote in basket_b2c.html.php
# Task #2344 - XHTML validation errors in basket
# Task #2346 - Username and password login boxes require unique ids for XHTML validation
# Task #2347 - XHTML validation errors in shop.downloads.php
# Task #2348 - XHTML validation error with PayPal image

13.08.2008 aravot
Corrected few spelling mistakes in English language (http://forum.virtuemart.net/index.php?topic=44169.0 - thank you Phil)

07.08.2008 aravot
Fix compatibility issues with jomcomment system plugin (http://forum.virtuemart.net/index.php?topic=42558.0 - thank you azrulrhm)

05.08.2008 aravot
Changes made to mod_virtuemart_login to make xhtml w3c compliance (http://forum.virtuemart.net/index.php?topic=44009.0 - thank you Phil)
Changes made to mod_virtuemart to make xhtml w3c compliance (http://forum.virtuemart.net/index.php?topic=44008.0 - thank you Phil)

03.08.2008
# Task #2286 - Manufacturer Description missing query mf_desc in shop.browse.php on line 121

--- VirtueMart 1.1.2 released (Rev. 1495 2008-07-31) ---

31.07.2008 soeren
# added missing  in update preview

31.07.2008 gregdev
# Change mkdir permissions from 755 to 0755 in updater.

30.07.2008 gregdev
# Task #2277 - Subcategories are not show if category has only one product
# Task #2219 - Attributes of Childproduct are not shown
- Removed 1.1.1->1.1.2 sql update script.
# Task #2263 - Incorrect total price rounding in mini cart and mod_virtuemart cart

25.07.2008 aravot
Minor CSS fix lightblue to #ADD8E6 (thank you Phil)

24.07.2008 soeren
# Task #2272 - added ccNewsletter Integration for VM

24.0.7.2008 aravot
# Fix productsnapshots output order when displaying a row of products (http://forum.virtuemart.net/index.php?topic=43001.0 - thanks donmarvin)
# 2176  Error in Infotip for Cofig/Layout/Category template.

23.07.2008 gregdev
# Fix disabled shipping methods when last option is chosen (http://forum.virtuemart.net/index.php?topic=40580.15 - thanks Joseph)

21.07.2008 soeren
# Task #2081 - add product page tabs empty

18.07.2008 gregdev
# Task #2260 - DHL shipping error when address 2 is present 

17.07.2008 gregdev
# Task #2256 - When Joomla Allow User Registration is set to No, VM template breaks.
^ Changed vmRedirect to use $mainframe->redirect($url, $msg) on Joomla! >= 1.5
# Task #2258 - Bottom page navigation is placed in wrong location for two product list styles.

16.07.2008 gregdev
# Task #2195 - Don't allow a user id of zero
# Fix fatal error for date-type userfield

16.07.2008 soeren
# Task #2246 - Download count and expiration still modified if file missing or unreadable when download requested.
^ language class: added the ability to retrieve a key from an arbitrary module, whose language file was loaded from within a page
	Example: $VM_LANG->load('mymodule') now gives you access to that language keys even if the current "page" belongs to a different module (e.g. "store")

15.07.2008 gregdev
# Task #2243 - User prompted for username & password when Virtuemart in "No Account Creation"
# Task #2245 - Shipping Address Selection - switching back to default address

14.07.2008 soeren
^ Task #2240 - mf description also in shop.browse.php and browse_header_manufacturer.tpl.php 
# Task #2227 - When Joomla cache is enabled Product list with table doesn't work 
# Task #2232 -  Wrong currency code value for Polish Zloty  
^ Task #2234 - added "statename" to the list of placeholders which can be used in the vendor address format. It holds the actual state name.

14.07.2008 gregdev
# Fixed product_url for featured products
# Fixed  typo in pageNavigation.class.php
# Xhtml compliance issues in shop.search.php
# Don't show the browse page footer when there are no products

11.07.2008 gregdev
# Task #2226 - Instead of 'Notify Me' button 'add to cart' button is shown when list box for child products is selected.

09.07.2008 gregdev
# Task #2224 - Don't show up ajax pop-up when click "Notify me"
^ Dates supplied to the browse templates are formatted now, rather plain UNIX timestamps
# Task #2204 - Fixed logic error for showing product name in product snapshot template
# Fixed missing $product_parent_id in header.php
# Task #2041 - Renamed Subtotal column to Total (English only) on order list

08.07.2008 gregdev
# Task #2168 - Fixed bank account information not saved in backend user form
# Task #2210 - product_availability_date typo in shop.browse.php 
# Task #2211 - product_url missing in shop.browse.php
# Task #2093 - Show Pagination only when needed
# Task #2220 - Add to Cart for each child is not saving
^ Added optional $force parameter to ps_product::get_field() to force reload from the database
# Task #2204 - Cannot remove product name in mod_productscroller
# Fixed missing class mosParameters (used vmParameters) when validating EUVatID during registration

08.07.2008 soeren
# Product Form: fixed Attribute Form becoming inaccessible when many attributes are added (overflow not visible)
# fixed hidden (inaccessible) Tabs when too many tabs are in the tab panel (scrolls like in FF now)
# Task #2185 - Advanced Search according to Parameters bug and fix
# Task #2214 - XTHTML Error in LoginScript
# Task #2215 -  Problems with ps_session.php after rev 1451

04.07.2008 soeren
# Task #2209 - Picture checkout2_1.png not in use
# shipping bypass didn't work
# re-enabling a product download made it impossible to resend the Download ID (user_id was set to 0)
^ adapted SEF pageNavigation.class.php by shumisha of sh404SEF

02.07.2008 gregdev
# Task #2059 - Plugins not working in child product.
^ Don't use 
administrator/components/com_virtuemart/COPYRIGHT.php100644 0 0 7326 11122262731 20400 0ustar 0 0
Copyright:

VirtueMart derives from copyrighted works licensed under the GNU General
Public License.  This version has been modified pursuant to the
GNU General Public License as of September 15, 2005, and as distributed,
it includes or is derivative of works licensed under the GNU General
Public License or other free or open source software licenses, including
works copyrighted by any or all of the following, from 2000 through 2005 (appearing in alphabetical order):
Ekkehard Domning, Zdenek Dvorak, Edikon corp., Soeren Eberhardt,
pablo (from Edikon), Bernhard Pfeifer,  John Syben, Phil Taylor, Erich Vinson,  
or Mike Wattier from Zephware (devcompany.com)

(If you have contributed a piece of VirtueMart that is not mentioned and missing here, 
and you feel that your copyright note should be mentioned here, 
please contact the author of VirtueMart (soeren |at| virtuemart.net).)

VirtueMart includes or is derivative of works distributed under the following copyright notices:

CreditCard Class
---
Copyright:	Daniel Fr�z Costa
License:	Public Domain

Currency Converter Module
----
Copyright:	2004 Werner Knudsen
License:	GNU General Public License (GPL)

ExtJS
----
Copyright: 2006-2007, Ext JS, LLC
License: Lesser GNU (LGPL) open source license version 2.1.

FPDF
----
Copyright:	Olivier PLATHEY
License:	Freeware

HMTL2PDF
----
Copyright: 2004-2005 Renato Coelho
License:	GNU Lesser General Public License (LGPL)

Image2Thumbnail Class
---
Copyright:	Andreas Martens and Patrick Teague
License:	Freeware

js-jscook-menu
---
Copyright:	2002-2005 by Heng Yuan
License:	Custom open source license

js-overlib
---
Copyright:	Erik Bosrup 1998-2004
License:	Artistic (see http://www.bosrup.com/web/overlib/?License)

js-tabs
---
Copyright:	1998 - 2003 Erik Arvidsson
License:	GNU General Public License (GPL)

Mambo
----
Copyright:	2000 - 2007 Mambo Foundation, Inc.
License:	GNU General Public License (GPL) Version 2.

minixml
---
Copyright:	2002,2003 Patrick Deegan, Psychogenic.com
License:	GNU General Public License (GPL)

PEAR
----
Copyright:	1997-2004 The PHP Group
License:	PHP license

phpInputfilter
----
Copyright:	Daniel Morris
License:	GNU General Public License (GPL)

phpMailer
----
Copyright:	2001 - 2003  Brent R. Matzelle
License:	GNU Lesser General Public License (LGPL)

phpShop
----
Copyright:	2000 - 2004 Edikon Corp. (http://www.edikon.com)
License:	GNU General Public License (GPL)
Community: http://www.phpshop.org

tar-archive
----
Copyright:	1997-2003 The PHP Group
License:	PHP License

wz-tooltip
----
Copyright:	2002-2004 Walter Zorn
License:	GNU Lesser General Public License (LGPL)

Administrator Icons
----
Copyright:	2008 Simon Josephson (http://www.artatwork.com.au)
Thank you Simon!

If you have contributed a vital part of VirtueMart that is not mentioned and missing here,
and you feel that your copyright note should be mentioned here,
please contact the author of VirtueMart (soeren|at|virtuemart.net).
administrator/components/com_virtuemart/INSTALLATION.php100644 0 0 44476 10774215017 20767 0ustar 0 0

MANUAL INSTALLATION OF VIRTUEMART
=== README FILE ===

The easy & automatic installation procedure is explained in the file
README.php of the COMPLETE PACKAGE.

You shouldn't use these instructions, when you have downloaded the
COMPLETE PACKAGE.

You should only use this file, when you have 
	* VirtueMart 1.0.x and want to upgrade to VirtueMart 1.1.x
	* safe mode problems, so you can't use the component installer (Safe Mode = On ? Manual Installation is your saviour)
	* problems installing the Component by uploading the contents of the component installer archive and installing from directory
	

=== ABOUT THIS FILE ===

This file is meant to provide hints on the Manual Installation Procedure for VirtueMart.


=== ABOUT VirtueMart ===

VirtueMart is an Open Source Online-Shop plugin for Joomla! and Mambo.


=== MANUAL INSTALLATION PROCEDURE ===
  
1. Unpack the archive file "VirtueMart_Manual-Installation-Package_1.x.tar.gz" (the one which contains this file as "README.txt")
	using WinRAR or a similar Archive Software
	
	You should now see some directories:
	  * /administrator
	  * /components
	  * /modules
	  * /mambots
	
	The directory structure in those directories is the
	same as in your Joomla!/Mambo site.
	
2.  Open up an FTP Connection to your site and upload
	the directories to your Joomla!/Mambo site.
	
	/components
	to
	  /path-to-site-root/components/

	/administrator
	to
	  /path-to-site-root/administrator/
	  
	/modules
	to
	  /path-to-site-root/modules/

	For Joomla! 1.0.x or Mambo:
	/mambots
	to
	  /path-to-site-root/mambots/

	Or, for Joomla! 1.5.x:
	/plugins
	to
	  /path-to-site-root/plugins/
	  
	You will probably have to confirm overwriting some existing files 
	in these directories.	
	An existing configuration file will not be overwritten.


3.  Login in to the Joomla! / Mambo Administration (the so-called Backend).

	  http://www.xxxxxx.com/administrator/
	
	* When having logged in, you see this URL in the address bar:
	
	  http://www.xxxxxx.com/administrator/index2.php
	  (or for Joomla! 1.5.x: http://www.xxxxxx.com/administrator/index.php)
	
	* Now just add "?option=com_virtuemart" after index2.php (or index.php for Joomla! 1.5.x), so it looks like this
	  in your browser's address bar:
	  
		http://www.xxxxxx.com/administrator/index2.php?option=com_virtuemart
		(or for Joomla! 1.5.x: http://www.xxxxxx.com/administrator/index.php?option=com_virtuemart)
	
	  and submit (press Enter).
	
	* You should now see the "Installation was successful..." Screen.
	  There you can click on 
		"GO TO THE SHOP >>" 
	  or on
		"INSTALL SAMPLE DATA" (when you want to have some sample products and categories in your Shop).

	* That's it.	  

=== Modules and Mambots (Plugins) ===

4. The Modules and Mambots (Plugins) in the archive are add-ons, but most important is the VirtueMart Main Module,
	which consists of two files:
	/modules/mod_virtuemart.php
	/modules/mod_virtuemart.xml
	
	You need this module to be able to access and browse your shop
	like a customer.

	For experienced users, just import the appropriate sql file:
	 - Joomla! 1.0.x: virtuemart.installation.addons.joomla.sql
	 - Joomla! 1.5.x: virtuemart.installation.addons.joomla1.5.sql
	 - Mambo: virtuemart.installation.addons.mambo.sql
	
	Otherwise, browse to phpMyAdmin and select your database.
	Select "SQL" in the toolbar on the middle top.
	Then run the approriate SQL code below:
	
	For Joomla! 1.0.x (using a jos_ table prefix):
	
####
INSERT IGNORE INTO `jos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Module', '', 99, 'left', 0, '0000-00-00 00:00:00', 1, 'mod_virtuemart', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `jos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Login', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_login', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `jos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart TopTen Products', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_topten', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `jos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Product Scroller', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_productscroller', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `jos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Product Categories', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_product_categories', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `jos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart All-In-One', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_allinone', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `jos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Cart', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_cart', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `jos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Featured Products', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_featureprod', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `jos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Latest Products', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_latestprod', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `jos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Manufacturers', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_manufacturers', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `jos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Random Products', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_randomprod', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `jos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Search', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_search', 0, 0, 1, '', 0, 0);

INSERT IGNORE INTO `jos_mambots` (`name`, `element`, `folder`, `access`, `ordering`, `published`, `iscore`, `client_id`, `checked_out`, `checked_out_time`, `params`) VALUES ('VirtueMart Product Snapshot', 'vmproductsnapshots', 'content', 0, 0, 0, 0, 0, 0, '0000-00-00 00:00:00', '');
INSERT IGNORE INTO `jos_mambots` (`name`, `element`, `folder`, `access`, `ordering`, `published`, `iscore`, `client_id`, `checked_out`, `checked_out_time`, `params`) VALUES ('VirtueMart Search', 'virtuemart.searchbot', 'search', 0, 0, 0, 0, 0, 0, '0000-00-00 00:00:00', '');
INSERT IGNORE INTO `jos_mambots` (`name`, `element`, `folder`, `access`, `ordering`, `published`, `iscore`, `client_id`, `checked_out`, `checked_out_time`, `params`) VALUES ('VirtueMart Xtd Search', 'vmxsearch.searchbot', 'search', 0, 0, 0, 0, 0, 0, '0000-00-00 00:00:00', '');
####

	For Joomla! 1.5.x (using a jos_ table prefix):
	
####
INSERT IGNORE INTO `jos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Module', '', 99, 'left', 0, '0000-00-00 00:00:00', 1, 'mod_virtuemart', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `jos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Login', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_login', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `jos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart TopTen Products', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_topten', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `jos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Product Scroller', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_productscroller', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `jos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Product Categories', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_product_categories', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `jos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart All-In-One', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_allinone', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `jos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Cart', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_cart', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `jos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Featured Products', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_featureprod', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `jos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Latest Products', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_latestprod', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `jos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Manufacturers', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_manufacturers', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `jos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Random Products', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_randomprod', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `jos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Search', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_search', 0, 0, 1, '', 0, 0);

INSERT IGNORE INTO `jos_plugins` (`name`, `element`, `folder`, `access`, `ordering`, `published`, `iscore`, `client_id`, `checked_out`, `checked_out_time`, `params`) VALUES ('VirtueMart Product Snapshot', 'vmproductsnapshots', 'content', 0, 0, 0, 0, 0, 0, '0000-00-00 00:00:00', '');
INSERT IGNORE INTO `jos_plugins` (`name`, `element`, `folder`, `access`, `ordering`, `published`, `iscore`, `client_id`, `checked_out`, `checked_out_time`, `params`) VALUES ('VirtueMart Product Search', 'vmxsearch.plugin', 'search', 0, 0, 0, 0, 0, 0, '0000-00-00 00:00:00', '');
####

	For Mambo (using a mos_ table prefix):

####
INSERT IGNORE INTO `mos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Module', '', 99, 'left', 0, '0000-00-00 00:00:00', 1, 'mod_virtuemart', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `mos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Login', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_login', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `mos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart TopTen Products', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_topten', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `mos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Product Scroller', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_productscroller', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `mos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Product Categories', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_product_categories', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `mos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart All-In-One', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_allinone', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `mos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Cart', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_cart', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `mos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Featured Products', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_featureprod', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `mos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Latest Products', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_latestprod', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `mos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Manufacturers', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_manufacturers', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `mos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Random Products', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_randomprod', 0, 0, 1, '', 0, 0);
INSERT IGNORE INTO `mos_modules` (`title`, `content`, `ordering`, `position`, `checked_out`, `checked_out_time`, `published`, `module`, `numnews`, `access`, `showtitle`, `params`, `iscore`, `client_id`) VALUES ( 'VirtueMart Search', '', 99, 'left', 0, '0000-00-00 00:00:00', 0, 'mod_virtuemart_search', 0, 0, 1, '', 0, 0);

INSERT IGNORE INTO `mos_mambots` (`name`, `element`, `folder`, `access`, `ordering`, `published`, `iscore`, `client_id`, `checked_out`, `checked_out_time`, `params`) VALUES ('VirtueMart Product Snapshot', 'vmproductsnapshots', 'content', 0, 0, 0, 0, 0, 0, '0000-00-00 00:00:00', '');
INSERT IGNORE INTO `mos_mambots` (`name`, `element`, `folder`, `access`, `ordering`, `published`, `iscore`, `client_id`, `checked_out`, `checked_out_time`, `params`) VALUES ('VirtueMart Search', 'virtuemart.searchbot', 'search', 0, 0, 0, 0, 0, 0, '0000-00-00 00:00:00', '');
INSERT IGNORE INTO `mos_mambots` (`name`, `element`, `folder`, `access`, `ordering`, `published`, `iscore`, `client_id`, `checked_out`, `checked_out_time`, `params`) VALUES ('VirtueMart Xtd Search', 'vmxsearch.searchbot', 'search', 0, 0, 0, 0, 0, 0, '0000-00-00 00:00:00', '');
####


5.  In the Joomla! / Mambo backend browse to "Modules" => "Site Modules" and
	search for VirtueMart modules.
	Select each of them step-by-step and set them to "published".
	Please note that you MUST PUBLISH THE 
		"VirtueMart Module"

administrator/components/com_virtuemart/LICENSE.php100644 0 0 45075 10727733223 20146 0ustar 0 0
GNU GENERAL PUBLIC LICENSE
		       Version 2, June 1991

 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

			    Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users.  This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it.  (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.)  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

  To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have.  You must make sure that they, too, receive or can get the
source code.  And you must show them these terms so they know their
rights.

  We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

  Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software.  If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

  Finally, any free program is threatened constantly by software
patents.  We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary.  To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

  The precise terms and conditions for copying, distribution and
modification follow.

		    GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License.  The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language.  (Hereinafter, translation is included without limitation in
the term "modification".)  Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.

  1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

  2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) You must cause the modified files to carry prominent notices
    stating that you changed the files and the date of any change.

    b) You must cause any work that you distribute or publish, that in
    whole or in part contains or is derived from the Program or any
    part thereof, to be licensed as a whole at no charge to all third
    parties under the terms of this License.

    c) If the modified program normally reads commands interactively
    when run, you must cause it, when started running for such
    interactive use in the most ordinary way, to print or display an
    announcement including an appropriate copyright notice and a
    notice that there is no warranty (or else, saying that you provide
    a warranty) and that users may redistribute the program under
    these conditions, and telling the user how to view a copy of this
    License.  (Exception: if the Program itself is interactive but
    does not normally print such an announcement, your work based on
    the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:

    a) Accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of Sections
    1 and 2 above on a medium customarily used for software interchange; or,

    b) Accompany it with a written offer, valid for at least three
    years, to give any third party, for a charge no more than your
    cost of physically performing source distribution, a complete
    machine-readable copy of the corresponding source code, to be
    distributed under the terms of Sections 1 and 2 above on a medium
    customarily used for software interchange; or,

    c) Accompany it with the information you received as to the offer
    to distribute corresponding source code.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form with such
    an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for
making modifications to it.  For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable.  However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.

  4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License.  Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

  5. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Program or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

  7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all.  For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded.  In such case, this License incorporates
the limitation as if written in the body of this License.

  9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number.  If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.

  10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.

			    NO WARRANTY

  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.

  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.

		     END OF TERMS AND CONDITIONS

	    How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    #one line to give the program's name and a brief idea of what it does.#
    Copyright (C) #year #name of author

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:

    Gnomovision version 69, Copyright (C) year name of author
    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary.  Here is a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  `Gnomovision' (which makes passes at compilers) written by James Hacker.

  <signature of Ty Coon>, 1 April 1989
  Ty Coon, President of Vice

This General Public License does not permit incorporating your program into
proprietary programs.  If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library.  If this is what you want to do, use the GNU Library General
Public License instead of this License.
administrator/components/com_virtuemart/PEAR.php100644 0 0 76406 11263443354 17614 0ustar 0 0 * @author Stig Bakken * @author Tomas V.V.Cox * * * @version $Id: PEAR.php 1958 2009-10-08 20:09:57Z soeren_nb $ * @package VirtueMart * @subpackage core * @copyright Copyright (C) 2004-2007 soeren - All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php * VirtueMart is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See /administrator/components/com_virtuemart/COPYRIGHT.php for copyright notices and details. * * http://virtuemart.net */ // // +--------------------------------------------------------------------+ // | PEAR, the PHP Extension and Application Repository | // +--------------------------------------------------------------------+ // | Copyright (c) 1997-2004 The PHP Group | // +--------------------------------------------------------------------+ // | This source file is subject to version 2.0 of the PHP license, | // | that is bundled with this package in the file LICENSE, and is | // | available through the world-wide-web at the following url: | // | http://www.php.net/license/3_0.txt. | // | If you did not receive a copy of the PHP license and are unable to | // | obtain it through the world-wide-web, please send a note to | // | license@php.net so we can mail you a copy immediately. | // +--------------------------------------------------------------------+ // | Authors: Sterling Hughes | // | Stig Bakken | // | Tomas V.V.Cox | // +--------------------------------------------------------------------+ // // $Id: PEAR.php 1958 2009-10-08 20:09:57Z soeren_nb $ // define('PEAR_ERROR_RETURN', 1); define('PEAR_ERROR_PRINT', 2); define('PEAR_ERROR_TRIGGER', 4); define('PEAR_ERROR_DIE', 8); define('PEAR_ERROR_CALLBACK', 16); /** * WARNING: obsolete * @deprecated */ define('PEAR_ERROR_EXCEPTION', 32); define('PEAR_ZE2', (function_exists('version_compare') && version_compare(zend_version(), "2-dev", "ge"))); if (substr(PHP_OS, 0, 3) == 'WIN') { define('OS_WINDOWS', true); define('OS_UNIX', false); define('PEAR_OS', 'Windows'); } else { define('OS_WINDOWS', false); define('OS_UNIX', true); define('PEAR_OS', 'Unix'); // blatant assumption } // instant backwards compatibility if (!defined('PATH_SEPARATOR')) { if (OS_WINDOWS) { define('PATH_SEPARATOR', ';'); } else { define('PATH_SEPARATOR', ':'); } } $GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_RETURN; $GLOBALS['_PEAR_default_error_options'] = E_USER_NOTICE; $GLOBALS['_PEAR_destructor_object_list'] = array(); $GLOBALS['_PEAR_shutdown_funcs'] = array(); $GLOBALS['_PEAR_error_handler_stack'] = array(); ini_set('track_errors', true); /** * Base class for other PEAR classes. Provides rudimentary * emulation of destructors. * * If you want a destructor in your class, inherit PEAR and make a * destructor method called _yourclassname (same name as the * constructor, but with a "_" prefix). Also, in your constructor you * have to call the PEAR constructor: $this->PEAR();. * The destructor method will be called without parameters. Note that * at in some SAPI implementations (such as Apache), any output during * the request shutdown (in which destructors are called) seems to be * discarded. If you need to get any debug information from your * destructor, use error_log(), syslog() or something similar. * * IMPORTANT! To use the emulated destructors you need to create the * objects by reference: $obj = new PEAR_child; * * @since PHP 4.0.2 * @author Stig Bakken * @see http://pear.php.net/manual/ */ class PEAR { // {{{ properties /** * Whether to enable internal debug messages. * * @var bool * @access private */ var $_debug = false; /** * Default error mode for this object. * * @var int * @access private */ var $_default_error_mode = null; /** * Default error options used for this object when error mode * is PEAR_ERROR_TRIGGER. * * @var int * @access private */ var $_default_error_options = null; /** * Default error handler (callback) for this object, if error mode is * PEAR_ERROR_CALLBACK. * * @var string * @access private */ var $_default_error_handler = ''; /** * Which class to use for error objects. * * @var string * @access private */ var $_error_class = 'PEAR_Error'; /** * An array of expected errors. * * @var array * @access private */ var $_expected_errors = array(); // }}} // {{{ constructor /** * Constructor. Registers this object in * $_PEAR_destructor_object_list for destructor emulation if a * destructor object exists. * * @param string $error_class (optional) which class to use for * error objects, defaults to PEAR_Error. * @access public * @return void */ function PEAR($error_class = null) { $classname = get_class($this); if ($this->_debug) { print "PEAR constructor called, class=$classname\n"; } if ($error_class !== null) { $this->_error_class = $error_class; } while ($classname) { $destructor = "_$classname"; if (method_exists($this, $destructor)) { global $_PEAR_destructor_object_list; $_PEAR_destructor_object_list[] = &$this; break; } else { $classname = get_parent_class($classname); } } } // }}} // {{{ destructor /** * Destructor (the emulated type of...). Does nothing right now, * but is included for forward compatibility, so subclass * destructors should always call it. * * See the note in the class desciption about output from * destructors. * * @access public * @return void */ function _PEAR() { if ($this->_debug) { printf("PEAR destructor called, class=%s\n", get_class($this)); } } // }}} // {{{ getStaticProperty() /** * If you have a class that's mostly/entirely static, and you need static * properties, you can use this method to simulate them. Eg. in your method(s) * do this: $myVar = &PEAR::getStaticProperty('myclass', 'myVar'); * You MUST use a reference, or they will not persist! * * @access public * @param string $class The calling classname, to prevent clashes * @param string $var The variable to retrieve. * @return mixed A reference to the variable. If not set it will be * auto initialised to NULL. */ function &getStaticProperty($class, $var) { static $properties; return $properties[$class][$var]; } // }}} // {{{ registerShutdownFunc() /** * Use this function to register a shutdown method for static * classes. * * @access public * @param mixed $func The function name (or array of class/method) to call * @param mixed $args The arguments to pass to the function * @return void */ function registerShutdownFunc($func, $args = array()) { $GLOBALS['_PEAR_shutdown_funcs'][] = array($func, $args); } // }}} // {{{ isError() /** * Tell whether a value is a PEAR error. * * @param mixed $data the value to test * @param int $code if $data is an error object, return true * only if $code is a string and * $obj->getMessage() == $code or * $code is an integer and $obj->getCode() == $code * @access public * @return bool true if parameter is an error */ function isError($data, $code = null) { if (is_a($data, 'PEAR_Error')) { if (is_null($code)) { return true; } elseif (is_string($code)) { return $data->getMessage() == $code; } else { return $data->getCode() == $code; } } return false; } // }}} // {{{ setErrorHandling() /** * Sets how errors generated by this object should be handled. * Can be invoked both in objects and statically. If called * statically, setErrorHandling sets the default behaviour for all * PEAR objects. If called in an object, setErrorHandling sets * the default behaviour for that object. * * @param int $mode * One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT, * PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE, * PEAR_ERROR_CALLBACK or PEAR_ERROR_EXCEPTION. * * @param mixed $options * When $mode is PEAR_ERROR_TRIGGER, this is the error level (one * of E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR). * * When $mode is PEAR_ERROR_CALLBACK, this parameter is expected * to be the callback function or method. A callback * function is a string with the name of the function, a * callback method is an array of two elements: the element * at index 0 is the object, and the element at index 1 is * the name of the method to call in the object. * * When $mode is PEAR_ERROR_PRINT or PEAR_ERROR_DIE, this is * a printf format string used when printing the error * message. * * @access public * @return void * @see PEAR_ERROR_RETURN * @see PEAR_ERROR_PRINT * @see PEAR_ERROR_TRIGGER * @see PEAR_ERROR_DIE * @see PEAR_ERROR_CALLBACK * @see PEAR_ERROR_EXCEPTION * * @since PHP 4.0.5 */ function setErrorHandling($mode = null, $options = null) { if (isset($this) && is_a($this, 'PEAR')) { $setmode = &$this->_default_error_mode; $setoptions = &$this->_default_error_options; } else { $setmode = &$GLOBALS['_PEAR_default_error_mode']; $setoptions = &$GLOBALS['_PEAR_default_error_options']; } switch ($mode) { case PEAR_ERROR_EXCEPTION: case PEAR_ERROR_RETURN: case PEAR_ERROR_PRINT: case PEAR_ERROR_TRIGGER: case PEAR_ERROR_DIE: case null: $setmode = $mode; $setoptions = $options; break; case PEAR_ERROR_CALLBACK: $setmode = $mode; // class/object method callback if (is_callable($options)) { $setoptions = $options; } else { trigger_error("invalid error callback", E_USER_WARNING); } break; default: trigger_error("invalid error mode", E_USER_WARNING); break; } } // }}} // {{{ expectError() /** * This method is used to tell which errors you expect to get. * Expected errors are always returned with error mode * PEAR_ERROR_RETURN. Expected error codes are stored in a stack, * and this method pushes a new element onto it. The list of * expected errors are in effect until they are popped off the * stack with the popExpect() method. * * Note that this method can not be called statically * * @param mixed $code a single error code or an array of error codes to expect * * @return int the new depth of the "expected errors" stack * @access public */ function expectError($code = '*') { if (is_array($code)) { array_push($this->_expected_errors, $code); } else { array_push($this->_expected_errors, array($code)); } return sizeof($this->_expected_errors); } // }}} // {{{ popExpect() /** * This method pops one element off the expected error codes * stack. * * @return array the list of error codes that were popped */ function popExpect() { return array_pop($this->_expected_errors); } // }}} // {{{ _checkDelExpect() /** * This method checks unsets an error code if available * * @param mixed error code * @return bool true if the error code was unset, false otherwise * @access private * @since PHP 4.3.0 */ function _checkDelExpect($error_code) { $deleted = false; foreach ($this->_expected_errors AS $key => $error_array) { if (in_array($error_code, $error_array)) { unset($this->_expected_errors[$key][array_search($error_code, $error_array)]); $deleted = true; } // clean up empty arrays if (0 == count($this->_expected_errors[$key])) { unset($this->_expected_errors[$key]); } } return $deleted; } // }}} // {{{ delExpect() /** * This method deletes all occurences of the specified element from * the expected error codes stack. * * @param mixed $error_code error code that should be deleted * @return mixed list of error codes that were deleted or error * @access public * @since PHP 4.3.0 */ function delExpect($error_code) { $deleted = false; if ((is_array($error_code) && (0 != count($error_code)))) { // $error_code is a non-empty array here; // we walk through it trying to unset all // values foreach($error_code as $key => $error) { if ($this->_checkDelExpect($error)) { $deleted = true; } else { $deleted = false; } } return $deleted ? true : PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME } elseif (!empty($error_code)) { // $error_code comes alone, trying to unset it if ($this->_checkDelExpect($error_code)) { return true; } else { return PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME } } else { // $error_code is empty return PEAR::raiseError("The expected error you submitted is empty"); // IMPROVE ME } } // }}} // {{{ raiseError() /** * This method is a wrapper that returns an instance of the * configured error class with this object's default error * handling applied. If the $mode and $options parameters are not * specified, the object's defaults are used. * * @param mixed $message a text error message or a PEAR error object * * @param int $code a numeric error code (it is up to your class * to define these if you want to use codes) * * @param int $mode One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT, * PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE, * PEAR_ERROR_CALLBACK, PEAR_ERROR_EXCEPTION. * * @param mixed $options If $mode is PEAR_ERROR_TRIGGER, this parameter * specifies the PHP-internal error level (one of * E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR). * If $mode is PEAR_ERROR_CALLBACK, this * parameter specifies the callback function or * method. In other error modes this parameter * is ignored. * * @param string $userinfo If you need to pass along for example debug * information, this parameter is meant for that. * * @param string $error_class The returned error object will be * instantiated from this class, if specified. * * @param bool $skipmsg If true, raiseError will only pass error codes, * the error message parameter will be dropped. * * @access public * @return object a PEAR error object * @see PEAR::setErrorHandling * @since PHP 4.0.5 */ function raiseError($message = null, $code = null, $mode = null, $options = null, $userinfo = null, $error_class = null, $skipmsg = false) { // The error is yet a PEAR error object if (is_object($message)) { $code = $message->getCode(); $userinfo = $message->getUserInfo(); $error_class = $message->getType(); $message->error_message_prefix = ''; $message = $message->getMessage(); } if (isset($this) && isset($this->_expected_errors) && sizeof($this->_expected_errors) > 0 && sizeof($exp = end($this->_expected_errors))) { if ($exp[0] == "*" || (is_int(reset($exp)) && in_array($code, $exp)) || (is_string(reset($exp)) && in_array($message, $exp))) { $mode = PEAR_ERROR_RETURN; } } // No mode given, try global ones if ($mode === null) { // Class error handler if (isset($this) && isset($this->_default_error_mode)) { $mode = $this->_default_error_mode; $options = $this->_default_error_options; // Global error handler } elseif (isset($GLOBALS['_PEAR_default_error_mode'])) { $mode = $GLOBALS['_PEAR_default_error_mode']; $options = $GLOBALS['_PEAR_default_error_options']; } } if ($error_class !== null) { $ec = $error_class; } elseif (isset($this) && isset($this->_error_class)) { $ec = $this->_error_class; } else { $ec = 'PEAR_Error'; } if ($skipmsg) { return new $ec($code, $mode, $options, $userinfo); } else { return new $ec($message, $code, $mode, $options, $userinfo); } } // }}} // {{{ throwError() /** * Simpler form of raiseError with fewer options. In most cases * message, code and userinfo are enough. * * @param string $message * */ function throwError($message = null, $code = null, $userinfo = null) { if (isset($this) && is_a($this, 'PEAR')) { return $this->raiseError($message, $code, null, null, $userinfo); } else { return PEAR::raiseError($message, $code, null, null, $userinfo); } } // }}} // {{{ pushErrorHandling() /** * Push a new error handler on top of the error handler options stack. With this * you can easily override the actual error handler for some code and restore * it later with popErrorHandling. * * @param mixed $mode (same as setErrorHandling) * @param mixed $options (same as setErrorHandling) * * @return bool Always true * * @see PEAR::setErrorHandling */ function pushErrorHandling($mode, $options = null) { $stack = &$GLOBALS['_PEAR_error_handler_stack']; if (isset($this) && is_a($this, 'PEAR')) { $def_mode = &$this->_default_error_mode; $def_options = &$this->_default_error_options; } else { $def_mode = &$GLOBALS['_PEAR_default_error_mode']; $def_options = &$GLOBALS['_PEAR_default_error_options']; } $stack[] = array($def_mode, $def_options); if (isset($this) && is_a($this, 'PEAR')) { $this->setErrorHandling($mode, $options); } else { PEAR::setErrorHandling($mode, $options); } $stack[] = array($mode, $options); return true; } // }}} // {{{ popErrorHandling() /** * Pop the last error handler used * * @return bool Always true * * @see PEAR::pushErrorHandling */ function popErrorHandling() { $stack = &$GLOBALS['_PEAR_error_handler_stack']; array_pop($stack); list($mode, $options) = $stack[sizeof($stack) - 1]; array_pop($stack); if (isset($this) && is_a($this, 'PEAR')) { $this->setErrorHandling($mode, $options); } else { PEAR::setErrorHandling($mode, $options); } return true; } // }}} // {{{ loadExtension() /** * OS independant PHP extension load. Remember to take care * on the correct extension name for case sensitive OSes. * * @param string $ext The extension name * @return bool Success or not on the dl() call */ function loadExtension($ext) { if (!extension_loaded($ext)) { // if either returns true dl() will produce a FATAL error, stop that if ((ini_get('enable_dl') != 1) || (ini_get('safe_mode') == 1)) { return false; } if (OS_WINDOWS) { $suffix = '.dll'; } elseif (PHP_OS == 'HP-UX') { $suffix = '.sl'; } elseif (PHP_OS == 'AIX') { $suffix = '.a'; } elseif (PHP_OS == 'OSX') { $suffix = '.bundle'; } else { $suffix = '.so'; } return @dl('php_'.$ext.$suffix) || @dl($ext.$suffix); } return true; } // }}} } // {{{ _PEAR_call_destructors() function _PEAR_call_destructors() { global $_PEAR_destructor_object_list; if (is_array($_PEAR_destructor_object_list) && sizeof($_PEAR_destructor_object_list)) { reset($_PEAR_destructor_object_list); while (list($k, $objref) = each($_PEAR_destructor_object_list)) { $classname = get_class($objref); while ($classname) { $destructor = "_$classname"; if (method_exists($objref, $destructor)) { $objref->$destructor(); break; } else { $classname = get_parent_class($classname); } } } // Empty the object list to ensure that destructors are // not called more than once. $_PEAR_destructor_object_list = array(); } // Now call the shutdown functions if (is_array($GLOBALS['_PEAR_shutdown_funcs']) AND !empty($GLOBALS['_PEAR_shutdown_funcs'])) { foreach ($GLOBALS['_PEAR_shutdown_funcs'] as $value) { call_user_func_array($value[0], $value[1]); } } } // }}} class PEAR_Error { // {{{ properties var $error_message_prefix = ''; var $mode = PEAR_ERROR_RETURN; var $level = E_USER_NOTICE; var $code = -1; var $message = ''; var $userinfo = ''; var $backtrace = null; // }}} // {{{ constructor /** * PEAR_Error constructor * * @param string $message message * * @param int $code (optional) error code * * @param int $mode (optional) error mode, one of: PEAR_ERROR_RETURN, * PEAR_ERROR_PRINT, PEAR_ERROR_DIE, PEAR_ERROR_TRIGGER, * PEAR_ERROR_CALLBACK or PEAR_ERROR_EXCEPTION * * @param mixed $options (optional) error level, _OR_ in the case of * PEAR_ERROR_CALLBACK, the callback function or object/method * tuple. * * @param string $userinfo (optional) additional user/debug info * * @access public * */ function PEAR_Error($message = 'unknown error', $code = null, $mode = null, $options = null, $userinfo = null) { if ($mode === null) { $mode = PEAR_ERROR_RETURN; } $this->message = $message; $this->code = $code; $this->mode = $mode; $this->userinfo = $userinfo; if (function_exists("debug_backtrace")) { $this->backtrace = debug_backtrace(); } if ($mode & PEAR_ERROR_CALLBACK) { $this->level = E_USER_NOTICE; $this->callback = $options; } else { if ($options === null) { $options = E_USER_NOTICE; } $this->level = $options; $this->callback = null; } if ($this->mode & PEAR_ERROR_PRINT) { if (is_null($options) || is_int($options)) { $format = "%s"; } else { $format = $options; } printf($format, $this->getMessage()); } if ($this->mode & PEAR_ERROR_TRIGGER) { trigger_error($this->getMessage(), $this->level); } if ($this->mode & PEAR_ERROR_DIE) { $msg = $this->getMessage(); if (is_null($options) || is_int($options)) { $format = "%s"; if (substr($msg, -1) != "\n") { $msg .= "\n"; } } else { $format = $options; } die(sprintf($format, $msg)); } if ($this->mode & PEAR_ERROR_CALLBACK) { if (is_callable($this->callback)) { call_user_func($this->callback, $this); } } if ($this->mode & PEAR_ERROR_EXCEPTION) { trigger_error("PEAR_ERROR_EXCEPTION is obsolete, use class PEAR_ErrorStack for exceptions", E_USER_WARNING); eval('$e = new Exception($this->message, $this->code);$e->PEAR_Error = $this;throw($e);'); } } // }}} // {{{ getMode() /** * Get the error mode from an error object. * * @return int error mode * @access public */ function getMode() { return $this->mode; } // }}} // {{{ getCallback() /** * Get the callback function/method from an error object. * * @return mixed callback function or object/method array * @access public */ function getCallback() { return $this->callback; } // }}} // {{{ getMessage() /** * Get the error message from an error object. * * @return string full error message * @access public */ function getMessage() { return ($this->error_message_prefix . $this->message); } // }}} // {{{ getCode() /** * Get error code from an error object * * @return int error code * @access public */ function getCode() { return $this->code; } // }}} // {{{ getType() /** * Get the name of this error/exception. * * @return string error/exception name (type) * @access public */ function getType() { return get_class($this); } // }}} // {{{ getUserInfo() /** * Get additional user-supplied information. * * @return string user-supplied information * @access public */ function getUserInfo() { return $this->userinfo; } // }}} // {{{ getDebugInfo() /** * Get additional debug information supplied by the application. * * @return string debug information * @access public */ function getDebugInfo() { return $this->getUserInfo(); } // }}} // {{{ getBacktrace() /** * Get the call backtrace from where the error was generated. * Supported with PHP 4.3.0 or newer. * * @param int $frame (optional) what frame to fetch * @return array Backtrace, or NULL if not available. * @access public */ function getBacktrace($frame = null) { if ($frame === null) { return $this->backtrace; } return $this->backtrace[$frame]; } // }}} // {{{ addUserInfo() function addUserInfo($info) { if (empty($this->userinfo)) { $this->userinfo = $info; } else { $this->userinfo .= " ** $info"; } } // }}} // {{{ toString() /** * Make a string representation of this object. * * @return string a string with an object summary * @access public */ function toString() { $modes = array(); $levels = array(E_USER_NOTICE => 'notice', E_USER_WARNING => 'warning', E_USER_ERROR => 'error'); if ($this->mode & PEAR_ERROR_CALLBACK) { if (is_array($this->callback)) { $callback = get_class($this->callback[0]) . '::' . $this->callback[1]; } else { $callback = $this->callback; } return sprintf('[%s: message="%s" code=%d mode=callback '. 'callback=%s prefix="%s" info="%s"]', get_class($this), $this->message, $this->code, $callback, $this->error_message_prefix, $this->userinfo); } if ($this->mode & PEAR_ERROR_PRINT) { $modes[] = 'print'; } if ($this->mode & PEAR_ERROR_TRIGGER) { $modes[] = 'trigger'; } if ($this->mode & PEAR_ERROR_DIE) { $modes[] = 'die'; } if ($this->mode & PEAR_ERROR_RETURN) { $modes[] = 'return'; } return sprintf('[%s: message="%s" code=%d mode=%s level=%s '. 'prefix="%s" info="%s"]', get_class($this), $this->message, $this->code, implode("|", $modes), $levels[$this->level], $this->error_message_prefix, $this->userinfo); } // }}} } register_shutdown_function("_PEAR_call_destructors"); /* * Local Variables: * mode: php * tab-width: 4 * c-basic-offset: 4 * End: */ ?> administrator/components/com_virtuemart/README.php100644 0 0 17401 11254672536 20016 0ustar 0 0
****************
VirtueMart 1.1
****************
Complete Package for Joomla! 1.0.x, Joomla! 1.5.x and Mambo >= 4.5.1

You can't use this software on an earlier Mambo version than 4.5.2 (e.g. Mambo 4.5 1.0.9) 
without running into serious problems.

Copyright (C) 2004-2009 soeren - All rights reserved.
License: http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
VirtueMart is free software. This version may have been modified pursuant
to the GNU General Public License, and as distributed it includes or
is derivative of works licensed under the GNU General Public License or
other free or open source software licenses.

Community Home: http://virtuemart.net

****************

##########################
Package Contents:
##########################

 * 1 component (com_virtuemart_1.1.x.zip for Joomla! 1.0.x and Mambo or com_virtuemart_1.1.x.j15.zip for Joomla! 1.5)
   INSTALLATION REQUIRED!
   
 * 1 main module (mod_virtuemart_1.1.x.zip for Joomla! 1.0.x and Mambo or mod_virtuemart_1.1.x.j15.zip for Joomla! 1.5)
   INSTALLATION REQUIRED!
   
 * 12 additional modules
 
 * Mambots / plugins
 
 * 3 mambots for Jooma! 1.0.x or mambo
   - 2 search mambots for integration into the site search (virtuemart.searchbot and vmxsearch.searchbot), 
   - 1 content mambot for displaying product details in content items (vmproductproductsnapshots)

-OR-

 * 2 plugins for Jooma! 1.5.x
   - 1 search plugin for integration into the site search (vmxsearch.plugin), 
   - 1 content mambot for displaying product details in content items (vmproductproductsnapshots)
   

##########################
   ABOUT
##########################
VirtueMart is an Open Source Online-Shop / Shopping Cart Web-Application.
It's a Component (means plugin / extension) for the Content Management Systems "Joomla!" and "Mambo"
and can't be used without one of both. It installs fairly easy using the automatic installers. 
It's intended for use in small / mid-sized Online businesses / Online-Shops. 
So every user who wants to build up a Online Store can use this component for selling something to customers.

This package is for New Installations and updates from mambo-phpShop. 

You just need a working Joomla/Mambo Installation. 
You can get your copy  of Joomla from http://joomla.org

This package contains some code from the original 0.8.0 Edikon Corp. phpShop distribution available at www.phpshop.org

This package was successfully tested on 
- Joomla 1.0.15
- Joomla 1.5.14

 -- IMPORTANT --
Please note that module and component SHOULD be used together! 
The thing is that you can only access all areas of the component via the VirtueMart Main Module links.

You can surely create a new Menu Item linking to VirtueMart, but you must also publish the VirtueMart module.

##########################
   INSTALLATION
##########################
The installation is really easy - 
thanks to the automatic installer!
You don't need to unpack any of the archives in this complete package!

1. If you have unpacked this archive (VirtueMart_x.x_COMPLETE_PACKAGE.zip), 
	you'll see a lot of other archives.
	- com_virtuemart_x.xxx.zip, 
	- some files beginning with mod_*.zip 
	- other packages (these are the mambots/plugins).
    
2. Login to the Administration Backend (/administrator on your site).
        
        Now go to "Installers" => "Components"
        or - if you are using an older Mambo version: "Components" --> "Install/Uninstall".
        
        You can see an upload form now.
        Select the file 
        - com_virtuemart_x.xx.zip 
        and click 'Upload Component'
        
        If everything is ok, you should see a "Welcome ..." screen.
        Choose you way of installation to finish the component installation.
        
3. Now we have to install the main module, which will help you to browse
        your categories and products.
        Go to "Installers" => "Modules"
        (or - if you're using an older Mambo version: "Modules" => "Install/Uninstall"), 
        and select the file 
        - mod_virtuemart_x.xx.zip
        and then click 'Upload module'.
    
4. The module is installed, but it still is not published!
	To publish that module on your site, you must go to the list of 
	your all modules. So now head on to 
	"Modules" => "Site Modules".
	You should somewhere see a module entry for "Virtuemart Module"
	with "mod_virtuemart" at the end of that row.
	If necessary, browse to the next page of the module list.
	If you've found the module, please select it's checkbox and click
	on "Edit" in the toolbar.
	Make your settings and don't forget to select "Published? - Yes".

       Note:
       Since unpublished modules and components appear by default on 
       the last page of  the modules listed, you may need to browse component 
       and module pages until you find the VirtueMart module.
       
	Now Save - and: Done.   
    
       Note: As long as the VirtueMart main module is NOT published, VirtueMart can't be used properly.

        IF successful, the installer will have created the following directory structure:
        
         /components/com_virtuemart
         - contains code for non-administrative surfing and ordering
         
         /components/com_virtuemart/js
         - contains JavaScript Files
		 
         /components/com_virtuemart/js/dtree
         - contains JS files and images for dTree usage.
		 
         /administrator/components/com_virtuemart/html/themes
         
         /components/com_virtuemart/shop_image
         /components/com_virtuemart/shop_image/vendor
         - contains the vendor images
		 
         /components/com_virtuemart/shop_image/product
         - contains the product images
         
         /components/com_virtuemart/shop_image/ps_image
         - contains general administration/shop images
         
         /components/com_virtuemart/shop_image/stars
         
         /administrator/components/com_virtuemart
         - contains config files and the main virtuemart-parser
         
         /administrator/components/com_virtuemart/classes
         - contains all the class files
         
         /administrator/components/com_virtuemart/html
         - contains all pages accessible for the shop
         
         /administrator/components/com_virtuemart/languages
         - contains the language files
         
   
##########################
   UNINSTALL
##########################

1. Go to "Installers" => "Components" (or "Modules")
	( or - if you're using Mambo - "Components" ( or "Modules" ) => "Install/Uninstall"
        
2. Now select 'VirtueMart' ( or for the module: 'mod_virtuemart' )
	and click on 'Delete'.
   
    Done.

#
############################
#

For updates / changes / hints please read the ChangeLog!
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


Developers, Documentation Writers, Helpers and Coders are welcome to help us. 
Please contact me: soeren|at|virtuemart.net

The VirtueMart Software needs Helpers to evolve.
administrator/components/com_virtuemart/TODO.php100644 0 0 3730 10722610140 17564 0ustar 0 0
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  VirtueMart To-Do List
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 Know Bugs
##################

See Bugtracker:
http://dev.virtuemart.net/cb/proj/tracker.do?proj_id=1


 FEATURES TO BE IMPLEMENTED
############################

* XML - Product Data Import/Export
* XML - Order Data Import/Export

* make Orders changeable afterwards
* bulk update of order statuses
* send Notification on new reviews
* send Notifications to customer + store owner (config option)

* Shipping Rate per Product
* "Compare Products"
* Tool to Remove all Products
* Add Discount on *all* Products
* Discount for Cart Total (> $100 = 1% discount...)
* Tool to Remove Orphan Images

* Gift- / Wish - List
* allow "Send as Gift" with individual Text on Order

* Modular Checkout
* Changeable Registration Form
  - allow Declaration of new Fields
  - make Fields reorderable
  - make Fields required / not required
  - switch Shopper Group including / excluding tax

 General to-do 
##################

* improve performance
  - Reduce Numbers of SQL Queries
  - Remove doubled function calls
  
* XHTML - Compliance, make it Barrier-free
* clean up checkout
administrator/components/com_virtuemart/Tar.php100644 0 0 164456 10772244673 17645 0ustar 0 0 * * * @version $Id: Tar.php 1323 2008-03-25 18:51:39Z soeren_nb $ * @package VirtueMart * @subpackage core * @copyright Copyright (C) 2004-2007 soeren - All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php * VirtueMart is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See /administrator/components/com_virtuemart/COPYRIGHT.php for copyright notices and details. * * http://virtuemart.net */ /* vim: set ts=4 sw=4: */ // +----------------------------------------------------------------------+ // | PHP Version 4 | // +----------------------------------------------------------------------+ // | Copyright (c) 1997-2003 The PHP Group | // +----------------------------------------------------------------------+ // | This source file is subject to version 3.0 of the PHP license, | // | that is bundled with this package in the file LICENSE, and is | // | available through the world-wide-web at the following url: | // | http://www.php.net/license/3_0.txt. | // | If you did not receive a copy of the PHP license and are unable to | // | obtain it through the world-wide-web, please send a note to | // | license@php.net so we can mail you a copy immediately. | // +----------------------------------------------------------------------+ // | Author: Vincent Blavet | // +----------------------------------------------------------------------+ require_once( $mosConfig_absolute_path.'/administrator/components/com_virtuemart/PEAR.php' ); define ('ARCHIVE_TAR_ATT_SEPARATOR', 90001); /** * Creates a (compressed) Tar archive * * @author Vincent Blavet * @version $Revision: 1323 $ * @package Archive */ class Archive_Tar extends PEAR { /** * @var string Name of the Tar */ var $_tarname=''; /** * @var boolean if true, the Tar file will be gzipped */ var $_compress=false; /** * @var string Type of compression : 'none', 'gz' or 'bz2' */ var $_compress_type='none'; /** * @var string Explode separator */ var $_separator=' '; /** * @var file descriptor */ var $_file=0; /** * @var string Local Tar name of a remote Tar (http:// or ftp://) */ var $_temp_tarname=''; // {{{ constructor /** * Archive_Tar Class constructor. This flavour of the constructor only * declare a new Archive_Tar object, identifying it by the name of the * tar file. * If the compress argument is set the tar will be read or created as a * gzip or bz2 compressed TAR file. * * @param string $p_tarname The name of the tar archive to create * @param string $p_compress can be null, 'gz' or 'bz2'. This * parameter indicates if gzip or bz2 compression * is required. For compatibility reason the * boolean value 'true' means 'gz'. * @access public */ function Archive_Tar($p_tarname, $p_compress = null) { global $mosConfig_absolute_path; $this->PEAR(); $this->_compress = false; $this->_compress_type = 'none'; if ($p_compress === null) { if (@file_exists($p_tarname)) { if ($fp = @fopen($p_tarname, "rb")) { // look for gzip magic cookie $data = fread($fp, 2); fclose($fp); if ($data == "\37\213") { $this->_compress = true; $this->_compress_type = 'gz'; // No sure it's enought for a magic code .... } elseif ($data == "BZ") { $this->_compress = true; $this->_compress_type = 'bz2'; } } } else { // probably a remote file or some file accessible // through a stream interface if (substr($p_tarname, -2) == 'gz') { $this->_compress = true; $this->_compress_type = 'gz'; } elseif ((substr($p_tarname, -3) == 'bz2') || (substr($p_tarname, -2) == 'bz')) { $this->_compress = true; $this->_compress_type = 'bz2'; } } } else { if (($p_compress === true) || ($p_compress == 'gz')) { $this->_compress = true; $this->_compress_type = 'gz'; } else if ($p_compress == 'bz2') { $this->_compress = true; $this->_compress_type = 'bz2'; } } $this->_tarname = $p_tarname; if ($this->_compress) { // assert zlib or bz2 extension support if ($this->_compress_type == 'gz') $extname = 'zlib'; else if ($this->_compress_type == 'bz2') $extname = 'bz2'; if (!extension_loaded($extname)) { PEAR::loadExtension($extname); } if (!extension_loaded($extname)) { die("The extension '$extname' couldn't be found.\n". "Please make sure your version of PHP was built ". "with '$extname' support.\n"); return false; } } } // }}} // {{{ destructor function _Archive_Tar() { $this->_close(); // ----- Look for a local copy to delete if ($this->_temp_tarname != '') @unlink($this->_temp_tarname); $this->_PEAR(); } // }}} // {{{ create() /** * This method creates the archive file and add the files / directories * that are listed in $p_filelist. * If a file with the same name exist and is writable, it is replaced * by the new tar. * The method return false and a PEAR error text. * The $p_filelist parameter can be an array of string, each string * representing a filename or a directory name with their path if * needed. It can also be a single string with names separated by a * single blank. * For each directory added in the archive, the files and * sub-directories are also added. * See also createModify() method for more details. * * @param array $p_filelist An array of filenames and directory names, or a single * string with names separated by a single blank space. * @return true on success, false on error. * @see createModify() * @access public */ function create($p_filelist) { return $this->createModify($p_filelist, '', ''); } // }}} // {{{ add() /** * This method add the files / directories that are listed in $p_filelist in * the archive. If the archive does not exist it is created. * The method return false and a PEAR error text. * The files and directories listed are only added at the end of the archive, * even if a file with the same name is already archived. * See also createModify() method for more details. * * @param array $p_filelist An array of filenames and directory names, or a single * string with names separated by a single blank space. * @return true on success, false on error. * @see createModify() * @access public */ function add($p_filelist) { return $this->addModify($p_filelist, '', ''); } // }}} // {{{ extract() function extract($p_path='') { return $this->extractModify($p_path, ''); } // }}} // {{{ listContent() function listContent() { $v_list_detail = array(); if ($this->_openRead()) { if (!$this->_extractList('', $v_list_detail, "list", '', '')) { unset($v_list_detail); $v_list_detail = 0; } $this->_close(); } return $v_list_detail; } // }}} // {{{ createModify() /** * This method creates the archive file and add the files / directories * that are listed in $p_filelist. * If the file already exists and is writable, it is replaced by the * new tar. It is a create and not an add. If the file exists and is * read-only or is a directory it is not replaced. The method return * false and a PEAR error text. * The $p_filelist parameter can be an array of string, each string * representing a filename or a directory name with their path if * needed. It can also be a single string with names separated by a * single blank. * The path indicated in $p_remove_dir will be removed from the * memorized path of each file / directory listed when this path * exists. By default nothing is removed (empty path '') * The path indicated in $p_add_dir will be added at the beginning of * the memorized path of each file / directory listed. However it can * be set to empty ''. The adding of a path is done after the removing * of path. * The path add/remove ability enables the user to prepare an archive * for extraction in a different path than the origin files are. * See also addModify() method for file adding properties. * * @param array $p_filelist An array of filenames and directory names, or a single * string with names separated by a single blank space. * @param string $p_add_dir A string which contains a path to be added to the * memorized path of each element in the list. * @param string $p_remove_dir A string which contains a path to be removed from * the memorized path of each element in the list, when * relevant. * @return boolean true on success, false on error. * @access public * @see addModify() */ function createModify($p_filelist, $p_add_dir, $p_remove_dir='') { $v_result = true; if (!$this->_openWrite()) return false; if ($p_filelist != '') { if (is_array($p_filelist)) $v_list = $p_filelist; elseif (is_string($p_filelist)) $v_list = explode($this->_separator, $p_filelist); else { $this->_cleanFile(); $this->_error('Invalid file list'); return false; } $v_result = $this->_addList($v_list, $p_add_dir, $p_remove_dir); } if ($v_result) { $this->_writeFooter(); $this->_close(); } else $this->_cleanFile(); return $v_result; } // }}} // {{{ addModify() /** * This method add the files / directories listed in $p_filelist at the * end of the existing archive. If the archive does not yet exists it * is created. * The $p_filelist parameter can be an array of string, each string * representing a filename or a directory name with their path if * needed. It can also be a single string with names separated by a * single blank. * The path indicated in $p_remove_dir will be removed from the * memorized path of each file / directory listed when this path * exists. By default nothing is removed (empty path '') * The path indicated in $p_add_dir will be added at the beginning of * the memorized path of each file / directory listed. However it can * be set to empty ''. The adding of a path is done after the removing * of path. * The path add/remove ability enables the user to prepare an archive * for extraction in a different path than the origin files are. * If a file/dir is already in the archive it will only be added at the * end of the archive. There is no update of the existing archived * file/dir. However while extracting the archive, the last file will * replace the first one. This results in a none optimization of the * archive size. * If a file/dir does not exist the file/dir is ignored. However an * error text is send to PEAR error. * If a file/dir is not readable the file/dir is ignored. However an * error text is send to PEAR error. * * @param array $p_filelist An array of filenames and directory names, or a single * string with names separated by a single blank space. * @param string $p_add_dir A string which contains a path to be added to the * memorized path of each element in the list. * @param string $p_remove_dir A string which contains a path to be removed from * the memorized path of each element in the list, when * relevant. * @return true on success, false on error. * @access public */ function addModify($p_filelist, $p_add_dir, $p_remove_dir='') { $v_result = true; if (!@is_file($this->_tarname)) $v_result = $this->createModify($p_filelist, $p_add_dir, $p_remove_dir); else { if (is_array($p_filelist)) $v_list = $p_filelist; elseif (is_string($p_filelist)) $v_list = explode($this->_separator, $p_filelist); else { $this->_error('Invalid file list'); return false; } $v_result = $this->_append($v_list, $p_add_dir, $p_remove_dir); } return $v_result; } // }}} // {{{ addString() /** * This method add a single string as a file at the * end of the existing archive. If the archive does not yet exists it * is created. * * @param string $p_filename A string which contains the full filename path * that will be associated with the string. * @param string $p_string The content of the file added in the archive. * @return true on success, false on error. * @access public */ function addString($p_filename, $p_string) { $v_result = true; if (!@is_file($this->_tarname)) { if (!$this->_openWrite()) { return false; } $this->_close(); } if (!$this->_openAppend()) return false; // Need to check the get back to the temporary file ? .... $v_result = $this->_addString($p_filename, $p_string); $this->_writeFooter(); $this->_close(); return $v_result; } // }}} // {{{ extractModify() /** * This method extract all the content of the archive in the directory * indicated by $p_path. When relevant the memorized path of the * files/dir can be modified by removing the $p_remove_path path at the * beginning of the file/dir path. * While extracting a file, if the directory path does not exists it is * created. * While extracting a file, if the file already exists it is replaced * without looking for last modification date. * While extracting a file, if the file already exists and is write * protected, the extraction is aborted. * While extracting a file, if a directory with the same name already * exists, the extraction is aborted. * While extracting a directory, if a file with the same name already * exists, the extraction is aborted. * While extracting a file/directory if the destination directory exist * and is write protected, or does not exist but can not be created, * the extraction is aborted. * If after extraction an extracted file does not show the correct * stored file size, the extraction is aborted. * When the extraction is aborted, a PEAR error text is set and false * is returned. However the result can be a partial extraction that may * need to be manually cleaned. * * @param string $p_path The path of the directory where the files/dir need to by * extracted. * @param string $p_remove_path Part of the memorized path that can be removed if * present at the beginning of the file/dir path. * @return boolean true on success, false on error. * @access public * @see extractList() */ function extractModify($p_path, $p_remove_path) { $v_result = true; $v_list_detail = array(); if ($v_result = $this->_openRead()) { $v_result = $this->_extractList($p_path, $v_list_detail, "complete", 0, $p_remove_path); $this->_close(); } return $v_result; } // }}} // {{{ extractInString() /** * This method extract from the archive one file identified by $p_filename. * The return value is a string with the file content, or NULL on error. * @param string $p_filename The path of the file to extract in a string. * @return a string with the file content or NULL. * @access public */ function extractInString($p_filename) { if ($this->_openRead()) { $v_result = $this->_extractInString($p_filename); $this->_close(); } else { $v_result = NULL; } return $v_result; } // }}} // {{{ extractList() /** * This method extract from the archive only the files indicated in the * $p_filelist. These files are extracted in the current directory or * in the directory indicated by the optional $p_path parameter. * If indicated the $p_remove_path can be used in the same way as it is * used in extractModify() method. * @param array $p_filelist An array of filenames and directory names, or a single * string with names separated by a single blank space. * @param string $p_path The path of the directory where the files/dir need to by * extracted. * @param string $p_remove_path Part of the memorized path that can be removed if * present at the beginning of the file/dir path. * @return true on success, false on error. * @access public * @see extractModify() */ function extractList($p_filelist, $p_path='', $p_remove_path='') { $v_result = true; $v_list_detail = array(); if (is_array($p_filelist)) $v_list = $p_filelist; elseif (is_string($p_filelist)) $v_list = explode($this->_separator, $p_filelist); else { $this->_error('Invalid string list'); return false; } if ($v_result = $this->_openRead()) { $v_result = $this->_extractList($p_path, $v_list_detail, "partial", $v_list, $p_remove_path); $this->_close(); } return $v_result; } // }}} // {{{ setAttribute() /** * This method set specific attributes of the archive. It uses a variable * list of parameters, in the format attribute code + attribute values : * $arch->setAttribute(ARCHIVE_TAR_ATT_SEPARATOR, ','); * @param mixed $argv variable list of attributes and values * @return true on success, false on error. * @access public */ function setAttribute() { $v_result = true; // ----- Get the number of variable list of arguments if (($v_size = func_num_args()) == 0) { return true; } // ----- Get the arguments $v_att_list = &func_get_args(); // ----- Read the attributes $i=0; while ($i<$v_size) { // ----- Look for next option switch ($v_att_list[$i]) { // ----- Look for options that request a string value case ARCHIVE_TAR_ATT_SEPARATOR : // ----- Check the number of parameters if (($i+1) >= $v_size) { $this->_error('Invalid number of parameters for attribute ARCHIVE_TAR_ATT_SEPARATOR'); return false; } // ----- Get the value $this->_separator = $v_att_list[$i+1]; $i++; break; default : $this->_error('Unknow attribute code '.$v_att_list[$i].''); return false; } // ----- Next attribute $i++; } return $v_result; } // }}} // {{{ _error() function _error($p_message) { // ----- To be completed $this->raiseError($p_message); } // }}} // {{{ _warning() function _warning($p_message) { // ----- To be completed $this->raiseError($p_message); } // }}} // {{{ _openWrite() function _openWrite() { if ($this->_compress_type == 'gz') $this->_file = @gzopen($this->_tarname, "wb"); else if ($this->_compress_type == 'bz2') $this->_file = @bzopen($this->_tarname, "wb"); else if ($this->_compress_type == 'none') $this->_file = @fopen($this->_tarname, "wb"); else $this->_error('Unknown or missing compression type ('.$this->_compress_type.')'); if ($this->_file == 0) { $this->_error('Unable to open in write mode \''.$this->_tarname.'\''); return false; } return true; } // }}} // {{{ _openRead() function _openRead() { if (strtolower(substr($this->_tarname, 0, 7)) == 'http://') { // ----- Look if a local copy need to be done if ($this->_temp_tarname == '') { $this->_temp_tarname = uniqid('tar').'.tmp'; if (!$v_file_from = @fopen($this->_tarname, 'rb')) { $this->_error('Unable to open in read mode \''.$this->_tarname.'\''); $this->_temp_tarname = ''; return false; } if (!$v_file_to = @fopen($this->_temp_tarname, 'wb')) { $this->_error('Unable to open in write mode \''.$this->_temp_tarname.'\''); $this->_temp_tarname = ''; return false; } while ($v_data = @fread($v_file_from, 1024)) @fwrite($v_file_to, $v_data); @fclose($v_file_from); @fclose($v_file_to); } // ----- File to open if the local copy $v_filename = $this->_temp_tarname; } else // ----- File to open if the normal Tar file $v_filename = $this->_tarname; if ($this->_compress_type == 'gz') $this->_file = @gzopen($v_filename, "rb"); else if ($this->_compress_type == 'bz2') $this->_file = @bzopen($v_filename, "rb"); else if ($this->_compress_type == 'none') $this->_file = @fopen($v_filename, "rb"); else $this->_error('Unknown or missing compression type ('.$this->_compress_type.')'); if ($this->_file == 0) { $this->_error('Unable to open in read mode \''.$v_filename.'\''); return false; } return true; } // }}} // {{{ _openReadWrite() function _openReadWrite() { if ($this->_compress_type == 'gz') $this->_file = @gzopen($this->_tarname, "r+b"); else if ($this->_compress_type == 'bz2') $this->_file = @bzopen($this->_tarname, "r+b"); else if ($this->_compress_type == 'none') $this->_file = @fopen($this->_tarname, "r+b"); else $this->_error('Unknown or missing compression type ('.$this->_compress_type.')'); if ($this->_file == 0) { $this->_error('Unable to open in read/write mode \''.$this->_tarname.'\''); return false; } return true; } // }}} // {{{ _close() function _close() { //if (isset($this->_file)) { if (is_resource($this->_file)) { if ($this->_compress_type == 'gz') @gzclose($this->_file); else if ($this->_compress_type == 'bz2') @bzclose($this->_file); else if ($this->_compress_type == 'none') @fclose($this->_file); else $this->_error('Unknown or missing compression type ('.$this->_compress_type.')'); $this->_file = 0; } // ----- Look if a local copy need to be erase // Note that it might be interesting to keep the url for a time : ToDo if ($this->_temp_tarname != '') { @unlink($this->_temp_tarname); $this->_temp_tarname = ''; } return true; } // }}} // {{{ _cleanFile() function _cleanFile() { $this->_close(); // ----- Look for a local copy if ($this->_temp_tarname != '') { // ----- Remove the local copy but not the remote tarname @unlink($this->_temp_tarname); $this->_temp_tarname = ''; } else { // ----- Remove the local tarname file @unlink($this->_tarname); } $this->_tarname = ''; return true; } // }}} // {{{ _writeBlock() function _writeBlock($p_binary_data, $p_len=null) { if (is_resource($this->_file)) { if ($p_len === null) { if ($this->_compress_type == 'gz') @gzputs($this->_file, $p_binary_data); else if ($this->_compress_type == 'bz2') @bzwrite($this->_file, $p_binary_data); else if ($this->_compress_type == 'none') @fputs($this->_file, $p_binary_data); else $this->_error('Unknown or missing compression type ('.$this->_compress_type.')'); } else { if ($this->_compress_type == 'gz') @gzputs($this->_file, $p_binary_data, $p_len); else if ($this->_compress_type == 'bz2') @bzwrite($this->_file, $p_binary_data, $p_len); else if ($this->_compress_type == 'none') @fputs($this->_file, $p_binary_data, $p_len); else $this->_error('Unknown or missing compression type ('.$this->_compress_type.')'); } } return true; } // }}} // {{{ _readBlock() function _readBlock($p_len=null) { $v_block = null; if (is_resource($this->_file)) { if ($p_len === null) $p_len = 512; if ($this->_compress_type == 'gz') $v_block = @gzread($this->_file, 512); else if ($this->_compress_type == 'bz2') $v_block = @bzread($this->_file, 512); else if ($this->_compress_type == 'none') $v_block = @fread($this->_file, 512); else $this->_error('Unknown or missing compression type ('.$this->_compress_type.')'); } return $v_block; } // }}} // {{{ _jumpBlock() function _jumpBlock($p_len=null) { if (is_resource($this->_file)) { if ($p_len === null) $p_len = 1; if ($this->_compress_type == 'gz') @gzseek($this->_file, @gztell($this->_file)+($p_len*512)); else if ($this->_compress_type == 'bz2') { // ----- Replace missing bztell() and bzseek() for ($i=0; $i<$p_len; $i++) $this->_readBlock(); } else if ($this->_compress_type == 'none') @fseek($this->_file, @ftell($this->_file)+($p_len*512)); else $this->_error('Unknown or missing compression type ('.$this->_compress_type.')'); } return true; } // }}} // {{{ _writeFooter() function _writeFooter() { if (is_resource($this->_file)) { // ----- Write the last 0 filled block for end of archive $v_binary_data = pack("a512", ''); $this->_writeBlock($v_binary_data); } return true; } // }}} // {{{ _addList() function _addList($p_list, $p_add_dir, $p_remove_dir) { $v_result=true; $v_header = array(); // ----- Remove potential windows directory separator $p_add_dir = $this->_translateWinPath($p_add_dir); $p_remove_dir = $this->_translateWinPath($p_remove_dir, false); if (!$this->_file) { $this->_error('Invalid file descriptor'); return false; } if (sizeof($p_list) == 0) return true; for ($j=0; ($j_tarname) continue; if ($v_filename == '') continue; if (!file_exists($v_filename)) { $this->_warning("File '$v_filename' does not exist"); continue; } // ----- Add the file or directory header if (!$this->_addFile($v_filename, $v_header, $p_add_dir, $p_remove_dir)) return false; if (@is_dir($v_filename)) { if (!($p_hdir = opendir($v_filename))) { $this->_warning("Directory '$v_filename' can not be read"); continue; } $p_hitem = readdir($p_hdir); // '.' directory $p_hitem = readdir($p_hdir); // '..' directory while (false !== ($p_hitem = readdir($p_hdir))) { if ($v_filename != ".") $p_temp_list[0] = $v_filename.'/'.$p_hitem; else $p_temp_list[0] = $p_hitem; $v_result = $this->_addList($p_temp_list, $p_add_dir, $p_remove_dir); } unset($p_temp_list); unset($p_hdir); unset($p_hitem); } } return $v_result; } // }}} // {{{ _addFile() function _addFile($p_filename, &$p_header, $p_add_dir, $p_remove_dir) { if (!$this->_file) { $this->_error('Invalid file descriptor'); return false; } if ($p_filename == '') { $this->_error('Invalid file name'); return false; } // ----- Calculate the stored filename $p_filename = $this->_translateWinPath($p_filename, false);; $v_stored_filename = $p_filename; if (strcmp($p_filename, $p_remove_dir) == 0) { return true; } if ($p_remove_dir != '') { if (substr($p_remove_dir, -1) != '/') $p_remove_dir .= '/'; if (substr($p_filename, 0, strlen($p_remove_dir)) == $p_remove_dir) $v_stored_filename = substr($p_filename, strlen($p_remove_dir)); } $v_stored_filename = $this->_translateWinPath($v_stored_filename); if ($p_add_dir != '') { if (substr($p_add_dir, -1) == '/') $v_stored_filename = $p_add_dir.$v_stored_filename; else $v_stored_filename = $p_add_dir.'/'.$v_stored_filename; } $v_stored_filename = $this->_pathReduction($v_stored_filename); if (is_file($p_filename)) { if (($v_file = @fopen($p_filename, "rb")) == 0) { $this->_warning("Unable to open file '$p_filename' in binary read mode"); return true; } if (!$this->_writeHeader($p_filename, $v_stored_filename)) return false; while (($v_buffer = fread($v_file, 512)) != '') { $v_binary_data = pack("a512", "$v_buffer"); $this->_writeBlock($v_binary_data); } fclose($v_file); } else { // ----- Only header for dir if (!$this->_writeHeader($p_filename, $v_stored_filename)) return false; } return true; } // }}} // {{{ _addString() function _addString($p_filename, $p_string) { if (!$this->_file) { $this->_error('Invalid file descriptor'); return false; } if ($p_filename == '') { $this->_error('Invalid file name'); return false; } // ----- Calculate the stored filename $p_filename = $this->_translateWinPath($p_filename, false);; if (!$this->_writeHeaderBlock($p_filename, strlen($p_string), 0, 0, "", 0, 0)) return false; $i=0; while (($v_buffer = substr($p_string, (($i++)*512), 512)) != '') { $v_binary_data = pack("a512", $v_buffer); $this->_writeBlock($v_binary_data); } return true; } // }}} // {{{ _writeHeader() function _writeHeader($p_filename, $p_stored_filename) { if ($p_stored_filename == '') $p_stored_filename = $p_filename; $v_reduce_filename = $this->_pathReduction($p_stored_filename); if (strlen($v_reduce_filename) > 99) { if (!$this->_writeLongHeader($v_reduce_filename)) return false; } $v_info = stat($p_filename); $v_uid = sprintf("%6s ", DecOct($v_info[4])); $v_gid = sprintf("%6s ", DecOct($v_info[5])); $v_perms = sprintf("%6s ", DecOct(fileperms($p_filename))); $v_mtime = sprintf("%11s", DecOct(filemtime($p_filename))); if (@is_dir($p_filename)) { $v_typeflag = "5"; $v_size = sprintf("%11s ", DecOct(0)); } else { $v_typeflag = ''; clearstatcache(); $v_size = sprintf("%11s ", DecOct(filesize($p_filename))); } $v_linkname = ''; $v_magic = ''; $v_version = ''; $v_uname = ''; $v_gname = ''; $v_devmajor = ''; $v_devminor = ''; $v_prefix = ''; $v_binary_data_first = pack("a100a8a8a8a12A12", $v_reduce_filename, $v_perms, $v_uid, $v_gid, $v_size, $v_mtime); $v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12", $v_typeflag, $v_linkname, $v_magic, $v_version, $v_uname, $v_gname, $v_devmajor, $v_devminor, $v_prefix, ''); // ----- Calculate the checksum $v_checksum = 0; // ..... First part of the header for ($i=0; $i<148; $i++) $v_checksum += ord(substr($v_binary_data_first,$i,1)); // ..... Ignore the checksum value and replace it by ' ' (space) for ($i=148; $i<156; $i++) $v_checksum += ord(' '); // ..... Last part of the header for ($i=156, $j=0; $i<512; $i++, $j++) $v_checksum += ord(substr($v_binary_data_last,$j,1)); // ----- Write the first 148 bytes of the header in the archive $this->_writeBlock($v_binary_data_first, 148); // ----- Write the calculated checksum $v_checksum = sprintf("%6s ", DecOct($v_checksum)); $v_binary_data = pack("a8", $v_checksum); $this->_writeBlock($v_binary_data, 8); // ----- Write the last 356 bytes of the header in the archive $this->_writeBlock($v_binary_data_last, 356); return true; } // }}} // {{{ _writeHeaderBlock() function _writeHeaderBlock($p_filename, $p_size, $p_mtime=0, $p_perms=0, $p_type='', $p_uid=0, $p_gid=0) { $p_filename = $this->_pathReduction($p_filename); if (strlen($p_filename) > 99) { if (!$this->_writeLongHeader($p_filename)) return false; } if ($p_type == "5") { $v_size = sprintf("%11s ", DecOct(0)); } else { $v_size = sprintf("%11s ", DecOct($p_size)); } $v_uid = sprintf("%6s ", DecOct($p_uid)); $v_gid = sprintf("%6s ", DecOct($p_gid)); $v_perms = sprintf("%6s ", DecOct($p_perms)); $v_mtime = sprintf("%11s", DecOct($p_mtime)); $v_linkname = ''; $v_magic = ''; $v_version = ''; $v_uname = ''; $v_gname = ''; $v_devmajor = ''; $v_devminor = ''; $v_prefix = ''; $v_binary_data_first = pack("a100a8a8a8a12A12", $p_filename, $v_perms, $v_uid, $v_gid, $v_size, $v_mtime); $v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12", $p_type, $v_linkname, $v_magic, $v_version, $v_uname, $v_gname, $v_devmajor, $v_devminor, $v_prefix, ''); // ----- Calculate the checksum $v_checksum = 0; // ..... First part of the header for ($i=0; $i<148; $i++) $v_checksum += ord(substr($v_binary_data_first,$i,1)); // ..... Ignore the checksum value and replace it by ' ' (space) for ($i=148; $i<156; $i++) $v_checksum += ord(' '); // ..... Last part of the header for ($i=156, $j=0; $i<512; $i++, $j++) $v_checksum += ord(substr($v_binary_data_last,$j,1)); // ----- Write the first 148 bytes of the header in the archive $this->_writeBlock($v_binary_data_first, 148); // ----- Write the calculated checksum $v_checksum = sprintf("%6s ", DecOct($v_checksum)); $v_binary_data = pack("a8", $v_checksum); $this->_writeBlock($v_binary_data, 8); // ----- Write the last 356 bytes of the header in the archive $this->_writeBlock($v_binary_data_last, 356); return true; } // }}} // {{{ _writeLongHeader() function _writeLongHeader($p_filename) { $v_size = sprintf("%11s ", DecOct(strlen($p_filename))); $v_typeflag = 'L'; $v_linkname = ''; $v_magic = ''; $v_version = ''; $v_uname = ''; $v_gname = ''; $v_devmajor = ''; $v_devminor = ''; $v_prefix = ''; $v_binary_data_first = pack("a100a8a8a8a12A12", '././@LongLink', 0, 0, 0, $v_size, 0); $v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12", $v_typeflag, $v_linkname, $v_magic, $v_version, $v_uname, $v_gname, $v_devmajor, $v_devminor, $v_prefix, ''); // ----- Calculate the checksum $v_checksum = 0; // ..... First part of the header for ($i=0; $i<148; $i++) $v_checksum += ord(substr($v_binary_data_first,$i,1)); // ..... Ignore the checksum value and replace it by ' ' (space) for ($i=148; $i<156; $i++) $v_checksum += ord(' '); // ..... Last part of the header for ($i=156, $j=0; $i<512; $i++, $j++) $v_checksum += ord(substr($v_binary_data_last,$j,1)); // ----- Write the first 148 bytes of the header in the archive $this->_writeBlock($v_binary_data_first, 148); // ----- Write the calculated checksum $v_checksum = sprintf("%6s ", DecOct($v_checksum)); $v_binary_data = pack("a8", $v_checksum); $this->_writeBlock($v_binary_data, 8); // ----- Write the last 356 bytes of the header in the archive $this->_writeBlock($v_binary_data_last, 356); // ----- Write the filename as content of the block $i=0; while (($v_buffer = substr($p_filename, (($i++)*512), 512)) != '') { $v_binary_data = pack("a512", "$v_buffer"); $this->_writeBlock($v_binary_data); } return true; } // }}} // {{{ _readHeader() function _readHeader($v_binary_data, &$v_header) { if (strlen($v_binary_data)==0) { $v_header['filename'] = ''; return true; } if (strlen($v_binary_data) != 512) { $v_header['filename'] = ''; $this->_error('Invalid block size : '.strlen($v_binary_data)); return false; } // ----- Calculate the checksum $v_checksum = 0; // ..... First part of the header for ($i=0; $i<148; $i++) $v_checksum+=ord(substr($v_binary_data,$i,1)); // ..... Ignore the checksum value and replace it by ' ' (space) for ($i=148; $i<156; $i++) $v_checksum += ord(' '); // ..... Last part of the header for ($i=156; $i<512; $i++) $v_checksum+=ord(substr($v_binary_data,$i,1)); $v_data = unpack("a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/a8checksum/a1typeflag/a100link/a6magic/a2version/a32uname/a32gname/a8devmajor/a8devminor", $v_binary_data); // ----- Extract the checksum $v_header['checksum'] = OctDec(trim($v_data['checksum'])); if ($v_header['checksum'] != $v_checksum) { $v_header['filename'] = ''; // ----- Look for last block (empty block) if (($v_checksum == 256) && ($v_header['checksum'] == 0)) return true; $this->_error('Invalid checksum for file "'.$v_data['filename'].'" : '.$v_checksum.' calculated, '.$v_header['checksum'].' expected'); return false; } // ----- Extract the properties $v_header['filename'] = trim($v_data['filename']); $v_header['mode'] = OctDec(trim($v_data['mode'])); $v_header['uid'] = OctDec(trim($v_data['uid'])); $v_header['gid'] = OctDec(trim($v_data['gid'])); $v_header['size'] = OctDec(trim($v_data['size'])); $v_header['mtime'] = OctDec(trim($v_data['mtime'])); if (($v_header['typeflag'] = $v_data['typeflag']) == "5") { $v_header['size'] = 0; } /* ----- All these fields are removed form the header because they do not carry interesting info $v_header[link] = trim($v_data[link]); $v_header[magic] = trim($v_data[magic]); $v_header[version] = trim($v_data[version]); $v_header[uname] = trim($v_data[uname]); $v_header[gname] = trim($v_data[gname]); $v_header[devmajor] = trim($v_data[devmajor]); $v_header[devminor] = trim($v_data[devminor]); */ return true; } // }}} // {{{ _readLongHeader() function _readLongHeader(&$v_header) { $v_filename = ''; $n = floor($v_header['size']/512); for ($i=0; $i<$n; $i++) { $v_content = $this->_readBlock(); $v_filename .= $v_content; } if (($v_header['size'] % 512) != 0) { $v_content = $this->_readBlock(); $v_filename .= $v_content; } // ----- Read the next header $v_binary_data = $this->_readBlock(); if (!$this->_readHeader($v_binary_data, $v_header)) return false; $v_header['filename'] = $v_filename; return true; } // }}} // {{{ _extractInString() /** * This method extract from the archive one file identified by $p_filename. * The return value is a string with the file content, or NULL on error. * @param string $p_filename The path of the file to extract in a string. * @return a string with the file content or NULL. * @access private */ function _extractInString($p_filename) { $v_result_str = ""; While (strlen($v_binary_data = $this->_readBlock()) != 0) { if (!$this->_readHeader($v_binary_data, $v_header)) return NULL; if ($v_header['filename'] == '') continue; // ----- Look for long filename if ($v_header['typeflag'] == 'L') { if (!$this->_readLongHeader($v_header)) return NULL; } if ($v_header['filename'] == $p_filename) { if ($v_header['typeflag'] == "5") { $this->_error('Unable to extract in string a directory entry {'.$v_header['filename'].'}'); return NULL; } else { $n = floor($v_header['size']/512); for ($i=0; $i<$n; $i++) { $v_result_str .= $this->_readBlock(); } if (($v_header['size'] % 512) != 0) { $v_content = $this->_readBlock(); $v_result_str .= substr($v_content, 0, ($v_header['size'] % 512)); } return $v_result_str; } } else { $this->_jumpBlock(ceil(($v_header['size']/512))); } } return NULL; } // }}} // {{{ _extractList() function _extractList($p_path, &$p_list_detail, $p_mode, $p_file_list, $p_remove_path) { $v_result=true; $v_nb = 0; $v_extract_all = true; $v_listing = false; $p_path = $this->_translateWinPath($p_path, false); if ($p_path == '' || (substr($p_path, 0, 1) != '/' && substr($p_path, 0, 3) != "../" && !strpos($p_path, ':'))) { $p_path = "./".$p_path; } $p_remove_path = $this->_translateWinPath($p_remove_path); // ----- Look for path to remove format (should end by /) if (($p_remove_path != '') && (substr($p_remove_path, -1) != '/')) $p_remove_path .= '/'; $p_remove_path_size = strlen($p_remove_path); switch ($p_mode) { case "complete" : $v_extract_all = TRUE; $v_listing = FALSE; break; case "partial" : $v_extract_all = FALSE; $v_listing = FALSE; break; case "list" : $v_extract_all = FALSE; $v_listing = TRUE; break; default : $this->_error('Invalid extract mode ('.$p_mode.')'); return false; } clearstatcache(); While (strlen($v_binary_data = $this->_readBlock()) != 0) { $v_extract_file = FALSE; $v_extraction_stopped = 0; if (!$this->_readHeader($v_binary_data, $v_header)) return false; if ($v_header['filename'] == '') continue; // ----- Look for long filename if ($v_header['typeflag'] == 'L') { if (!$this->_readLongHeader($v_header)) return false; } if ((!$v_extract_all) && (is_array($p_file_list))) { // ----- By default no unzip if the file is not found $v_extract_file = false; for ($i=0; $i strlen($p_file_list[$i])) && (substr($v_header['filename'], 0, strlen($p_file_list[$i])) == $p_file_list[$i])) { $v_extract_file = TRUE; break; } } // ----- It is a file, so compare the file names elseif ($p_file_list[$i] == $v_header['filename']) { $v_extract_file = TRUE; break; } } } else { $v_extract_file = TRUE; } // ----- Look if this file need to be extracted if (($v_extract_file) && (!$v_listing)) { if (($p_remove_path != '') && (substr($v_header['filename'], 0, $p_remove_path_size) == $p_remove_path)) $v_header['filename'] = substr($v_header['filename'], $p_remove_path_size); if (($p_path != './') && ($p_path != '/')) { while (substr($p_path, -1) == '/') $p_path = substr($p_path, 0, strlen($p_path)-1); if (substr($v_header['filename'], 0, 1) == '/') $v_header['filename'] = $p_path.$v_header['filename']; else $v_header['filename'] = $p_path.'/'.$v_header['filename']; } if (file_exists($v_header['filename'])) { if ((@is_dir($v_header['filename'])) && ($v_header['typeflag'] == '')) { $this->_error('File '.$v_header['filename'].' already exists as a directory'); return false; } if ((is_file($v_header['filename'])) && ($v_header['typeflag'] == "5")) { $this->_error('Directory '.$v_header['filename'].' already exists as a file'); return false; } if (!is_writeable($v_header['filename'])) { $this->_error('File '.$v_header['filename'].' already exists and is write protected'); return false; } if (filemtime($v_header['filename']) > $v_header['mtime']) { // To be completed : An error or silent no replace ? } } // ----- Check the directory availability and create it if necessary elseif (($v_result = $this->_dirCheck(($v_header['typeflag'] == "5"?$v_header['filename']:dirname($v_header['filename'])))) != 1) { $this->_error('Unable to create path for '.$v_header['filename']); return false; } if ($v_extract_file) { if ($v_header['typeflag'] == "5") { if (!@file_exists($v_header['filename'])) { if (!@mkdir($v_header['filename'], 0777)) { $this->_error('Unable to create directory {'.$v_header['filename'].'}'); return false; } } } else { if (($v_dest_file = @fopen($v_header['filename'], "wb")) == 0) { $this->_error('Error while opening {'.$v_header['filename'].'} in write binary mode'); return false; } else { $n = floor($v_header['size']/512); for ($i=0; $i<$n; $i++) { $v_content = $this->_readBlock(); fwrite($v_dest_file, $v_content, 512); } if (($v_header['size'] % 512) != 0) { $v_content = $this->_readBlock(); fwrite($v_dest_file, $v_content, ($v_header['size'] % 512)); } @fclose($v_dest_file); // ----- Change the file mode, mtime @touch($v_header['filename'], $v_header['mtime']); // To be completed chmod($v_header['filename'], 0644 ); } // ----- Check the file size clearstatcache(); if (filesize($v_header['filename']) != $v_header['size']) { $this->_error('Extracted file '.$v_header['filename'].' does not have the correct file size \''.filesize($v_filename).'\' ('.$v_header['size'].' expected). Archive may be corrupted.'); return false; } } } else { $this->_jumpBlock(ceil(($v_header['size']/512))); } } else { $this->_jumpBlock(ceil(($v_header['size']/512))); } /* TBC : Seems to be unused ... if ($this->_compress) $v_end_of_file = @gzeof($this->_file); else $v_end_of_file = @feof($this->_file); */ if ($v_listing || $v_extract_file || $v_extraction_stopped) { // ----- Log extracted files if (($v_file_dir = dirname($v_header['filename'])) == $v_header['filename']) $v_file_dir = ''; if ((substr($v_header['filename'], 0, 1) == '/') && ($v_file_dir == '')) $v_file_dir = '/'; $p_list_detail[$v_nb++] = $v_header; } } return true; } // }}} // {{{ _openAppend() function _openAppend() { if (filesize($this->_tarname) == 0) return $this->_openWrite(); if ($this->_compress) { $this->_close(); if (!@rename($this->_tarname, $this->_tarname.".tmp")) { $this->_error('Error while renaming \''.$this->_tarname.'\' to temporary file \''.$this->_tarname.'.tmp\''); return false; } if ($this->_compress_type == 'gz') $v_temp_tar = @gzopen($this->_tarname.".tmp", "rb"); elseif ($this->_compress_type == 'bz2') $v_temp_tar = @bzopen($this->_tarname.".tmp", "rb"); if ($v_temp_tar == 0) { $this->_error('Unable to open file \''.$this->_tarname.'.tmp\' in binary read mode'); @rename($this->_tarname.".tmp", $this->_tarname); return false; } if (!$this->_openWrite()) { @rename($this->_tarname.".tmp", $this->_tarname); return false; } if ($this->_compress_type == 'gz') { $v_buffer = @gzread($v_temp_tar, 512); // ----- Read the following blocks but not the last one if (!@gzeof($v_temp_tar)) { do{ $v_binary_data = pack("a512", $v_buffer); $this->_writeBlock($v_binary_data); $v_buffer = @gzread($v_temp_tar, 512); } while (!@gzeof($v_temp_tar)); } @gzclose($v_temp_tar); } elseif ($this->_compress_type == 'bz2') { $v_buffered_lines = array(); $v_buffered_lines[] = @bzread($v_temp_tar, 512); // ----- Read the following blocks but not the last one while (strlen($v_buffered_lines[] = @bzread($v_temp_tar, 512)) > 0) { $v_binary_data = pack("a512", array_shift($v_buffered_lines)); $this->_writeBlock($v_binary_data); } @bzclose($v_temp_tar); } if (!@unlink($this->_tarname.".tmp")) { $this->_error('Error while deleting temporary file \''.$this->_tarname.'.tmp\''); } } else { // ----- For not compressed tar, just add files before the last 512 bytes block if (!$this->_openReadWrite()) return false; clearstatcache(); $v_size = filesize($this->_tarname); fseek($this->_file, $v_size-512); } return true; } // }}} // {{{ _append() function _append($p_filelist, $p_add_dir='', $p_remove_dir='') { if (!$this->_openAppend()) return false; if ($this->_addList($p_filelist, $p_add_dir, $p_remove_dir)) $this->_writeFooter(); $this->_close(); return true; } // }}} // {{{ _dirCheck() /** * Check if a directory exists and create it (including parent * dirs) if not. * * @param string $p_dir directory to check * * @return bool TRUE if the directory exists or was created */ function _dirCheck($p_dir) { if ((@is_dir($p_dir)) || ($p_dir == '')) return true; $p_parent_dir = dirname($p_dir); if (($p_parent_dir != $p_dir) && ($p_parent_dir != '') && (!$this->_dirCheck($p_parent_dir))) return false; if (!@mkdir($p_dir, 0777)) { $this->_error("Unable to create directory '$p_dir'"); return false; } return true; } // }}} // {{{ _pathReduction() /** * Compress path by changing for example "/dir/foo/../bar" to "/dir/bar", and * remove double slashes. * * @param string $p_dir path to reduce * * @return string reduced path * * @access private * */ function _pathReduction($p_dir) { $v_result = ''; // ----- Look for not empty path if ($p_dir != '') { // ----- Explode path by directory names $v_list = explode('/', $p_dir); // ----- Study directories from last to first for ($i=sizeof($v_list)-1; $i>=0; $i--) { // ----- Look for current path if ($v_list[$i] == ".") { // ----- Ignore this directory // Should be the first $i=0, but no check is done } else if ($v_list[$i] == "..") { // ----- Ignore it and ignore the $i-1 $i--; } else if (($v_list[$i] == '') && ($i!=(sizeof($v_list)-1)) && ($i!=0)) { // ----- Ignore only the double '//' in path, // but not the first and last / } else { $v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?'/'.$v_result:''); } } } $v_result = strtr($v_result, '\\', '/'); return $v_result; } // }}} // {{{ _translateWinPath() function _translateWinPath($p_path, $p_remove_disk_letter=true) { if (OS_WINDOWS) { // ----- Look for potential disk letter if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) { $p_path = substr($p_path, $v_position+1); } // ----- Change potential windows directory separator if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) { $p_path = strtr($p_path, '\\', '/'); } } return $p_path; } // }}} } ?> administrator/components/com_virtuemart/admin.styles.css100644 0 0 1617 10547254314 21450 0ustar 0 0 #cpanel { text-align: center; vertical-align: middle; } #cpanel div.icon { margin: 3px; } #cpanel div.icon a { display: block; height: 93px !important; height: 95px; width: 108px !important; width: 110px; vertical-align: middle; text-decoration : none; border: 1px solid #DDD; padding: 2px 5px 1px 5px; } #cpanel div.icon a:link { color : #808080; } #cpanel div.icon a:hover { color : #333; background-color: #f1e8e6; border: 1px solid #c24733; padding: 3px 4px 0px 6px; } #cpanel div.icon a:active { color : #808080; } #cpanel div.icon a:visited { color : #808080; } #cpanel div.iconimage { padding-top: 13px; } .adminListHeader { height: 48px; background-repeat: no-repeat; text-align: left; font-size: 18px; font-weight: bold; padding-left: 80px; } .editable { background: #ffff33; cursor: pointer; }administrator/components/com_virtuemart/admin.virtuemart.php100644 0 0 16212 11263443355 22344 0ustar 0 0 $val ) { if( strstr( $key, 'amp;')) { $key = str_replace( 'amp;', '', $key ); $_REQUEST[$key] = $val; } } } else { $page = vmget( $_SESSION, 'last_page', 'store.index' ); } } $limit = $vm_mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit ); $limitstart = $vm_mainframe->getUserStateFromRequest( "view{$page}{$product_id}{$category_id}limitstart", 'limitstart', 0 ); if (defined('_DONT_VIEW_PAGE') && !isset($install_type) ) { echo "\n"; } // renew Page-Information if( $pagePermissionsOK ) { $my_page= explode ( '.', $page ); $modulename = $my_page[0]; $pagename = $my_page[1]; } if( !defined('_VM_TOOLBAR_LOADED') && $no_toolbar != 1 ) { if( $vmLayout == 'standard' && strstr($_SERVER['SCRIPT_NAME'], 'index3.php')) { echo ''; } else { include( ADMINPATH.'toolbar.php'); } } // Include the Stylesheet $vm_mainframe->addStyleSheet( VM_THEMEURL.'admin.styles.css' ); $vm_mainframe->addStyleSheet( VM_THEMEURL.'theme.css' ); $vm_mainframe->addScript( $mosConfig_live_site.'/components/'.VM_COMPONENT_NAME.'/js/functions.js' ); if( $no_menu != 1 && $vmLayout != 'extended' ) { echo ''; } if( $only_page != 1 && $vmLayout == 'extended') { vmCommonHTML::loadExtjs(); $vm_mainframe->addScript( $_SERVER['SCRIPT_NAME'].'?option='.$option.'&task=extlayout' ); $phpscript_url = str_replace( 'index2.php', 'index3.php', str_replace('index.php', 'index3.php', $_SERVER['SCRIPT_NAME'])); echo ''; } else { if( $vmLayout == 'extended' ) { echo '
'; if( $no_toolbar != 1 ) { $bar =& vmToolBar::getInstance('virtuemart'); $bar->render(); } echo '
'; } else { echo '
'; include(ADMINPATH.'header.php'); echo ''; } // Load PAGE if( !$pagePermissionsOK ) { $error = $VM_LANG->_('PHPSHOP_MOD_NO_AUTH'); include( PAGEPATH. ERRORPAGE .'.php'); return; } if(file_exists(PAGEPATH.$modulename.".".$pagename.".php")) { if( $only_page ) { if( @$_REQUEST['format'] == 'raw' ) while( @ob_end_clean()); if( $func ) echo vmCommonHTML::getSuccessIndicator( $ok, $vmDisplayLogger ); include( PAGEPATH.$modulename.".".$pagename.".php" ); if( @$_REQUEST['format'] == 'raw' ) { $vm_mainframe->close(true); } } else { include( PAGEPATH.$modulename.".".$pagename.".php" ); } } else { include( PAGEPATH.'store.index.php' ); } if( $vmLayout != 'extended' ) { echo '
' .$VMVERSION->PRODUCT.' '.$VMVERSION->RELEASE .' ('.$VM_LANG->_('VM_VERSIONCHECK_NOW').')
'; } if( DEBUG == '1' && $no_menu != 1 ) { // Load PAGE include( PAGEPATH."shop.debug.php" ); } if( $vmLayout == 'extended' ) { echo ''; if( stristr($page, '_list') && $page != 'product.file_list' ) { echo vmCommonHTML::scriptTag('', 'var listItemClicked = function(e){ // find the element that was clicked var a = e.getTarget("a"); try { if(a && !a.onclick && a.href.indexOf("javascript:") == -1 && a.href.indexOf("func=") == -1 ) { e.preventDefault(); parent.addSimplePanel( a.title != "" ? a.title : a.innerHTML, a.href ); } } catch(e) {} }; Ext.get("vmPage").mon("click", listItemClicked );'); } } else { echo '
'; } } // Render the script and style resources into the document head $vm_mainframe->close(); ?>administrator/components/com_virtuemart/cart.gif100644 0 0 13114 10333733604 17754 0ustar 0 0 GIF89abO"%!*%"''(1-*51."+3'.6'1:642:63=;::99 B>$5D&8J%>V8>F9CJ&B]6HV&Ec&Jk(Hi)Mt'Os)S|(Rv6RkJFDGGHQMKTQNFNSJRXTRRZVTZZZa^\GUdW^cYciZkwRj{fcbifdlkkhhiqnlspoutsyvu{{zyxwgqxeb_~}*V.X+\*Z/\-].^/\2^6Y.`,a*b.b-f,e,h=f4b/e,j,m+l+o+s.t5w*w+y7}:nDlStezJvVy9{FQWVlfxqx 57.JYeXSNkixwhykFQfw}₂śĔʜĔnjڄוاƵ»Εݛޝ׿¸̴ҽӻҽԬڇ! ,bO HSwӥE]]‹3jܨ) ```DqI&zRpYcɂ M! !ͧP1`F@c:psjUdPѻp!QV39z×o=yѣ(C r{@X ` &l=hBɛg7W{`AK,.ACAgopa{;iB@b ,TXlرrFR<3'!-SƿcDB(U $"*wC>3|I Ѝ?鰣:cb:먣N<2 #`Cn  `}Ϗgΐs)6P %"pB 0p!10 5p,QkPK!8 +H0 M5( oQGc10ma<*T,gœ1jH~6ڮp#A$cISS %Kش0+B9l^\`:0#\BuAGXB(]9  +圃ŀEآUB $0'` 'х e CebU?=B8H`J a/r{ 4xA$3an(`7p5[ !8C*tB5`sF9QbH?t4Bч;1 N`BQ7`aF0ݘ'qLXc '=I-T TB,*@zʸ[80ai ɜF Ol`lbS ̰Q#{7>adxFzx !l$A5`0E|bQL|b @pfs PQ#87)"}<uۀ6b@LcA5nc2J T <-(6@(5Avw20$'KUAm6 DdΨ%jFxz+ȕBK7X-N1b(P}ã Dl"Ӱ6Fm`ܸ'"5hj:)|a)3"v-1t=(÷*Utb4j7gth( Yv(,xIy@YЁؓ0'.?(QoO<(Ee@ R5K݄%Axm\Քu?ׅlX?Aj4X, nd#=Lj>=) 0 5ayp Px 8 ~J0 ip&wHDi׆PɜʗNp 0=@ʐ 8 zp QPS:0 :mK̨}HC zIZE0 Κ 050 P `u  B;۱l ";  P ӐZ0K8Pp`7г>[5(@9*`D`ڱL۴NP2p5p={8`B7  y 0y ! N t[u xz|۷p ijp{ !pe{Pxe͐ O`v뷞y k7x fpw gg ۷ `{; КP r@۽z+ $ 0 Kȋmpw\pӺ i \ $ ఻zx ֐!zpwjw CP ` ny o  J`yj o@wZG` G y \ P RE Ѐ g k on߀h0 @  l0~\{` V @xzL`yz)y E`М\ A iʻpEEpgl ʵz rPǯʂ`F|7e|G C0ɚh PN A ph  œv0 \n0ρ @̉5ոP\J@G wzՠ Ӱ _Nqoϰm@0˂˃pD̪`;` 6Pi J@laO ÆɘLo`l ,op 8E\` 0:P J  P pΥ Φ2 l vv, l  Ȁpiͪê_h_P|Op+ OҪ l } lF% `1 0 M}NAO͙N <о=˃0 P=uq٥ ~]Rpא i x piҐg  ")-n00<qm\ xj `ֆ NT@ ʕD JΛ Qyz K@S~h~-b t^<lnn|煻4QQ 0^~舞芾苾xy P~阞难и;administrator/components/com_virtuemart/classes/DebugUtil.php100644 0 0 3640 10745456471 22364 0ustar 0 0 administrator/components/com_virtuemart/classes/JSON.php100644 0 0 103777 10651454063 21314 0ustar 0 0 * @author Matt Knapp * @author Brett Stimmerman * @copyright 2005 Michal Migurski * @version CVS: $Id: JSON.php 887 2007-07-24 19:51:15Z soeren_nb $ * @license http://www.opensource.org/licenses/bsd-license.php * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198 */ /** * Marker constant for Services_JSON::decode(), used to flag stack state */ define('SERVICES_JSON_SLICE', 1); /** * Marker constant for Services_JSON::decode(), used to flag stack state */ define('SERVICES_JSON_IN_STR', 2); /** * Marker constant for Services_JSON::decode(), used to flag stack state */ define('SERVICES_JSON_IN_ARR', 3); /** * Marker constant for Services_JSON::decode(), used to flag stack state */ define('SERVICES_JSON_IN_OBJ', 4); /** * Marker constant for Services_JSON::decode(), used to flag stack state */ define('SERVICES_JSON_IN_CMT', 5); /** * Behavior switch for Services_JSON::decode() */ define('SERVICES_JSON_LOOSE_TYPE', 16); /** * Behavior switch for Services_JSON::decode() */ define('SERVICES_JSON_SUPPRESS_ERRORS', 32); /** * Converts to and from JSON format. * * Brief example of use: * * * // create a new instance of Services_JSON * $json = new Services_JSON(); * * // convert a complexe value to JSON notation, and send it to the browser * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4))); * $output = $json->encode($value); * * print($output); * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]] * * // accept incoming POST data, assumed to be in JSON notation * $input = file_get_contents('php://input', 1000000); * $value = $json->decode($input); * */ class Services_JSON { /** * constructs a new JSON instance * * @param int $use object behavior flags; combine with boolean-OR * * possible values: * - SERVICES_JSON_LOOSE_TYPE: loose typing. * "{...}" syntax creates associative arrays * instead of objects in decode(). * - SERVICES_JSON_SUPPRESS_ERRORS: error suppression. * Values which can't be encoded (e.g. resources) * appear as NULL instead of throwing errors. * By default, a deeply-nested resource will * bubble up with an error, so all return values * from encode() should be checked with isError() */ function Services_JSON($use = 0) { $this->use = $use; } /** * convert a string from one UTF-16 char to one UTF-8 char * * Normally should be handled by mb_convert_encoding, but * provides a slower PHP-only method for installations * that lack the multibye string extension. * * @param string $utf16 UTF-16 character * @return string UTF-8 character * @access private */ function utf162utf8($utf16) { // oh please oh please oh please oh please oh please if(function_exists('mb_convert_encoding')) { return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16'); } $bytes = (ord($utf16{0}) << 8) | ord($utf16{1}); switch(true) { case ((0x7F & $bytes) == $bytes): // this case should never be reached, because we are in ASCII range // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0x7F & $bytes); case (0x07FF & $bytes) == $bytes: // return a 2-byte UTF-8 character // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0xC0 | (($bytes >> 6) & 0x1F)) . chr(0x80 | ($bytes & 0x3F)); case (0xFFFF & $bytes) == $bytes: // return a 3-byte UTF-8 character // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0xE0 | (($bytes >> 12) & 0x0F)) . chr(0x80 | (($bytes >> 6) & 0x3F)) . chr(0x80 | ($bytes & 0x3F)); } // ignoring UTF-32 for now, sorry return ''; } /** * convert a string from one UTF-8 char to one UTF-16 char * * Normally should be handled by mb_convert_encoding, but * provides a slower PHP-only method for installations * that lack the multibye string extension. * * @param string $utf8 UTF-8 character * @return string UTF-16 character * @access private */ function utf82utf16($utf8) { // oh please oh please oh please oh please oh please if(function_exists('mb_convert_encoding')) { return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8'); } switch(strlen($utf8)) { case 1: // this case should never be reached, because we are in ASCII range // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return $utf8; case 2: // return a UTF-16 character from a 2-byte UTF-8 char // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0x07 & (ord($utf8{0}) >> 2)) . chr((0xC0 & (ord($utf8{0}) << 6)) | (0x3F & ord($utf8{1}))); case 3: // return a UTF-16 character from a 3-byte UTF-8 char // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr((0xF0 & (ord($utf8{0}) << 4)) | (0x0F & (ord($utf8{1}) >> 2))) . chr((0xC0 & (ord($utf8{1}) << 6)) | (0x7F & ord($utf8{2}))); } // ignoring UTF-32 for now, sorry return ''; } /** * encodes an arbitrary variable into JSON format * * @param mixed $var any number, boolean, string, array, or object to be encoded. * see argument 1 to Services_JSON() above for array-parsing behavior. * if var is a strng, note that encode() always expects it * to be in ASCII or UTF-8 format! * * @return mixed JSON string representation of input var or an error if a problem occurs * @access public */ function encode($var) { switch (gettype($var)) { case 'boolean': return $var ? 'true' : 'false'; case 'NULL': return 'null'; case 'integer': return (int) $var; case 'double': case 'float': return (float) $var; case 'string': // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT $ascii = ''; $strlen_var = strlen($var); /* * Iterate over every character in the string, * escaping with a slash or encoding to UTF-8 where necessary */ for ($c = 0; $c < $strlen_var; ++$c) { $ord_var_c = ord($var{$c}); switch (true) { case $ord_var_c == 0x08: $ascii .= '\b'; break; case $ord_var_c == 0x09: $ascii .= '\t'; break; case $ord_var_c == 0x0A: $ascii .= '\n'; break; case $ord_var_c == 0x0C: $ascii .= '\f'; break; case $ord_var_c == 0x0D: $ascii .= '\r'; break; case $ord_var_c == 0x22: case $ord_var_c == 0x2F: case $ord_var_c == 0x5C: // double quote, slash, slosh $ascii .= '\\'.$var{$c}; break; case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)): // characters U-00000000 - U-0000007F (same as ASCII) $ascii .= $var{$c}; break; case (($ord_var_c & 0xE0) == 0xC0): // characters U-00000080 - U-000007FF, mask 110XXXXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c + 1})); $c += 1; $utf16 = $this->utf82utf16($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; case (($ord_var_c & 0xF0) == 0xE0): // characters U-00000800 - U-0000FFFF, mask 1110XXXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c + 1}), ord($var{$c + 2})); $c += 2; $utf16 = $this->utf82utf16($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; case (($ord_var_c & 0xF8) == 0xF0): // characters U-00010000 - U-001FFFFF, mask 11110XXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c + 1}), ord($var{$c + 2}), ord($var{$c + 3})); $c += 3; $utf16 = $this->utf82utf16($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; case (($ord_var_c & 0xFC) == 0xF8): // characters U-00200000 - U-03FFFFFF, mask 111110XX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c + 1}), ord($var{$c + 2}), ord($var{$c + 3}), ord($var{$c + 4})); $c += 4; $utf16 = $this->utf82utf16($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; case (($ord_var_c & 0xFE) == 0xFC): // characters U-04000000 - U-7FFFFFFF, mask 1111110X // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c + 1}), ord($var{$c + 2}), ord($var{$c + 3}), ord($var{$c + 4}), ord($var{$c + 5})); $c += 5; $utf16 = $this->utf82utf16($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; } } return '"'.$ascii.'"'; case 'array': /* * As per JSON spec if any array key is not an integer * we must treat the the whole array as an object. We * also try to catch a sparsely populated associative * array with numeric keys here because some JS engines * will create an array with empty indexes up to * max_index which can cause memory issues and because * the keys, which may be relevant, will be remapped * otherwise. * * As per the ECMA and JSON specification an object may * have any string as a property. Unfortunately due to * a hole in the ECMA specification if the key is a * ECMA reserved word or starts with a digit the * parameter is only accessible using ECMAScript's * bracket notation. */ // treat as a JSON object if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) { $properties = array_map(array($this, 'name_value'), array_keys($var), array_values($var)); foreach($properties as $property) { if(Services_JSON::isError($property)) { return $property; } } return '{' . join(',', $properties) . '}'; } // treat it like a regular array $elements = array_map(array($this, 'encode'), $var); foreach($elements as $element) { if(Services_JSON::isError($element)) { return $element; } } return '[' . join(',', $elements) . ']'; case 'object': $vars = get_object_vars($var); $properties = array_map(array($this, 'name_value'), array_keys($vars), array_values($vars)); foreach($properties as $property) { if(Services_JSON::isError($property)) { return $property; } } return '{' . join(',', $properties) . '}'; default: return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS) ? 'null' : new Services_JSON_Error(gettype($var)." can not be encoded as JSON string"); } } /** * array-walking function for use in generating JSON-formatted name-value pairs * * @param string $name name of key to use * @param mixed $value reference to an array element to be encoded * * @return string JSON-formatted name-value pair, like '"name":value' * @access private */ function name_value($name, $value) { $encoded_value = $this->encode($value); if(Services_JSON::isError($encoded_value)) { return $encoded_value; } return $this->encode(strval($name)) . ':' . $encoded_value; } /** * reduce a string by removing leading and trailing comments and whitespace * * @param $str string string value to strip of comments and whitespace * * @return string string value stripped of comments and whitespace * @access private */ function reduce_string($str) { $str = preg_replace(array( // eliminate single line comments in '// ...' form '#^\s*//(.+)$#m', // eliminate multi-line comments in '/* ... */' form, at start of string '#^\s*/\*(.+)\*/#Us', // eliminate multi-line comments in '/* ... */' form, at end of string '#/\*(.+)\*/\s*$#Us' ), '', $str); // eliminate extraneous space return trim($str); } /** * decodes a JSON string into appropriate variable * * @param string $str JSON-formatted string * * @return mixed number, boolean, string, array, or object * corresponding to given JSON input string. * See argument 1 to Services_JSON() above for object-output behavior. * Note that decode() always returns strings * in ASCII or UTF-8 format! * @access public */ function decode($str) { $str = $this->reduce_string($str); switch (strtolower($str)) { case 'true': return true; case 'false': return false; case 'null': return null; default: $m = array(); if (is_numeric($str)) { // Lookie-loo, it's a number // This would work on its own, but I'm trying to be // good about returning integers where appropriate: // return (float)$str; // Return float or int, as appropriate return ((float)$str == (integer)$str) ? (integer)$str : (float)$str; } elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) { // STRINGS RETURNED IN UTF-8 FORMAT $delim = substr($str, 0, 1); $chrs = substr($str, 1, -1); $utf8 = ''; $strlen_chrs = strlen($chrs); for ($c = 0; $c < $strlen_chrs; ++$c) { $substr_chrs_c_2 = substr($chrs, $c, 2); $ord_chrs_c = ord($chrs{$c}); switch (true) { case $substr_chrs_c_2 == '\b': $utf8 .= chr(0x08); ++$c; break; case $substr_chrs_c_2 == '\t': $utf8 .= chr(0x09); ++$c; break; case $substr_chrs_c_2 == '\n': $utf8 .= chr(0x0A); ++$c; break; case $substr_chrs_c_2 == '\f': $utf8 .= chr(0x0C); ++$c; break; case $substr_chrs_c_2 == '\r': $utf8 .= chr(0x0D); ++$c; break; case $substr_chrs_c_2 == '\\"': case $substr_chrs_c_2 == '\\\'': case $substr_chrs_c_2 == '\\\\': case $substr_chrs_c_2 == '\\/': if (($delim == '"' && $substr_chrs_c_2 != '\\\'') || ($delim == "'" && $substr_chrs_c_2 != '\\"')) { $utf8 .= $chrs{++$c}; } break; case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)): // single, escaped unicode character $utf16 = chr(hexdec(substr($chrs, ($c + 2), 2))) . chr(hexdec(substr($chrs, ($c + 4), 2))); $utf8 .= $this->utf162utf8($utf16); $c += 5; break; case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F): $utf8 .= $chrs{$c}; break; case ($ord_chrs_c & 0xE0) == 0xC0: // characters U-00000080 - U-000007FF, mask 110XXXXX //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= substr($chrs, $c, 2); ++$c; break; case ($ord_chrs_c & 0xF0) == 0xE0: // characters U-00000800 - U-0000FFFF, mask 1110XXXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= substr($chrs, $c, 3); $c += 2; break; case ($ord_chrs_c & 0xF8) == 0xF0: // characters U-00010000 - U-001FFFFF, mask 11110XXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= substr($chrs, $c, 4); $c += 3; break; case ($ord_chrs_c & 0xFC) == 0xF8: // characters U-00200000 - U-03FFFFFF, mask 111110XX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= substr($chrs, $c, 5); $c += 4; break; case ($ord_chrs_c & 0xFE) == 0xFC: // characters U-04000000 - U-7FFFFFFF, mask 1111110X // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= substr($chrs, $c, 6); $c += 5; break; } } return $utf8; } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) { // array, or object notation if ($str{0} == '[') { $stk = array(SERVICES_JSON_IN_ARR); $arr = array(); } else { if ($this->use & SERVICES_JSON_LOOSE_TYPE) { $stk = array(SERVICES_JSON_IN_OBJ); $obj = array(); } else { $stk = array(SERVICES_JSON_IN_OBJ); $obj = new stdClass(); } } array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => 0, 'delim' => false)); $chrs = substr($str, 1, -1); $chrs = $this->reduce_string($chrs); if ($chrs == '') { if (reset($stk) == SERVICES_JSON_IN_ARR) { return $arr; } else { return $obj; } } //print("\nparsing {$chrs}\n"); $strlen_chrs = strlen($chrs); for ($c = 0; $c <= $strlen_chrs; ++$c) { $top = end($stk); $substr_chrs_c_2 = substr($chrs, $c, 2); if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) { // found a comma that is not inside a string, array, etc., // OR we've reached the end of the character list $slice = substr($chrs, $top['where'], ($c - $top['where'])); array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false)); //print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); if (reset($stk) == SERVICES_JSON_IN_ARR) { // we are in an array, so just push an element onto the stack array_push($arr, $this->decode($slice)); } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { // we are in an object, so figure // out the property name and set an // element in an associative array, // for now $parts = array(); if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { // "name":value pair $key = $this->decode($parts[1]); $val = $this->decode($parts[2]); if ($this->use & SERVICES_JSON_LOOSE_TYPE) { $obj[$key] = $val; } else { $obj->$key = $val; } } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { // name:value pair, where name is unquoted $key = $parts[1]; $val = $this->decode($parts[2]); if ($this->use & SERVICES_JSON_LOOSE_TYPE) { $obj[$key] = $val; } else { $obj->$key = $val; } } } } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) { // found a quote, and we are not inside a string array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c})); //print("Found start of string at {$c}\n"); } elseif (($chrs{$c} == $top['delim']) && ($top['what'] == SERVICES_JSON_IN_STR) && ((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) { // found a quote, we're in a string, and it's not escaped // we know that it's not escaped becase there is _not_ an // odd number of backslashes at the end of the string so far array_pop($stk); //print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n"); } elseif (($chrs{$c} == '[') && in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { // found a left-bracket, and we are in an array, object, or slice array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false)); //print("Found start of array at {$c}\n"); } elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) { // found a right-bracket, and we're in an array array_pop($stk); //print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); } elseif (($chrs{$c} == '{') && in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { // found a left-brace, and we are in an array, object, or slice array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false)); //print("Found start of object at {$c}\n"); } elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) { // found a right-brace, and we're in an object array_pop($stk); //print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); } elseif (($substr_chrs_c_2 == '/*') && in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { // found a comment start, and we are in an array, object, or slice array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false)); $c++; //print("Found start of comment at {$c}\n"); } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) { // found a comment end, and we're in one now array_pop($stk); $c++; for ($i = $top['where']; $i <= $c; ++$i) $chrs = substr_replace($chrs, ' ', $i, 1); //print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); } } if (reset($stk) == SERVICES_JSON_IN_ARR) { return $arr; } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { return $obj; } } } } /** * @todo Ultimately, this should just call PEAR::isError() */ function isError($data, $code = null) { if (class_exists('pear')) { return PEAR::isError($data, $code); } elseif (is_object($data) && (get_class($data) == 'services_json_error' || is_subclass_of($data, 'services_json_error'))) { return true; } return false; } } if (class_exists('PEAR_Error')) { class Services_JSON_Error extends PEAR_Error { function Services_JSON_Error($message = 'unknown error', $code = null, $mode = null, $options = null, $userinfo = null) { parent::PEAR_Error($message, $code, $mode, $options, $userinfo); } } } else { /** * @todo Ultimately, this class shall be descended from PEAR_Error */ class Services_JSON_Error { function Services_JSON_Error($message = 'unknown error', $code = null, $mode = null, $options = null, $userinfo = null) { } } } ?> administrator/components/com_virtuemart/classes/Log/Log.php100644 0 0 63672 10774215017 21764 0ustar 0 0 * @author Jon Parise * @since Horde 1.3 * @package Log */ class vmLog { /** * Indicates whether or not the log can been opened / connected. * * @var boolean * @access private */ var $_opened = false; /** * Instance-specific unique identification number. * * @var integer * @access private */ var $_id = 0; /** * The label that uniquely identifies this set of log messages. * * @var string * @access private */ var $_ident = ''; /** * The default priority to use when logging an event. * * @var integer * @access private */ var $_priority = PEAR_LOG_INFO; /** * The bitmask of allowed log levels. * @var integer * @access private */ var $_mask = PEAR_LOG_ALL; /** * Holds all Log_observer objects that wish to be notified of new messages. * * @var array * @access private */ var $_listeners = array(); /** * Counts all log messages * * @var int * @access private */ var $_ticker = 0; /** * Attempts to return a concrete Log instance of type $handler. * * @param string $handler The type of concrete Log subclass to return. * Attempt to dynamically include the code for * this subclass. Currently, valid values are * 'console', 'syslog', 'sql', 'file', and 'mcal'. * * @param string $name The name of the actually log file, table, or * other specific store to use. Defaults to an * empty string, with which the subclass will * attempt to do something intelligent. * * @param string $ident The identity reported to the log system. * * @param array $conf A hash containing any additional configuration * information that a subclass might need. * * @param int $level Log messages up to and including this level. * * @return Log Log The newly created concrete Log instance, or an * false on an error. * @access public * @since Log 1.0 */ function &factory($handler, $name = '', $ident = '', $conf = array(), $level = PEAR_LOG_DEBUG) { $obj = false; $handler = strtolower($handler); $class = 'vmLog_' . $handler; $classfile = CLASSPATH.'Log/' . $handler . '.php'; /* * Attempt to include our version of the named class, but don't treat * a failure as fatal. The caller may have already included their own * version of the named class. */ if (!class_exists($class)) { @include_once $classfile; } /* If the class exists, return a new instance of it. */ if (class_exists($class)) { $obj = new $class($name, $ident, $conf, $level); return $obj; } return $obj; } /** * Attempts to return a reference to a concrete Log instance of type * $handler, only creating a new instance if no log instance with the same * parameters currently exists. * * You should use this if there are multiple places you might create a * logger, you don't want to create multiple loggers, and you don't want to * check for the existance of one each time. The singleton pattern does all * the checking work for you. * * You MUST call this method with the $var = &Log::singleton() syntax. * Without the ampersand (&) in front of the method name, you will not get * a reference, you will get a copy. * * @param string $handler The type of concrete Log subclass to return. * Attempt to dynamically include the code for * this subclass. Currently, valid values are * 'console', 'syslog', 'sql', 'file', and 'mcal'. * * @param string $name The name of the actually log file, table, or * other specific store to use. Defaults to an * empty string, with which the subclass will * attempt to do something intelligent. * * @param string $ident The identity reported to the log system. * * @param array $conf A hash containing any additional configuration * information that a subclass might need. * * @param int $level Log messages up to and including this level. * * @return object Log The newly created concrete Log instance, or an * false on an error. * @access public * @since Log 1.0 */ function &singleton($handler, $name = '', $ident = '', $conf = array(), $level = PEAR_LOG_DEBUG) { static $instances; if (!isset($instances)) $instances = array(); $signature = serialize(array($handler, $name, $ident, $conf, $level)); if (!isset($instances[$signature])) { $instances[$signature] = &vmLog::factory($handler, $name, $ident, $conf, $level); } return $instances[$signature]; } /** * Abstract implementation of the open() method. * @since Log 1.0 */ function open() { return false; } /** * Abstract implementation of the close() method. * @since Log 1.0 */ function close() { return false; } /** * Abstract implementation of the flush() method. * @since Log 1.8.2 */ function flush() { return false; } /** * Abstract implementation of the log() method. * @since Log 1.0 */ function log($message, $priority = null) { return false; } /** * A convenience function for logging a emergency event. It will log a * message at the PEAR_LOG_EMERG log level. * * @param mixed $message String or object containing the message * to log. * * @return boolean True if the message was successfully logged. * * @access public * @since Log 1.7.0 */ function emerg($message) { return $this->log($message, PEAR_LOG_EMERG); } /** * A convenience function for logging an alert event. It will log a * message at the PEAR_LOG_ALERT log level. * * @param mixed $message String or object containing the message * to log. * * @return boolean True if the message was successfully logged. * * @access public * @since Log 1.7.0 */ function alert($message) { return $this->log($message, PEAR_LOG_ALERT); } /** * A convenience function for logging a critical event. It will log a * message at the PEAR_LOG_CRIT log level. * * @param mixed $message String or object containing the message * to log. * * @return boolean True if the message was successfully logged. * * @access public * @since Log 1.7.0 */ function crit($message) { return $this->log($message, PEAR_LOG_CRIT); } /** * A convenience function for logging a error event. It will log a * message at the PEAR_LOG_ERR log level. * * @param mixed $message String or object containing the message * to log. * * @return boolean True if the message was successfully logged. * * @access public * @since Log 1.7.0 */ function err($message) { return $this->log($message, PEAR_LOG_ERR); } /** * A convenience function for logging a warning event. It will log a * message at the PEAR_LOG_WARNING log level. * * @param mixed $message String or object containing the message * to log. * * @return boolean True if the message was successfully logged. * * @access public * @since Log 1.7.0 */ function warning($message) { return $this->log($message, PEAR_LOG_WARNING); } /** * A convenience function for logging a notice event. It will log a * message at the PEAR_LOG_NOTICE log level. * * @param mixed $message String or object containing the message * to log. * * @return boolean True if the message was successfully logged. * * @access public * @since Log 1.7.0 */ function notice($message) { return $this->log($message, PEAR_LOG_NOTICE); } /** * A convenience function for logging a information event. It will log a * message at the PEAR_LOG_INFO log level. * * @param mixed $message String or object containing the message * to log. * * @return boolean True if the message was successfully logged. * * @access public * @since Log 1.7.0 */ function info($message) { return $this->log($message, PEAR_LOG_INFO); } /** * A convenience function for logging a debug event. It will log a * message at the PEAR_LOG_DEBUG log level. * * @param mixed $message String or object containing the message * to log. * * @return boolean True if the message was successfully logged. * * @access public * @since Log 1.7.0 */ function debug($message) { return $this->log($message, PEAR_LOG_DEBUG); } /** * A convenience function for logging an advice event. It will log a * message at the PEAR_LOG_TIP log level. * * @param mixed $message String or object containing the message * to log. * * @return boolean True if the message was successfully logged. * @author soeren * @access public * @since Log 1.9.0 */ function tip($message) { return $this->log($message, PEAR_LOG_TIP); } /** * Returns the string representation of the message data. * * If $message is an object, _extractMessage() will attempt to extract * the message text using a known method (such as a PEAR_Error object's * getMessage() method). If a known method, cannot be found, the * serialized representation of the object will be returned. * * If the message data is already a string, it will be returned unchanged. * * @param mixed $message The original message data. This may be a * string or any object. * * @return string The string representation of the message. * * @access private */ function _extractMessage($message) { /* * If we've been given an object, attempt to extract the message using * a known method. If we can't find such a method, default to the * "human-readable" version of the object. * * We also use the human-readable format for arrays. */ if (is_object($message)) { if (method_exists($message, 'getmessage')) { $message = $message->getMessage(); } else if (method_exists($message, 'tostring')) { $message = $message->toString(); } else if (method_exists($message, '__tostring')) { if (version_compare(PHP_VERSION, '5.0.0', 'ge')) { $message = (string)$message; } else { $message = $message->__toString(); } } else { $message = print_r($message, true); } } else if (is_array($message)) { if (isset($message['message'])) { $message = $message['message']; } else { $message = print_r($message, true); } } /* Otherwise, we assume the message is a string. */ return $message; } /** * Returns the string representation of a PEAR_LOG_* integer constant. * * @param int $priority A PEAR_LOG_* integer constant. * * @return string The string representation of $level. * * @since Log 1.0 */ function priorityToString($priority) { global $VM_LANG; $levels = array( PEAR_LOG_EMERG => $VM_LANG->_('PEAR_LOG_EMERG'), PEAR_LOG_ALERT => $VM_LANG->_('PEAR_LOG_ALERT'), PEAR_LOG_CRIT => $VM_LANG->_('PEAR_LOG_CRIT'), PEAR_LOG_ERR => $VM_LANG->_('PEAR_LOG_ERR'), PEAR_LOG_WARNING => $VM_LANG->_('PEAR_LOG_WARNING'), PEAR_LOG_NOTICE => $VM_LANG->_('PEAR_LOG_NOTICE'), PEAR_LOG_INFO => $VM_LANG->_('PEAR_LOG_INFO'), PEAR_LOG_DEBUG => $VM_LANG->_('PEAR_LOG_DEBUG'), PEAR_LOG_TIP => $VM_LANG->_('PEAR_LOG_TIP') ); return $levels[$priority]; } /** * Returns the the PEAR_LOG_* integer constant for the given string * representation of a priority name. This function performs a * case-insensitive search. * * @param string $name String containing a priority name. * * @return string The PEAR_LOG_* integer contstant corresponding * the the specified priority name. * * @since Log 1.9.0 */ function stringToPriority($name) { global $VM_LANG; $levels = array( $VM_LANG->_('PEAR_LOG_EMERG') => PEAR_LOG_EMERG, $VM_LANG->_('PEAR_LOG_ALERT') => PEAR_LOG_ALERT, $VM_LANG->_('PEAR_LOG_CRIT') => PEAR_LOG_CRIT, $VM_LANG->_('PEAR_LOG_ERR') => PEAR_LOG_ERR, $VM_LANG->_('PEAR_LOG_WARNING') => PEAR_LOG_WARNING, $VM_LANG->_('PEAR_LOG_NOTICE') => PEAR_LOG_NOTICE, $VM_LANG->_('PEAR_LOG_INFO') => PEAR_LOG_INFO, $VM_LANG->_('PEAR_LOG_DEBUG') => PEAR_LOG_DEBUG, $VM_LANG->_('PEAR_LOG_TIP') => PEAR_LOG_TIP ); return $levels[strtolower($name)]; } /* @MWM: There was a typo in at least common/english.php for PEAR_LOG_TIP. Note that correct text is needed to ensure proper conversion from number to text (and vice-versa). For this and other reasons, I'm creating the conversion functions below and use names based on the __same name as the actual constant__ for file logging. In general, I don't think that the logging level should be subject to translation errors. Moreover, the log messages themselves are in English, so it seems pointless to translate just the logging level. */ /** * Convert a priorty name to a priority number. * Name is based on actual priority name. * * @param string $name String containing a priority name. * @return string The PEAR_LOG_* integer contstant corresponding * to the specified priority name. */ function stringToPriorityPEAR($name) { global $VM_LANG; $levels = array( 'PEAR_LOG_EMERG' => PEAR_LOG_EMERG, 'PEAR_LOG_ALERT' => PEAR_LOG_ALERT, 'PEAR_LOG_CRIT' => PEAR_LOG_CRIT, 'PEAR_LOG_ERR' => PEAR_LOG_ERR, 'PEAR_LOG_WARNING' => PEAR_LOG_WARNING, 'PEAR_LOG_NOTICE' => PEAR_LOG_NOTICE, 'PEAR_LOG_INFO' => PEAR_LOG_INFO, 'PEAR_LOG_DEBUG' => PEAR_LOG_DEBUG, 'PEAR_LOG_TIP' => PEAR_LOG_TIP ); return $levels[$name]; } /** * Returns the string representation of a PEAR_LOG_* integer constant. * Name is based on actual priority name. * * @param int $priority A PEAR_LOG_* integer constant. * * @return string The string representation of $priority. * */ function priorityToStringPEAR($priority) { global $VM_LANG; $levels = array( PEAR_LOG_EMERG => 'PEAR_LOG_EMERG', PEAR_LOG_ALERT => 'PEAR_LOG_ALERT', PEAR_LOG_CRIT => 'PEAR_LOG_CRIT', PEAR_LOG_ERR => 'PEAR_LOG_ERR', PEAR_LOG_WARNING => 'PEAR_LOG_WARNING', PEAR_LOG_NOTICE => 'PEAR_LOG_NOTICE', PEAR_LOG_INFO => 'PEAR_LOG_INFO', PEAR_LOG_DEBUG => 'PEAR_LOG_DEBUG', PEAR_LOG_TIP => 'PEAR_LOG_TIP' ); return $levels[$priority]; } /** * Returns the string representation of a PEAR_LOG_* integer constant. * Name is a shortened version of the actual priority name. * * @param int $priority A PEAR_LOG_* integer constant. * * @return string The string representation of $priority. * */ function priorityToShortStringPEAR($priority) { global $VM_LANG; $levels = array( PEAR_LOG_EMERG => 'EMERG', PEAR_LOG_ALERT => 'ALERT', PEAR_LOG_CRIT => 'CRIT', PEAR_LOG_ERR => 'ERR', PEAR_LOG_WARNING => 'WARNING', PEAR_LOG_NOTICE => 'NOTICE', PEAR_LOG_INFO => 'INFO', PEAR_LOG_DEBUG => 'DEBUG', PEAR_LOG_TIP => 'TIP' ); return $levels[$priority]; } /** * Convert a short priorty name to a priority number. * Name is based on actual priority name. * * @param string $name String containing a priority name. * @return string The PEAR_LOG_* integer contstant corresponding * to the specified priority name. */ function shortStringToPriorityPEAR($name) { global $VM_LANG; $levels = array( 'EMERG' => PEAR_LOG_EMERG, 'ALERT' => PEAR_LOG_ALERT, 'CRIT' => PEAR_LOG_CRIT, 'ERR' => PEAR_LOG_ERR, 'WARNING' => PEAR_LOG_WARNING, 'NOTICE' => PEAR_LOG_NOTICE, 'INFO' => PEAR_LOG_INFO, 'DEBUG' => PEAR_LOG_DEBUG, 'TIP' => PEAR_LOG_TIP ); return $levels[$name]; } /** * Calculate the log mask for the given priority. * * @param integer $priority The priority whose mask will be calculated. * * @return integer The calculated log mask. * * @access public * @since Log 1.7.0 */ function MASK($priority) { return (1 << $priority); } /** * Calculate the log mask for all priorities up to the given priority. * * @param integer $priority The maximum priority covered by this mask. * * @return integer The calculated log mask. * * @access public * @since Log 1.7.0 */ function UPTO($priority) { return ((1 << ($priority + 1)) - 1); } /** * Set and return the level mask for the current Log instance. * * @param integer $mask A bitwise mask of log levels. * * @return integer The current level mask. * * @access public * @since Log 1.7.0 */ function setMask($mask) { $this->_mask = $mask; return $this->_mask; } /** * Returns the current level mask. * * @return interger The current level mask. * * @access public * @since Log 1.7.0 */ function getMask() { return $this->_mask; } /** * Check if the given priority is included in the current level mask. * * @param integer $priority The priority to check. * * @return boolean True if the given priority is included in the current * log mask. * * @access private * @since Log 1.7.0 */ function _isMasked($priority) { return (vmLog::MASK($priority) & $this->_mask); } /** * Returns the current default priority. * * @return integer The current default priority. * * @access public * @since Log 1.8.4 */ function getPriority() { return $this->_priority; } /** * Sets the default priority to the specified value. * * @param integer $priority The new default priority. * * @access public * @since Log 1.8.4 */ function setPriority($priority) { $this->_priority = $priority; } /** * Adds a Log_observer instance to the list of observers that are listening * for messages emitted by this Log instance. * * @param object $observer The Log_observer instance to attach as a * listener. * * @param boolean True if the observer is successfully attached. * * @access public * @since Log 1.0 */ function attach(&$observer) { if (!is_a($observer, 'Log_observer')) { return false; } $this->_listeners[$observer->_id] = &$observer; return true; } /** * Removes a Log_observer instance from the list of observers. * * @param object $observer The Log_observer instance to detach from * the list of listeners. * * @param boolean True if the observer is successfully detached. * * @access public * @since Log 1.0 */ function detach($observer) { if (!is_a($observer, 'Log_observer') || !isset($this->_listeners[$observer->_id])) { return false; } unset($this->_listeners[$observer->_id]); return true; } /** * Informs each registered observer instance that a new message has been * logged. * * @param array $event A hash describing the log event. * * @access private */ function _announce($event) { foreach ($this->_listeners as $id => $listener) { if ($event['priority'] <= $this->_listeners[$id]->_priority) { $this->_listeners[$id]->notify($event); } } } /** * Indicates whether this is a composite class. * * @return boolean True if this is a composite class. * * @access public * @since Log 1.0 */ function isComposite() { return false; } /** * Sets this Log instance's identification string. * * @param string $ident The new identification string. * * @access public * @since Log 1.6.3 */ function setIdent($ident) { $this->_ident = $ident; } /** * Returns the current identification string. * * @return string The current Log instance's identification string. * * @access public * @since Log 1.6.3 */ function getIdent() { return $this->_ident; } } ?> administrator/components/com_virtuemart/classes/Log/LogInit.php100644 0 0 14155 10752051433 22574 0ustar 0 0 debug("This is a debug message."); * * ...the message will get logged by the file logger (because * it's log level is DEBUG), but NOT by the display logger * (because it's log level is WARNING.) * * * $vmDisplayLogger - The actual display logger. Note that, due to the * way the display logger is implemented, log messages * with a priority >PEAR_LOG_DEBUG will always go to * the display. Debug-priority messages will only be * shown if the DEBUG option is enabled in the VM admin * configuration panel. Also, display logging can now * be restricted by client IP address, also within the * VM admin configuration panel. * * * $vmFileLogger - The file logger. Note that, if file logging is * disabled, a "null" logger will be instantiated in * it's place. This is so that code using vmFileLogger * will continue to function without error, and without * having to actually test if the file logger is enabled. * * If file logging is enabled, but the logger cannot be * created, then a message will be written to the * display (using the vmDisplayLogger), and then a * "null" logger will be created in it's place (for the * same reason as noted above.) * * The log file can be enabled/disabled via the VM admin * config panel; this is also where the log file name is * specified, along with the log level and formatting * options (such as inclusion of remote IP address, * username [if logged in], and VM session ID.) * * Note that, by my reasoning, pretty much all logging output intended for * the display should also go to the file. So, you would normally use * $vmLogger instead of just $vmDisplayLogger. * However, there are many cases where you would only want to log to * file and not have the output go to display. In these cases, you would * use the $vmFileLogger. * * All three loggers are available via $GLOBALS[] as: * * $GLOBALS['vmLogger'] //The composite logger * $GLOBALS['vmDisplayLogger'] //The display logger * $GLOBALS['vmFileLogger'] //The file logger * * * @version $Id: LogInit.php 1215 2008-02-05 12:14:19Z soeren_nb $ * @package VirtueMart * @subpackage Log * @author Mike Mills (mike@MikeMillsConsulting.com) * @copyright Copyright (C) 2008 Mike Mills. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php * VirtueMart is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See /administrator/components/com_virtuemart/COPYRIGHT.php for copyright notices and details. * * http://virtuemart.net */ require_once(CLASSPATH."Log/Log.php"); require_once(CLASSPATH."Log/composite.php"); require_once(CLASSPATH."Log/display.php"); require_once(CLASSPATH."Log/file.php"); $vmLogger = null; $vmDisplayLogger = null; $vmFileLogger = null; /* The $vmLogIdentifier is intended to separate different sources of logging information - such as VirtueMart itself, or external apps like the PayPal notification script (notify.php). */ if(!isset($vmLogIdentifier)) $vmLogIdentifier = ''; /* The existing display logger starts out with a log level of PEAR_LOG_TIP. However, no debug-levwel output will be sent to the display unless the DEBUG option is turned on inside the VM admin configuration panel. */ $vmDisplayLoggerConf = array( 'buffering' => true ); $vmDisplayLogger = &vmLog::singleton('display', '', $vmLogIdentifier, $vmDisplayLoggerConf, PEAR_LOG_TIP); /* Use a null logger if file logging is disabled or if there is an error. This is so that code using the logger will continue to work without problem. */ if(VM_LOGFILE_ENABLED != '1') $vmFileLogger = &vmLog::singleton('null'); else { $vmFileLoggerConf = array('mode' => 0600, 'timeFormat' => '%X %x', 'lineFormat' => VM_LOGFILE_FORMAT); $vmFileLogger = &vmLog::singleton('file', VM_LOGFILE_NAME, $vmLogIdentifier, $vmFileLoggerConf, vmLog::stringToPriorityPEAR(VM_LOGFILE_LEVEL)); if($vmFileLogger == false) { $vmDisplayLogger->warning($VM_LANG->_VM_ADMIN_CFG_LOGFILE_ERROR); $vmFileLogger = &vmLog::singleton('null'); } } $vmLogger = &vmLog::singleton('composite'); $vmLogger->addChild($vmDisplayLogger); $vmLogger->addChild($vmFileLogger); $vmLogger->open(); $GLOBALS['vmLogger'] =& $vmLogger; $GLOBALS['vmDisplayLogger'] =& $vmDisplayLogger; $GLOBALS['vmFileLogger'] =& $vmFileLogger; ?> administrator/components/com_virtuemart/classes/Log/composite.php100644 0 0 13702 10774215017 23232 0ustar 0 0 * @author Jon Parise * * @since Horde 1.3 * @since Log 1.0 * @package Log * * @example composite.php Using the composite handler. */ class vmLog_composite extends vmLog { /** * Array holding all of the Log instances to which log events should be * sent. * * @var array * @access private */ var $_children = array(); /** * Constructs a new composite Log object. * * @param boolean $name This parameter is ignored. * @param boolean $ident This parameter is ignored. * @param boolean $conf This parameter is ignored. * @param boolean $level This parameter is ignored. * * @access public */ function vmLog_composite($name, $ident = '', $conf = array(), $level = PEAR_LOG_DEBUG) { $this->_ident = $ident; } /** * Opens the child connections. * * @access public */ function open() { if (!$this->_opened) { foreach ($this->_children as $id => $child) { $this->_children[$id]->open(); } $this->_opened = true; } } /** * Closes any child instances. * * @access public */ function close() { if ($this->_opened) { foreach ($this->_children as $id => $child) { $this->_children[$id]->close(); } $this->_opened = false; } } /** * Flushes all open child instances. * * @access public * @since Log 1.8.2 */ function flush() { if ($this->_opened) { foreach ($this->_children as $id => $child) { $this->_children[$id]->flush(); } } } /** * Sends $message and $priority to each child of this composite. * * @param mixed $message String or object containing the message * to log. * @param string $priority (optional) The priority of the message. * Valid values are: PEAR_LOG_EMERG, * PEAR_LOG_ALERT, PEAR_LOG_CRIT, * PEAR_LOG_ERR, PEAR_LOG_WARNING, * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and * PEAR_LOG_DEBUG. * * @return boolean True if the entry is successfully logged. * * @access public */ function log($message, $priority = null) { /* If a priority hasn't been specified, use the default value. */ if ($priority === null) { $priority = $this->_priority; } foreach ($this->_children as $id => $child) { $this->_children[$id]->log($message, $priority); } $this->_announce(array('priority' => $priority, 'message' => $message)); return true; } /** * Returns true if this is a composite. * * @return boolean True if this is a composite class. * * @access public */ function isComposite() { return true; } /** * Sets this identification string for all of this composite's children. * * @param string $ident The new identification string. * * @access public * @since Log 1.6.7 */ function setIdent($ident) { /* Call our base class's setIdent() method. */ parent::setIdent($ident); /* ... and then call setIdent() on all of our children. */ foreach ($this->_children as $id => $child) { $this->_children[$id]->setIdent($ident); } } /** * Adds a Log instance to the list of children. * * @param object $child The Log instance to add. * * @return boolean True if the Log instance was successfully added. * * @access public */ function addChild(&$child) { /* Make sure this is a Log instance. */ if (!is_a($child, 'vmLog')) { /*@MWM1: Bugfix, was 'Log', changed to 'vmLog' */ return false; } $this->_children[$child->_id] = &$child; return true; } /** * Removes a Log instance from the list of children. * * @param object $child The Log instance to remove. * * @return boolean True if the Log instance was successfully removed. * * @access public */ function removeChild($child) { if (!is_a($child, 'Log') || !isset($this->_children[$child->_id])) { return false; } unset($this->_children[$child->_id]); return true; } } administrator/components/com_virtuemart/classes/Log/console.php100644 0 0 15063 10774215017 22674 0ustar 0 0 * @since Log 1.1 * @package Log * * @example console.php Using the console handler. */ class vmLog_console extends vmLog { /** * Handle to the current output stream. * @var resource * @access private */ var $_stream = STDOUT; /** * Should the output be buffered or displayed immediately? * @var string * @access private */ var $_buffering = false; /** * String holding the buffered output. * @var string * @access private */ var $_buffer = ''; /** * String containing the format of a log line. * @var string * @access private */ var $_lineFormat = '%1$s %2$s [%3$s] %4$s'; /** * String containing the timestamp format. It will be passed directly to * strftime(). Note that the timestamp string will generated using the * current locale. * @var string * @access private */ var $_timeFormat = '%b %d %H:%M:%S'; /** * Hash that maps canonical format keys to position arguments for the * "line format" string. * @var array * @access private */ var $_formatMap = array('%{timestamp}' => '%1$s', '%{ident}' => '%2$s', '%{priority}' => '%3$s', '%{message}' => '%4$s', '%\{' => '%%{'); /** * Constructs a new vmLog_console object. * * @param string $name Ignored. * @param string $ident The identity string. * @param array $conf The configuration array. * @param int $level Log messages up to and including this level. * @access public */ function vmLog_console($name, $ident = '', $conf = array(), $level = PEAR_LOG_DEBUG) { $this->_id = md5(microtime()); $this->_ident = $ident; $this->_mask = vmLog::UPTO($level); if (!empty($conf['stream'])) { $this->_stream = $conf['stream']; } if (isset($conf['buffering'])) { $this->_buffering = $conf['buffering']; } if (!empty($conf['lineFormat'])) { $this->_lineFormat = str_replace(array_keys($this->_formatMap), array_values($this->_formatMap), $conf['lineFormat']); } if (!empty($conf['timeFormat'])) { $this->_timeFormat = $conf['timeFormat']; } /* * If output buffering has been requested, we need to register a * shutdown function that will dump the buffer upon termination. */ if ($this->_buffering) { register_shutdown_function(array(&$this, '_vmLog_console')); } } /** * Destructor */ function _vmLog_console() { $this->close(); } /** * Closes the output stream. * * This results in a call to flush(). * * @access public * @since Log 1.9.0 */ function close() { $this->flush(); } /** * Flushes all pending ("buffered") data to the output stream. * * @access public * @since Log 1.8.2 */ function flush() { /* * If output buffering is enabled, dump the contents of the buffer to * the output stream. */ if ($this->_buffering && (strlen($this->_buffer) > 0)) { fwrite($this->_stream, $this->_buffer); $this->_buffer = ''; } return fflush($this->_stream); } /** * Writes $message to the text console. Also, passes the message * along to any Log_observer instances that are observing this Log. * * @param mixed $message String or object containing the message to log. * @param string $priority The priority of the message. Valid * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. * @return boolean True on success or false on failure. * @access public */ function log($message, $priority = null) { /* If a priority hasn't been specified, use the default value. */ if ($priority === null) { $priority = $this->_priority; } /* Abort early if the priority is above the maximum logging level. */ if (!$this->_isMasked($priority)) { return false; } /* Extract the string representation of the message. */ $message = $this->_extractMessage($message); /* Build the string containing the complete log line. */ $line = sprintf($this->_lineFormat, strftime($this->_timeFormat), $this->_ident, $this->priorityToString($priority), $message) . "\n"; /* * If buffering is enabled, append this line to the output buffer. * Otherwise, print the line to the output stream immediately. */ if ($this->_buffering) { $this->_buffer .= $line; } else { fwrite($this->_stream, $line); } /* Notify observers about this log message. */ $this->_announce(array('priority' => $priority, 'message' => $message)); return true; } } administrator/components/com_virtuemart/classes/Log/daemon.php100644 0 0 17037 10774215017 22500 0ustar 0 0 * @version $ Revision: 1.2 $ * @package Log */ class vmLog_daemon extends vmLog { /** * Integer holding the log facility to use. * @var string */ var $_name = vmLog_daemon; /** * Var holding the resource pointer to the socket * @var resource */ var $_socket; /** * The ip address or servername * @see http://www.php.net/manual/en/transports.php * @var string */ var $_ip = '127.0.0.1'; /** * Protocol to use (tcp, udp, etc.) * @see http://www.php.net/manual/en/transports.php * @var string */ var $_proto = 'udp'; /** * Port to connect to * @var int */ var $_port = 514; /** * Maximum message length in bytes * @var int */ var $_maxsize = 4096; /** * Socket timeout in seconds * @var int */ var $_timeout = 1; /** * Constructs a new syslog object. * * @param string $name The syslog facility. * @param string $ident The identity string. * @param array $conf The configuration array. * @param int $maxLevel Maximum level at which to log. * @access public */ function vmLog_daemon($name, $ident = '', $conf = array(), $level = PEAR_LOG_DEBUG) { /* Ensure we have a valid integer value for $name. */ if (empty($name) || !is_int($name)) { $name = LOG_SYSLOG; } $this->_id = md5(microtime()); $this->_name = $name; $this->_ident = $ident; $this->_mask = vmLog::UPTO($level); if (isset($conf['ip'])) { $this->_ip = $conf['ip']; } if (isset($conf['proto'])) { $this->_proto = $conf['proto']; } if (isset($conf['port'])) { $this->_port = $conf['port']; } if (isset($conf['maxsize'])) { $this->_maxsize = $conf['maxsize']; } if (isset($conf['timeout'])) { $this->_timeout = $conf['timeout']; } $this->_proto = $this->_proto . '://'; register_shutdown_function(array(&$this, '_vmLog_daemon')); } /** * Destructor. * * @access private */ function _vmLog_daemon() { $this->close(); } /** * Opens a connection to the system logger, if it has not already * been opened. This is implicitly called by log(), if necessary. * @access public */ function open() { if (!$this->_opened) { $this->_opened = (bool)($this->_socket = @fsockopen( $this->_proto . $this->_ip, $this->_port, $errno, $errstr, $this->_timeout)); } return $this->_opened; } /** * Closes the connection to the system logger, if it is open. * @access public */ function close() { if ($this->_opened) { $this->_opened = false; return fclose($this->_socket); } return true; } /** * Sends $message to the currently open syslog connection. Calls * open() if necessary. Also passes the message along to any Log_observer * instances that are observing this Log. * * @param string $message The textual message to be logged. * @param int $priority (optional) The priority of the message. Valid * values are: LOG_EMERG, LOG_ALERT, LOG_CRIT, * LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, * and LOG_DEBUG. The default is LOG_INFO. * @access public */ function log($message, $priority = null) { /* If a priority hasn't been specified, use the default value. */ if ($priority === null) { $priority = $this->_priority; } /* Abort early if the priority is above the maximum logging level. */ if (!$this->_isMasked($priority)) { return false; } /* If the connection isn't open and can't be opened, return failure. */ if (!$this->_opened && !$this->open()) { return false; } /* Extract the string representation of the message. */ $message = $this->_extractMessage($message); /* Set the facility level. */ $facility_level = intval($this->_name) + intval($this->_toSyslog($priority)); /* Prepend ident info. */ if (!empty($this->_ident)) { $message = $this->_ident . ' ' . $message; } /* Check for message length. */ if (strlen($message) > $this->_maxsize) { $message = substr($message, 0, ($this->_maxsize) - 10) . ' [...]'; } /* Write to socket. */ fwrite($this->_socket, '<' . $facility_level . '>' . $message . "\n"); $this->_announce(array('priority' => $priority, 'message' => $message)); } /** * Converts a PEAR_LOG_* constant into a syslog LOG_* constant. * * This function exists because, under Windows, not all of the LOG_* * constants have unique values. Instead, the PEAR_LOG_* were introduced * for global use, with the conversion to the LOG_* constants kept local to * to the syslog driver. * * @param int $priority PEAR_LOG_* value to convert to LOG_* value. * * @return The LOG_* representation of $priority. * * @access private */ function _toSyslog($priority) { static $priorities = array( PEAR_LOG_EMERG => LOG_EMERG, PEAR_LOG_ALERT => LOG_ALERT, PEAR_LOG_CRIT => LOG_CRIT, PEAR_LOG_ERR => LOG_ERR, PEAR_LOG_WARNING => LOG_WARNING, PEAR_LOG_NOTICE => LOG_NOTICE, PEAR_LOG_INFO => LOG_INFO, PEAR_LOG_DEBUG => LOG_DEBUG ); /* If we're passed an unknown priority, default to LOG_INFO. */ if (!is_int($priority) || !in_array($priority, $priorities)) { return LOG_INFO; } return $priorities[$priority]; } } administrator/components/com_virtuemart/classes/Log/display.php100644 0 0 15767 11176664624 22723 0ustar 0 0 * @since Log 1.8.0 * @package Log * * @example display.php Using the display handler. */ class vmLog_display extends vmLog { /** * String used to represent a line break. * @var string * @access private */ var $_linebreak = "
\n"; /** * Flag to enable or disable buffering. * @var boolean * @access private */ var $_buffering = true; /** * Array to store messages when buffering is enabled * * @var array * @access private */ var $_messages = array(); /** * Counts messages in the message array * @var int */ var $_count = 0; /** * Constructs a new vmLog_display object. * * @param string $name Ignored. * @param string $ident The identity string. * @param array $conf The configuration array. * @param int $level Log messages up to and including this level. * @access public */ function vmLog_display($name = '', $ident = '', $conf = array(), $level = PEAR_LOG_TIP) { $this->_id = md5(microtime()); $this->_ident = $ident; $this->_mask = vmLog::UPTO($level); if (isset($conf['linebreak'])) { $this->_linebreak = $conf['linebreak']; } if (isset($conf['buffering'])) { $this->_buffering = $conf['buffering']; } } /** * Writes $message to the text browser. Also, passes the message * along to any Log_observer instances that are observing this Log. * * @param mixed $message String or object containing the message to log. * @param string $priority The priority of the message. Valid * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. * @return boolean True on success or false on failure. * @access public */ function log($message, $priority = null) { /* If a priority hasn't been specified, use the default value. */ if ($priority === null) { $priority = $this->_priority; } /* Abort early if the priority is above the maximum logging level. */ if (!$this->_isMasked($priority)) { return false; } /*@MWM1: Limit debugging by IP address, if enabled.*/ if((VM_DEBUG_IP_ENABLED == '1') && (strcmp($_SERVER['REMOTE_ADDR'], VM_DEBUG_IP_ADDRESS) != 0)) { /* Remote address is NOT our configured debug IP address (if enabled), so skip logging. */ return false; } $this->_ticker++; if( $priority >= PEAR_LOG_ERR ) { defined( '_VM_LOG_ERRORS' ) or define( '_VM_LOG_ERRORS', 1); } /* Extract the string representation of the message. */ $message = $this->_extractMessage($message); // Store the log message and its priority $this->_messages[$this->_count]['priority'] = $priority; $this->_messages[$this->_count]['message'] = $message; $this->_count++; if( !$this->_buffering ) { $this->printLog(); } /* Notify observers about this log message. */ $this->_announce(array('priority' => $priority, 'message' => $message)); return true; } /** * Formats a message depending on its priority * * @param string $message * @param int $priority * @return formatted HTML code */ function formatOutput( $message, $priority) { if( $priority >= PEAR_LOG_TIP) { return '
'. $message . '
'; } elseif( $priority >= PEAR_LOG_DEBUG) { return '
'. $message . '
'; } elseif( $priority >= PEAR_LOG_INFO) { return '
'. $message . '
'; } elseif( $priority >= PEAR_LOG_WARNING ) { return '
'. $message . '
'; } elseif( $priority >= PEAR_LOG_ERR ) { return '
'. $message . '
'; } elseif( $priority >= PEAR_LOG_CRIT ) { return '
'. $message . '
'; } } /** * Override function for printLog * * @param int $priority */ function flush($priority=null) { $this->printLog($priority); } /** * Flush the _messages array and print all messages * @author Soeren Eberhardt */ function printLog( $priority = null ) { if( $this->_count == 0 ) { return; } $output = ''; $has_output = false; $i = 0; $message_tmp = ''; foreach( $this->_messages as $message ) { if( ( $priority === null || $priority <= $message['priority'] ) && $message['priority'] !== PEAR_LOG_DEBUG || ( $message['priority'] === PEAR_LOG_DEBUG && DEBUG == '1')) { $has_output= true; $message_tmp .= '' . ucfirst($this->priorityToString($message['priority'])) . ': ' . nl2br($message['message']) . $this->_linebreak; if( @$this->_messages[$i+1]['priority'] != $message['priority'] ) { $output .= $this->formatOutput( $message_tmp, $message['priority'] ); $message_tmp = ''; } } $i++; } $html = '
_count > 10 && DEBUG) { // Wrap the messages into a scrollable div field $html .= 'style="width:90%; overflow:auto; height:150px;"'; } $html .= '>'. $output . '
'; $this->_count = 0; $this->_messages = array(); if( $output ) { echo $html;// . $this->_linebreak; } } } administrator/components/com_virtuemart/classes/Log/error_log.php100644 0 0 7553 10774215017 23211 0ustar 0 0 * @since Log 1.7.0 * @package Log * * @example error_log.php Using the error_log handler. */ class vmLog_error_log extends vmLog { /** * The error_log() log type. * @var integer * @access private */ var $_type = PEAR_LOG_TYPE_SYSTEM; /** * The type-specific destination value. * @var string * @access private */ var $_destination = ''; /** * Additional headers to pass to the mail() function when the * PEAR_LOG_TYPE_MAIL type is used. * @var string * @access private */ var $_extra_headers = ''; /** * Constructs a new vmLog_error_log object. * * @param string $name Ignored. * @param string $ident The identity string. * @param array $conf The configuration array. * @param int $level Log messages up to and including this level. * @access public */ function vmLog_error_log($name, $ident = '', $conf = array(), $level = PEAR_LOG_DEBUG) { $this->_id = md5(microtime()); $this->_type = $name; $this->_ident = $ident; $this->_mask = vmLog::UPTO($level); if (!empty($conf['destination'])) { $this->_destination = $conf['destination']; } if (!empty($conf['extra_headers'])) { $this->_extra_headers = $conf['extra_headers']; } } /** * Logs $message using PHP's error_log() function. The message is also * passed along to any Log_observer instances that are observing this Log. * * @param mixed $message String or object containing the message to log. * @param string $priority The priority of the message. Valid * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. * @return boolean True on success or false on failure. * @access public */ function log($message, $priority = null) { /* If a priority hasn't been specified, use the default value. */ if ($priority === null) { $priority = $this->_priority; } /* Abort early if the priority is above the maximum logging level. */ if (!$this->_isMasked($priority)) { return false; } /* Extract the string representation of the message. */ $message = $this->_extractMessage($message); $success = error_log($this->_ident . ': ' . $message, $this->_type, $this->_destination, $this->_extra_headers); $this->_announce(array('priority' => $priority, 'message' => $message)); return $success; } } administrator/components/com_virtuemart/classes/Log/file.php100644 0 0 26274 11242221770 22151 0ustar 0 0 * @author Roman Neuhauser * @since Log 1.0 * @package Log * * @example file.php Using the file handler. */ class vmLog_file extends vmLog { /** * String containing the name of the log file. * @var string * @access private */ var $_filename = 'php.log'; /** * Handle to the log file. * @var resource * @access private */ var $_fp = false; /** * Should new log entries be append to an existing log file, or should the * a new log file overwrite an existing one? * @var boolean * @access private */ var $_append = true; /** * Should advisory file locking (i.e., flock()) be used? * @var boolean * @access private */ var $_locking = false; /** * Integer (in octal) containing the log file's permissions mode. * @var integer * @access private */ var $_mode = 0644; /** * Integer (in octal) specifying the file permission mode that will be * used when creating directories that do not already exist. * @var integer * @access private */ var $_dirmode = 0755; /** * String containing the format of a log line. * @var string * @access private */ var $_lineFormat = '%1$s %2$s [%3$s] %4$s'; /** * String containing the timestamp format. It will be passed directly to * strftime(). Note that the timestamp string will generated using the * current locale. * @var string * @access private */ var $_timeFormat = '%b %d %H:%M:%S'; /** * Hash that maps canonical format keys to position arguments for the * "line format" string. * @var array * @access private */ /*@MWM1:Add additional format keys {remoteip}, {username}, {vmsessionid}*/ var $_formatMap = array('%{timestamp}' => '%1$s', '%{ident}' => '%2$s', '%{priority}' => '%3$s', '%{message}' => '%4$s', '%{remoteip}' => '%5$s', '%{username}' => '%6$s', '%{vmsessionid}' => '%7$s', '%\{' => '%%{'); /** * String containing the end-on-line character sequence. * @var string * @access private */ var $_eol = "\n"; /** * Constructs a new vmLog_file object. * * @param string $name Ignored. * @param string $ident The identity string. * @param array $conf The configuration array. * @param int $level Log messages up to and including this level. * @access public */ function vmLog_file($name, $ident = '', $conf = array(), $level = PEAR_LOG_DEBUG) { $this->_id = md5(microtime()); $this->_filename = $name; $this->_ident = $ident; $this->_mask = vmLog::UPTO($level); if (isset($conf['append'])) { $this->_append = $conf['append']; } if (isset($conf['locking'])) { $this->_locking = $conf['locking']; } if (!empty($conf['mode'])) { if (is_string($conf['mode'])) { $this->_mode = octdec($conf['mode']); } else { $this->_mode = $conf['mode']; } } if (!empty($conf['dirmode'])) { if (is_string($conf['dirmode'])) { $this->_dirmode = octdec($conf['dirmode']); } else { $this->_dirmode = $conf['dirmode']; } } if (!empty($conf['lineFormat'])) { $this->_lineFormat = str_replace(array_keys($this->_formatMap), array_values($this->_formatMap), $conf['lineFormat']); } if (!empty($conf['timeFormat'])) { $this->_timeFormat = $conf['timeFormat']; } if (!empty($conf['eol'])) { $this->_eol = $conf['eol']; } else { $this->_eol = (strstr(PHP_OS, 'WIN')) ? "\r\n" : "\n"; } register_shutdown_function(array(&$this, '_vmLog_file')); } /** * Destructor */ function _vmLog_file() { if ($this->_opened) { $this->close(); } } /** * Creates the given directory path. If the parent directories don't * already exist, they will be created, too. * * This implementation is inspired by Python's os.makedirs function. * * @param string $path The full directory path to create. * @param integer $mode The permissions mode with which the * directories will be created. * * @return True if the full path is successfully created or already * exists. * * @access private */ function _mkpath($path, $mode = 0700) { /* Separate the last pathname component from the rest of the path. */ $head = dirname($path); $tail = basename($path); /* Make sure we've split the path into two complete components. */ if (empty($tail)) { $head = dirname($path); $tail = basename($path); } /* Recurse up the path if our current segment does not exist. */ if (!empty($head) && !empty($tail) && !is_dir($head)) { $this->_mkpath($head, $mode); } /* Create this segment of the path. */ return @mkdir($head, $mode); } /** * Opens the log file for output. If the specified log file does not * already exist, it will be created. By default, new log entries are * appended to the end of the log file. * * This is implicitly called by log(), if necessary. * * @access public */ function open() { if (!$this->_opened) { if( empty( $this->_filename )) { return false; } /* If the log file's directory doesn't exist, create it. */ if (!is_dir(dirname($this->_filename))) { $this->_mkpath($this->_filename, $this->_dirmode); } /* Determine whether the log file needs to be created. */ $creating = !file_exists($this->_filename); /* Obtain a handle to the log file. */ $this->_fp = fopen($this->_filename, ($this->_append) ? 'a' : 'w'); /* We consider the file "opened" if we have a valid file pointer. */ $this->_opened = ($this->_fp !== false); /* Attempt to set the file's permissions if we just created it. */ if ($creating && $this->_opened) { chmod($this->_filename, $this->_mode); } } return $this->_opened; } /** * Closes the log file if it is open. * * @access public */ function close() { /* If the log file is open, close it. */ if ($this->_opened && fclose($this->_fp)) { $this->_opened = false; } return ($this->_opened === false); } /** * Flushes all pending data to the file handle. * * @access public * @since Log 1.8.2 */ function flush() { return is_resource($this->_fp) ? fflush($this->_fp) : false; } /** * Logs $message to the output window. The message is also passed along * to any Log_observer instances that are observing this Log. * * @param mixed $message String or object containing the message to log. * @param string $priority The priority of the message. Valid * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. * @return boolean True on success or false on failure. * @access public */ function log($message, $priority = null) { /* If a priority hasn't been specified, use the default value. */ if ($priority === null) { $priority = $this->_priority; } /* Abort early if the priority is above the maximum logging level. */ if (!$this->_isMasked($priority)) { return false; } /* If the log file isn't already open, open it now. */ if (!$this->_opened && !$this->open()) { return false; } /* Extract the string representation of the message. */ $message = $this->_extractMessage($message); /* #B@MWM1: Add additional info that can be logged */ if (!empty($_SERVER['REMOTE_ADDR'])) $remoteip = $_SERVER['REMOTE_ADDR']; else $remoteip = 'unknown IP'; if (!empty($_SESSION['auth']["username"])) $username = $_SESSION['auth']["username"]; else $username = 'unknown user'; $vmsessionid = session_id(); /*#E@MWM1*/ /* Build the string containing the complete log line. */ /* @MWM1 Logging changes...*/ $line = sprintf($this->_lineFormat, strftime($this->_timeFormat), $this->_ident, $this->priorityToShortStringPEAR($priority), $message, $remoteip, $username, $vmsessionid) . $this->_eol; /* If locking is enabled, acquire an exclusive lock on the file. */ if ($this->_locking) { flock($this->_fp, LOCK_EX); } /* Write the log line to the log file. */ $success = (fwrite($this->_fp, $line) !== false); /* Unlock the file now that we're finished writing to it. */ if ($this->_locking) { flock($this->_fp, LOCK_UN); } /* Notify observers about this log message. */ $this->_announce(array('priority' => $priority, 'message' => $message)); return $success; } } administrator/components/com_virtuemart/classes/Log/index.html100644 0 0 0 11026265061 22372 0ustar 0 0 administrator/components/com_virtuemart/classes/Log/mail.php100644 0 0 16045 10774215017 22155 0ustar 0 0 * @author Jon Parise * @since Log 1.3 * @package Log * * @example mail.php Using the mail handler. */ class vmLog_mail extends vmLog { /** * String holding the recipient's email address. * @var string * @access private */ var $_recipient = ''; /** * String holding the sender's email address. * @var string * @access private */ var $_from = ''; /** * String holding the email's subject. * @var string * @access private */ var $_subject = '[vmLog_mail] Log message'; /** * String holding an optional preamble for the log messages. * @var string * @access private */ var $_preamble = ''; /** * String holding the mail message body. * @var string * @access private */ var $_message = ''; /** * Constructs a new vmLog_mail object. * * Here is how you can customize the mail driver with the conf[] hash : * $conf['from'] : the mail's "From" header line, * $conf['subject'] : the mail's "Subject" line. * * @param string $name The filename of the logfile. * @param string $ident The identity string. * @param array $conf The configuration array. * @param int $level Log messages up to and including this level. * @access public */ function vmLog_mail($name, $ident = '', $conf = array(), $level = PEAR_LOG_DEBUG) { $this->_id = md5(microtime()); $this->_recipient = $name; $this->_ident = $ident; $this->_mask = vmLog::UPTO($level); if (!empty($conf['from'])) { $this->_from = $conf['from']; } else { $this->_from = ini_get('sendmail_from'); } if (!empty($conf['subject'])) { $this->_subject = $conf['subject']; } if (!empty($conf['preamble'])) { $this->_preamble = $conf['preamble']; } /* register the destructor */ register_shutdown_function(array(&$this, '_vmLog_mail')); } /** * Destructor. Calls close(). * * @access private */ function _vmLog_mail() { $this->close(); } /** * Starts a new mail message. * This is implicitly called by log(), if necessary. * * @access public */ function open() { if (!$this->_opened) { if (!empty($this->_preamble)) { $this->_message = $this->_preamble . "\r\n\r\n"; } $this->_opened = true; } return $this->_opened; } /** * Closes the message, if it is open, and sends the mail. * This is implicitly called by the destructor, if necessary. * * @access public */ function close() { if ($this->_opened) { if (!empty($this->_message)) { $headers = "From: $this->_from\r\n"; $headers .= "User-Agent: vmLog_mail"; if (mail($this->_recipient, $this->_subject, $this->_message, $headers) == false) { error_log("vmLog_mail: Failure executing mail()", 0); return false; } /* Clear the message string now that the email has been sent. */ $this->_message = ''; } $this->_opened = false; } return ($this->_opened === false); } /** * Flushes the log output by forcing the email message to be sent now. * Events that are logged after flush() is called will be appended to a * new email message. * * @access public * @since Log 1.8.2 */ function flush() { /* * It's sufficient to simply call close() to flush the output. * The next call to log() will cause the handler to be reopened. */ return $this->close(); } /** * Writes $message to the currently open mail message. * Calls open(), if necessary. * * @param mixed $message String or object containing the message to log. * @param string $priority The priority of the message. Valid * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. * @return boolean True on success or false on failure. * @access public */ function log($message, $priority = null) { /* If a priority hasn't been specified, use the default value. */ if ($priority === null) { $priority = $this->_priority; } /* Abort early if the priority is above the maximum logging level. */ if (!$this->_isMasked($priority)) { return false; } /* If the message isn't open and can't be opened, return failure. */ if (!$this->_opened && !$this->open()) { return false; } /* Extract the string representation of the message. */ $message = $this->_extractMessage($message); $entry = sprintf("%s %s [%s] %s\r\n", strftime('%b %d %H:%M:%S'), $this->_ident, vmLog::priorityToString($priority), $message); $this->_message .= $entry; $this->_announce(array('priority' => $priority, 'message' => $message)); return true; } } administrator/components/com_virtuemart/classes/Log/mcal.php100644 0 0 13315 10774215017 22144 0ustar 0 0 * @since Horde 1.3 * @since Log 1.0 * @package Log */ class vmLog_mcal extends vmLog { /** * holding the calendar specification to connect to. * @var string * @access private */ var $_calendar = '{localhost/mstore}'; /** * holding the username to use. * @var string * @access private */ var $_username = ''; /** * holding the password to use. * @var string * @access private */ var $_password = ''; /** * holding the options to pass to the calendar stream. * @var integer * @access private */ var $_options = 0; /** * ResourceID of the MCAL stream. * @var string * @access private */ var $_stream = ''; /** * Integer holding the log facility to use. * @var string * @access private */ var $_name = LOG_SYSLOG; /** * Constructs a new vmLog_mcal object. * * @param string $name The category to use for our events. * @param string $ident The identity string. * @param array $conf The configuration array. * @param int $level Log messages up to and including this level. * @access public */ function vmLog_mcal($name, $ident = '', $conf = array(), $level = PEAR_LOG_DEBUG) { $this->_id = md5(microtime()); $this->_name = $name; $this->_ident = $ident; $this->_mask = vmLog::UPTO($level); $this->_calendar = $conf['calendar']; $this->_username = $conf['username']; $this->_password = $conf['password']; $this->_options = $conf['options']; } /** * Opens a calendar stream, if it has not already been * opened. This is implicitly called by log(), if necessary. * @access public */ function open() { if (!$this->_opened) { $this->_stream = mcal_open($this->_calendar, $this->_username, $this->_password, $this->_options); $this->_opened = true; } return $this->_opened; } /** * Closes the calendar stream, if it is open. * @access public */ function close() { if ($this->_opened) { mcal_close($this->_stream); $this->_opened = false; } return ($this->_opened === false); } /** * Logs $message and associated information to the currently open * calendar stream. Calls open() if necessary. Also passes the * message along to any Log_observer instances that are observing * this Log. * * @param mixed $message String or object containing the message to log. * @param string $priority The priority of the message. Valid * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. * @return boolean True on success or false on failure. * @access public */ function log($message, $priority = null) { /* If a priority hasn't been specified, use the default value. */ if ($priority === null) { $priority = $this->_priority; } /* Abort early if the priority is above the maximum logging level. */ if (!$this->_isMasked($priority)) { return false; } /* If the connection isn't open and can't be opened, return failure. */ if (!$this->_opened && !$this->open()) { return false; } /* Extract the string representation of the message. */ $message = $this->_extractMessage($message); $date_str = date('Y:n:j:G:i:s'); $dates = explode(':', $date_str); mcal_event_init($this->_stream); mcal_event_set_title($this->_stream, $this->_ident); mcal_event_set_category($this->_stream, $this->_name); mcal_event_set_description($this->_stream, $message); mcal_event_add_attribute($this->_stream, 'priority', $priority); mcal_event_set_start($this->_stream, $dates[0], $dates[1], $dates[2], $dates[3], $dates[4], $dates[5]); mcal_event_set_end($this->_stream, $dates[0], $dates[1], $dates[2], $dates[3], $dates[4], $dates[5]); mcal_append_event($this->_stream); $this->_announce(array('priority' => $priority, 'message' => $message)); return true; } } administrator/components/com_virtuemart/classes/Log/null.php100644 0 0 5430 10774215017 22161 0ustar 0 0 * @since Log 1.8.2 * @package Log * * @example null.php Using the null handler. */ class vmLog_null extends vmLog { /** * Constructs a new vmLog_null object. * * @param string $name Ignored. * @param string $ident The identity string. * @param array $conf The configuration array. * @param int $level Log messages up to and including this level. * @access public */ function vmLog_null($name, $ident = '', $conf = array(), $level = PEAR_LOG_DEBUG) { $this->_id = md5(microtime()); $this->_ident = $ident; $this->_mask = vmLog::UPTO($level); } /** * Simply consumes the log event. The message will still be passed * along to any Log_observer instances that are observing this Log. * * @param mixed $message String or object containing the message to log. * @param string $priority The priority of the message. Valid * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. * @return boolean True on success or false on failure. * @access public */ function log($message, $priority = null) { /* If a priority hasn't been specified, use the default value. */ if ($priority === null) { $priority = $this->_priority; } /* Abort early if the priority is above the maximum logging level. */ if (!$this->_isMasked($priority)) { return false; } $this->_announce(array('priority' => $priority, 'message' => $message)); return true; } } administrator/components/com_virtuemart/classes/Log/observer.php100644 0 0 12526 10774215017 23062 0ustar 0 0 * @since Horde 1.3 * @since Log 1.0 * @package Log * * @example observer_mail.php An example vmLog_observer implementation. */ class vmLog_observer { /** * Instance-specific unique identification number. * * @var integer * @access private */ var $_id = 0; /** * The minimum priority level of message that we want to hear about. * PEAR_LOG_EMERG is the highest priority, so we will only hear messages * with an integer priority value less than or equal to ours. It defaults * to PEAR_LOG_INFO, which listens to everything except PEAR_LOG_DEBUG. * * @var string * @access private */ var $_priority = PEAR_LOG_INFO; /** * Creates a new basic vmLog_observer instance. * * @param integer $priority The highest priority at which to receive * log event notifications. * * @access public */ function vmLog_observer($priority = PEAR_LOG_INFO) { $this->_id = md5(microtime()); $this->_priority = $priority; } /** * Attempts to return a new concrete vmLog_observer instance of the requested * type. * * @param string $type The type of concreate vmLog_observer subclass * to return. * @param integer $priority The highest priority at which to receive * log event notifications. * @param array $conf Optional associative array of additional * configuration values. * * @return object The newly created concrete vmLog_observer * instance, or an false on an error. */ function &factory($type, $priority = PEAR_LOG_INFO, $conf = array()) { $type = strtolower($type); $class = 'vmLog_observer_' . $type; /* Support both the new-style and old-style file naming conventions. */ if (file_exists(dirname(__FILE__) . '/observer_' . $type . '.php')) { $classfile = 'Log/observer_' . $type . '.php'; $newstyle = true; } else { $classfile = 'Log/' . $type . '.php'; $newstyle = false; } /* Issue a warning if the old-style conventions are being used. */ if (!$newstyle) { trigger_error('Using old-style vmLog_observer conventions', E_USER_WARNING); } /* * Attempt to include our version of the named class, but don't treat * a failure as fatal. The caller may have already included their own * version of the named class. */ @include_once $classfile; /* If the class exists, return a new instance of it. */ if (class_exists($class)) { /* Support both new-style and old-style construction. */ if ($newstyle) { return new $class($priority, $conf); } else { return new $class($priority); } } return false; } /** <<<<<<< observer.php * This is a stub method to make sure that vmLog_observer classes do * something when they are notified of a message. The default * behavior is to just print the message, which is obviously not * desireable in practically any situation - which is why you need * to override this method. :) * * @param array $messageOb A hash containing all information - the text * message itself, the priority, what log it came * from, etc. ======= * This is a stub method to make sure that vmLog_observer classes do * something when they are notified of a message. The default behavior * is to just print the message, which is obviously not desireable in * practically any situation - which is why you need to override this * method. :) * * @param array $event A hash describing the log event. >>>>>>> 1.5 */ function notify($event) { print_r($event); } } administrator/components/com_virtuemart/classes/Log/sql.php100644 0 0 20607 10774215017 22031 0ustar 0 0 * @since Horde 1.3 * @since Log 1.0 * @package Log * * @example sql.php Using the SQL handler. */ class vmLog_sql extends vmLog { /** * Variable containing the DSN information. * @var mixed * @access private */ var $_dsn = ''; /** * Array containing our set of DB configuration options. * @var array * @access private */ var $_options = array('persistent' => true); /** * Object holding the database handle. * @var object * @access private */ var $_db = null; /** * Resource holding the prepared statement handle. * @var resource * @access private */ var $_statement = null; /** * Flag indicating that we're using an existing database connection. * @var boolean * @access private */ var $_existingConnection = false; /** * String holding the database table to use. * @var string * @access private */ var $_table = 'log_table'; /** * String holding the name of the ID sequence. * @var string * @access private */ var $_sequence = 'log_id'; /** * Maximum length of the $ident string. This corresponds to the size of * the 'ident' column in the SQL table. * @var integer * @access private */ var $_identLimit = 16; /** * Constructs a new sql logging object. * * @param string $name The target SQL table. * @param string $ident The identification field. * @param array $conf The connection configuration array. * @param int $level Log messages up to and including this level. * @access public */ function vmLog_sql($name, $ident = '', $conf = array(), $level = PEAR_LOG_DEBUG) { $this->_id = md5(microtime()); $this->_table = $name; $this->_mask = vmLog::UPTO($level); /* If an options array was provided, use it. */ if (isset($conf['options']) && is_array($conf['options'])) { $this->_options = $conf['options']; } /* If a specific sequence name was provided, use it. */ if (!empty($conf['sequence'])) { $this->_sequence = $conf['sequence']; } /* If a specific sequence name was provided, use it. */ if (isset($conf['identLimit'])) { $this->_identLimit = $conf['identLimit']; } /* Now that the ident limit is confirmed, set the ident string. */ $this->setIdent($ident); /* If an existing database connection was provided, use it. */ if (isset($conf['db'])) { $this->_db = &$conf['db']; $this->_existingConnection = true; $this->_opened = true; } else { $this->_dsn = $conf['dsn']; } } /** * Opens a connection to the database, if it has not already * been opened. This is implicitly called by log(), if necessary. * * @return boolean True on success, false on failure. * @access public */ function open() { if (!$this->_opened) { /* Use the DSN and options to create a database connection. */ $this->_db = &DB::connect($this->_dsn, $this->_options); if (DB::isError($this->_db)) { return false; } /* Create a prepared statement for repeated use in log(). */ $this->_statement = $this->_db->prepare('INSERT INTO ' . $this->_table . ' (id, logtime, ident, priority, message)' . ' VALUES(?, CURRENT_TIMESTAMP, ?, ?, ?)'); if (DB::isError($this->_statement)) { return false; } /* We now consider out connection open. */ $this->_opened = true; } return $this->_opened; } /** * Closes the connection to the database if it is still open and we were * the ones that opened it. It is the caller's responsible to close an * existing connection that was passed to us via $conf['db']. * * @return boolean True on success, false on failure. * @access public */ function close() { if ($this->_opened && !$this->_existingConnection) { $this->_opened = false; $this->_db->freePrepared($this->_statement); return $this->_db->disconnect(); } return ($this->_opened === false); } /** * Sets this Log instance's identification string. Note that this * SQL-specific implementation will limit the length of the $ident string * to sixteen (16) characters. * * @param string $ident The new identification string. * * @access public * @since Log 1.8.5 */ function setIdent($ident) { $this->_ident = substr($ident, 0, $this->_identLimit); } /** * Inserts $message to the currently open database. Calls open(), * if necessary. Also passes the message along to any Log_observer * instances that are observing this Log. * * @param mixed $message String or object containing the message to log. * @param string $priority The priority of the message. Valid * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. * @return boolean True on success or false on failure. * @access public */ function log($message, $priority = null) { /* If a priority hasn't been specified, use the default value. */ if ($priority === null) { $priority = $this->_priority; } /* Abort early if the priority is above the maximum logging level. */ if (!$this->_isMasked($priority)) { return false; } /* If the connection isn't open and can't be opened, return failure. */ if (!$this->_opened && !$this->open()) { return false; } /* Extract the string representation of the message. */ $message = $this->_extractMessage($message); /* Build our set of values for this log entry. */ $id = $this->_db->nextId($this->_sequence); $values = array($id, $this->_ident, $priority, $message); /* Execute the SQL query for this log entry insertion. */ $result =& $this->_db->execute($this->_statement, $values); if (DB::isError($result)) { return false; } $this->_announce(array('priority' => $priority, 'message' => $message)); return true; } } administrator/components/com_virtuemart/classes/Log/syslog.php100644 0 0 13175 10774215017 22554 0ustar 0 0 * @since Horde 1.3 * @since Log 1.0 * @package Log * * @example syslog.php Using the syslog handler. */ class vmLog_syslog extends vmLog { /** * Integer holding the log facility to use. * @var string * @access private */ var $_name = vmLog_syslog; /** * Constructs a new syslog object. * * @param string $name The syslog facility. * @param string $ident The identity string. * @param array $conf The configuration array. * @param int $level Log messages up to and including this level. * @access public */ function vmLog_syslog($name, $ident = '', $conf = array(), $level = PEAR_LOG_DEBUG) { /* Ensure we have a valid integer value for $name. */ if (empty($name) || !is_int($name)) { $name = vmLog_syslog; } $this->_id = md5(microtime()); $this->_name = $name; $this->_ident = $ident; $this->_mask = vmLog::UPTO($level); } /** * Opens a connection to the system logger, if it has not already * been opened. This is implicitly called by log(), if necessary. * @access public */ function open() { if (!$this->_opened) { openlog($this->_ident, LOG_PID, $this->_name); $this->_opened = true; } return $this->_opened; } /** * Closes the connection to the system logger, if it is open. * @access public */ function close() { if ($this->_opened) { closelog(); $this->_opened = false; } return ($this->_opened === false); } /** * Sends $message to the currently open syslog connection. Calls * open() if necessary. Also passes the message along to any Log_observer * instances that are observing this Log. * * @param mixed $message String or object containing the message to log. * @param int $priority (optional) The priority of the message. Valid * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. * @return boolean True on success or false on failure. * @access public */ function log($message, $priority = null) { /* If a priority hasn't been specified, use the default value. */ if ($priority === null) { $priority = $this->_priority; } /* Abort early if the priority is above the maximum logging level. */ if (!$this->_isMasked($priority)) { return false; } /* If the connection isn't open and can't be opened, return failure. */ if (!$this->_opened && !$this->open()) { return false; } /* Extract the string representation of the message. */ $message = $this->_extractMessage($message); if (!syslog($this->_toSyslog($priority), $message)) { return false; } $this->_announce(array('priority' => $priority, 'message' => $message)); return true; } /** * Converts a PEAR_LOG_* constant into a syslog LOG_* constant. * * This function exists because, under Windows, not all of the LOG_* * constants have unique values. Instead, the PEAR_LOG_* were introduced * for global use, with the conversion to the LOG_* constants kept local to * to the syslog driver. * * @param int $priority PEAR_LOG_* value to convert to LOG_* value. * * @return The LOG_* representation of $priority. * * @access private */ function _toSyslog($priority) { static $priorities = array( PEAR_LOG_EMERG => LOG_EMERG, PEAR_LOG_ALERT => LOG_ALERT, PEAR_LOG_CRIT => LOG_CRIT, PEAR_LOG_ERR => LOG_ERR, PEAR_LOG_WARNING => LOG_WARNING, PEAR_LOG_NOTICE => LOG_NOTICE, PEAR_LOG_INFO => LOG_INFO, PEAR_LOG_DEBUG => LOG_DEBUG ); /* If we're passed an unknown priority, default to LOG_INFO. */ if (!is_int($priority) || !in_array($priority, $priorities)) { return LOG_INFO; } return $priorities[$priority]; } } administrator/components/com_virtuemart/classes/Log/win.php100644 0 0 21133 10774215017 22022 0ustar 0 0 * @since Log 1.7.0 * @package Log * * @example win.php Using the window handler. */ class vmLog_win extends vmLog { /** * The name of the output window. * @var string * @access private */ var $_name = 'LogWindow'; /** * The title of the output window. * @var string * @access private */ var $_title = 'Log Output Window'; /** * Mapping of log priorities to colors. * @var array * @access private */ var $_colors = array( PEAR_LOG_EMERG => 'red', PEAR_LOG_ALERT => 'orange', PEAR_LOG_CRIT => 'yellow', PEAR_LOG_ERR => 'green', PEAR_LOG_WARNING => 'blue', PEAR_LOG_NOTICE => 'indigo', PEAR_LOG_INFO => 'violet', PEAR_LOG_DEBUG => 'black' ); /** * String buffer that holds line that are pending output. * @var array * @access private */ var $_buffer = array(); /** * Constructs a new vmLog_win object. * * @param string $name Ignored. * @param string $ident The identity string. * @param array $conf The configuration array. * @param int $level Log messages up to and including this level. * @access public */ function vmLog_win($name, $ident = '', $conf = array(), $level = PEAR_LOG_DEBUG) { $this->_id = md5(microtime()); $this->_name = $name; $this->_ident = $ident; $this->_mask = vmLog::UPTO($level); if (isset($conf['title'])) { $this->_title = $conf['title']; } if (isset($conf['colors']) && is_array($conf['colors'])) { $this->_colors = $conf['colors']; } register_shutdown_function(array(&$this, '_vmLog_win')); } /** * Destructor */ function _vmLog_win() { if ($this->_opened || (count($this->_buffer) > 0)) { $this->close(); } } /** * The first time open() is called, it will open a new browser window and * prepare it for output. * * This is implicitly called by log(), if necessary. * * @access public */ function open() { if (!$this->_opened) { $win = $this->_name; if (!empty($this->_ident)) { $identHeader = "$win.document.writeln('Ident')"; } else { $identHeader = ''; } echo <<< END_OF_SCRIPT END_OF_SCRIPT; $this->_opened = true; } return $this->_opened; } /** * Closes the output stream if it is open. If there are still pending * lines in the output buffer, the output window will be opened so that * the buffer can be drained. * * @access public */ function close() { /* * If there are still lines waiting to be written, open the output * window so that we can drain the buffer. */ if (!$this->_opened && (count($this->_buffer) > 0)) { $this->open(); } if ($this->_opened) { $this->_writeln(''); $this->_writeln(''); $this->_opened = false; } return ($this->_opened === false); } /** * Writes a single line of text to the output window. * * @param string $line The line of text to write. * * @access private */ function _writeln($line) { /* Add this line to our output buffer. */ $this->_buffer[] = $line; /* Buffer the output until this page's headers have been sent. */ if (!headers_sent()) { return; } /* If we haven't already opened the output window, do so now. */ if (!$this->_opened && !$this->open()) { return false; } /* Drain the buffer to the output window. */ $win = $this->_name; foreach ($this->_buffer as $line) { echo "\n"; } /* Now that the buffer has been drained, clear it. */ $this->_buffer = array(); } /** * Logs $message to the output window. The message is also passed along * to any Log_observer instances that are observing this Log. * * @param mixed $message String or object containing the message to log. * @param string $priority The priority of the message. Valid * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. * @return boolean True on success or false on failure. * @access public */ function log($message, $priority = null) { /* If a priority hasn't been specified, use the default value. */ if ($priority === null) { $priority = $this->_priority; } /* Abort early if the priority is above the maximum logging level. */ if (!$this->_isMasked($priority)) { return false; } /* Extract the string representation of the message. */ $message = $this->_extractMessage($message); list($usec, $sec) = explode(' ', microtime()); /* Build the output line that contains the log entry row. */ $line = ''; $line .= sprintf('%s.%s', strftime('%T', $sec), substr($usec, 2, 2)); if (!empty($this->_ident)) { $line .= '' . $this->_ident . ''; } $line .= '' . ucfirst($this->priorityToString($priority)) . ''; $line .= sprintf('%s', $this->_colors[$priority], preg_replace('/\r\n|\n|\r/', '
', $message)); $line .= ''; $this->_writeln($line); $this->_announce(array('priority' => $priority, 'message' => $message)); return true; } } administrator/components/com_virtuemart/classes/PEAR/Common.php100644 0 0 27620 10547254314 22473 0ustar 0 0 | // +----------------------------------------------------------------------+ // // $Id: Common.php 617 2007-01-04 19:43:08Z soeren_nb $ /** * Base class for all HTML classes * * @author Adam Daniel * @category HTML * @package HTML_Common * @version 1.2.2 * @abstract */ /** * Base class for all HTML classes * * @author Adam Daniel * @version 1.7 * @since PHP 4.0.3pl1 * @abstract */ class HTML_Common { /** * Associative array of table attributes * @var array * @access private */ var $_attributes = array(); /** * Tab offset of the table * @var int * @access private */ var $_tabOffset = 0; /** * Tab string * @var string * @since 1.7 * @access private */ var $_tab = "\11"; /** * Contains the line end string * @var string * @since 1.7 * @access private */ var $_lineEnd = "\12"; /** * HTML comment on the object * @var string * @since 1.5 * @access private */ var $_comment = ''; /** * Class constructor * @param mixed $attributes Associative array of table tag attributes * or HTML attributes name="value" pairs * @param int $tabOffset Indent offset in tabs * @access public */ function HTML_Common($attributes = null, $tabOffset = 0) { $this->setAttributes($attributes); $this->setTabOffset($tabOffset); } // end constructor /** * Returns the current API version * @access public * @returns double */ function apiVersion() { return 1.7; } // end func apiVersion /** * Returns the lineEnd * * @since 1.7 * @access private * @return string * @throws */ function _getLineEnd() { return $this->_lineEnd; } // end func getLineEnd /** * Returns a string containing the unit for indenting HTML * * @since 1.7 * @access private * @return string */ function _getTab() { return $this->_tab; } // end func _getTab /** * Returns a string containing the offset for the whole HTML code * * @return string * @access private */ function _getTabs() { return str_repeat($this->_getTab(), $this->_tabOffset); } // end func _getTabs /** * Returns an HTML formatted attribute string * @param array $attributes * @return string * @access private */ function _getAttrString($attributes) { $strAttr = ''; if (is_array($attributes)) { foreach ($attributes as $key => $value) { $strAttr .= ' ' . $key . '="' . htmlspecialchars($value) . '"'; } } return $strAttr; } // end func _getAttrString /** * Returns a valid atrributes array from either a string or array * @param mixed $attributes Either a typical HTML attribute string or an associative array * @access private */ function _parseAttributes($attributes) { if (is_array($attributes)) { $ret = array(); foreach ($attributes as $key => $value) { if (is_int($key)) { $key = $value = strtolower($value); } else { $key = strtolower($key); } $ret[$key] = $value; } return $ret; } elseif (is_string($attributes)) { $preg = "/(([A-Za-z_:]|[^\\x00-\\x7F])([A-Za-z0-9_:.-]|[^\\x00-\\x7F])*)" . "([ \\n\\t\\r]+)?(=([ \\n\\t\\r]+)?(\"[^\"]*\"|'[^']*'|[^ \\n\\t\\r]*))?/"; if (preg_match_all($preg, $attributes, $regs)) { for ($counter=0; $counter $value) { $attr1[$key] = $value; } } // end func _updateAtrrArray /** * Removes the given attribute from the given array * * @param string $attr Attribute name * @param array $attributes Attribute array * @since 1.4 * @access private * @return void * @throws */ function _removeAttr($attr, &$attributes) { $attr = strtolower($attr); if (isset($attributes[$attr])) { unset($attributes[$attr]); } } //end func _removeAttr /** * Returns the value of the given attribute * * @param string $attr Attribute name * @since 1.5 * @access public * @return void * @throws */ function getAttribute($attr) { $attr = strtolower($attr); if (isset($this->_attributes[$attr])) { return $this->_attributes[$attr]; } return null; } //end func getAttribute /** * Sets the HTML attributes * @param mixed $attributes Either a typical HTML attribute string or an associative array * @access public */ function setAttributes($attributes) { $this->_attributes = $this->_parseAttributes($attributes); } // end func setAttributes /** * Returns the assoc array (default) or string of attributes * * @param bool Whether to return the attributes as string * @since 1.6 * @access public * @return mixed attributes */ function getAttributes($asString = false) { if ($asString) { return $this->_getAttrString($this->_attributes); } else { return $this->_attributes; } } //end func getAttributes /** * Updates the passed attributes without changing the other existing attributes * @param mixed $attributes Either a typical HTML attribute string or an associative array * @access public */ function updateAttributes($attributes) { $this->_updateAttrArray($this->_attributes, $this->_parseAttributes($attributes)); } // end func updateAttributes /** * Removes an attribute * * @param string $attr Attribute name * @since 1.4 * @access public * @return void * @throws */ function removeAttribute($attr) { $this->_removeAttr($attr, $this->_attributes); } //end func removeAttribute /** * Sets the line end style to Windows, Mac, Unix or a custom string. * * @param string $style "win", "mac", "unix" or custom string. * @since 1.7 * @access public * @return void */ function setLineEnd($style) { switch ($style) { case 'win': $this->_lineEnd = "\15\12"; break; case 'unix': $this->_lineEnd = "\12"; break; case 'mac': $this->_lineEnd = "\15"; break; default: $this->_lineEnd = $style; } } // end func setLineEnd /** * Sets the tab offset * * @param int $offset * @access public */ function setTabOffset($offset) { $this->_tabOffset = $offset; } // end func setTabOffset /** * Returns the tabOffset * * @since 1.5 * @access public * @return int */ function getTabOffset() { return $this->_tabOffset; } //end func getTabOffset /** * Sets the string used to indent HTML * * @since 1.7 * @param string $string String used to indent ("\11", "\t", ' ', etc.). * @access public * @return void */ function setTab($string) { $this->_tab = $string; } // end func setTab /** * Sets the HTML comment to be displayed at the beginning of the HTML string * * @param string * @since 1.4 * @access public * @return void */ function setComment($comment) { $this->_comment = $comment; } // end func setHtmlComment /** * Returns the HTML comment * * @since 1.5 * @access public * @return string */ function getComment() { return $this->_comment; } //end func getComment /** * Abstract method. Must be extended to return the objects HTML * * @access public * @return string * @abstract */ function toHtml() { return ''; } // end func toHtml /** * Displays the HTML to the screen * * @access public */ function display() { print $this->toHtml(); } // end func display } // end class HTML_Common ?> administrator/components/com_virtuemart/classes/PEAR/Table.php100644 0 0 54503 11263443355 22273 0ustar 0 0 * @author Bertrand Mansion * @copyright 2005 The PHP Group * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version CVS: $Id: Table.php 1958 2009-10-08 20:09:57Z soeren_nb $ * @link http://pear.php.net/package/HTML_Table */ /** * Requires PEAR, HTML_Common and HTML_Table_Storage */ require_once dirname(__FILE__).'/../../PEAR.php'; require_once dirname(__FILE__).'/Common.php'; require_once dirname(__FILE__).'/Table/Storage.php'; /** * PEAR::HTML_Table makes the design of HTML tables easy, flexible, reusable and efficient. * * The PEAR::HTML_Table package provides methods for easy and efficient design of HTML tables. * - Lots of customization options. * - Tables can be modified at any time. * - The logic is the same as standard HTML editors. * - Handles col and rowspans. * - PHP code is shorter, easier to read and to maintain. * - Tables options can be reused. * * For auto filling of data and such then check out http://pear.php.net/package/HTML_Table_Matrix * * @category HTML * @package HTML_Table * @author Adam Daniel * @author Bertrand Mansion * @copyright 2005 The PHP Group * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version Release: @package_version@ * @link http://pear.php.net/package/HTML_Table */ class HTML_Table extends HTML_Common { /** * Value to insert into empty cells * @var string * @access private */ var $_autoFill = ' '; /** * Array containing the table caption * @var array * @access private */ var $_caption = array(); /** * Array containing the table column group specifications * * @var array * @author Laurent Laville (pear at laurent-laville dot org) * @access private */ var $_colgroup = array(); /** * HTML_Table_Storage object for the (t)head of the table * @var object * @access private */ var $_thead = null; /** * HTML_Table_Storage object for the (t)foot of the table * @var object * @access private */ var $_tfoot = null; /** * HTML_Table_Storage object for the (t)body of the table * @var object * @access private */ var $_tbody = null; /** * Whether to use , and or not * @var bool * @access private */ var $_useTGroups = false; /** * Class constructor * @param array $attributes Associative array of table tag attributes * @param int $tabOffset Tab offset of the table * @param bool $useTGroups Whether to use , and * or not * @access public */ function HTML_Table($attributes = null, $tabOffset = 0, $useTGroups = false) { $commonVersion = 1.7; if (HTML_Common::apiVersion() < $commonVersion) { return PEAR::raiseError('HTML_Table version ' . $this->apiVersion() . ' requires ' . "HTML_Common version $commonVersion or greater.", 0, PEAR_ERROR_TRIGGER); } HTML_Common::HTML_Common($attributes, (int)$tabOffset); $this->_useTGroups = (boolean)$useTGroups; $this->_tbody = new HTML_Table_Storage($attributes, $tabOffset, $this->_useTGroups); if ($this->_useTGroups) { $this->_thead = new HTML_Table_Storage($attributes, $tabOffset, $this->_useTGroups); $this->_tfoot = new HTML_Table_Storage($attributes, $tabOffset, $this->_useTGroups); } } /** * Returns the API version * @access public * @return double */ function apiVersion() { return 1.7; } /** * Returns the HTML_Table_Storage object for * @access public * @return object */ function &getHeader() { if (is_null($this->_thead)) { $this->_useTGroups = true; $this->_thead = new HTML_Table_Storage($this->_attributes, $this->_tabOffset, $this->_useTGroups); $this->_tbody->setUseTGroups(true); } return $this->_thead; } /** * Returns the HTML_Table_Storage object for * @access public * @return object */ function &getFooter() { if (is_null($this->_tfoot)) { $this->_useTGroups = true; $this->_tfoot = new HTML_Table_Storage($this->_attributes, $this->_tabOffset, $this->_useTGroups); $this->_tbody->setUseTGroups(true); } return $this->_tfoot; } /** * Returns the HTML_Table_Storage object for * (or the whole table if is not used) * @access public * @return object */ function &getBody() { return $this->_tbody; } /** * Sets the table caption * @param string $caption * @param mixed $attributes Associative array or string of table row attributes * @access public */ function setCaption($caption, $attributes = null) { $attributes = $this->_parseAttributes($attributes); $this->_caption = array('attr' => $attributes, 'contents' => $caption); } /** * Sets the table columns group specifications, or removes existing ones. * * @param mixed $colgroup (optional) Columns attributes * @param mixed $attributes (optional) Associative array or string * of table row attributes * @author Laurent Laville (pear at laurent-laville dot org) * @access public */ function setColGroup($colgroup = null, $attributes = null) { if (isset($colgroup)) { $attributes = $this->_parseAttributes($attributes); $this->_colgroup[] = array('attr' => $attributes, 'contents' => $colgroup); } else { $this->_colgroup = array(); } } /** * Sets the autoFill value * @param mixed $fill * @access public */ function setAutoFill($fill) { $this->_tbody->setAutoFill($fill); } /** * Returns the autoFill value * @access public * @return mixed */ function getAutoFill() { return $this->_tbody->getAutoFill(); } /** * Sets the autoGrow value * @param bool $fill * @access public */ function setAutoGrow($grow) { $this->_tbody->setAutoGrow($grow); } /** * Returns the autoGrow value * @access public * @return mixed */ function getAutoGrow() { return $this->_tbody->getAutoGrow(); } /** * Sets the number of rows in the table * @param int $rows * @access public */ function setRowCount($rows) { $this->_tbody->setRowCount($rows); } /** * Sets the number of columns in the table * @param int $cols * @access public */ function setColCount($cols) { $this->_tbody->setColCount($cols); } /** * Returns the number of rows in the table * @access public * @return int */ function getRowCount() { return $this->_tbody->getRowCount(); } /** * Gets the number of columns in the table * * If a row index is specified, the count will not take * the spanned cells into account in the return value. * * @param int Row index to serve for cols count * @access public * @return int */ function getColCount($row = null) { return $this->_tbody->getColCount($row); } /** * Sets a rows type 'TH' or 'TD' * @param int $row Row index * @param string $type 'TH' or 'TD' * @access public */ function setRowType($row, $type) { $this->_tbody->setRowType($row, $type); } /** * Sets a columns type 'TH' or 'TD' * @param int $col Column index * @param string $type 'TH' or 'TD' * @access public */ function setColType($col, $type) { $this->_tbody->setColType($col, $type); } /** * Sets the cell attributes for an existing cell. * * If the given indices do not exist and autoGrow is true then the given * row and/or col is automatically added. If autoGrow is false then an * error is returned. * @param int $row Row index * @param int $col Column index * @param mixed $attributes Associative array or string of table row attributes * @access public * @throws PEAR_Error */ function setCellAttributes($row, $col, $attributes) { $ret = $this->_tbody->setCellAttributes($row, $col, $attributes); if (PEAR::isError($ret)) { return $ret; } } /** * Updates the cell attributes passed but leaves other existing attributes in tact * @param int $row Row index * @param int $col Column index * @param mixed $attributes Associative array or string of table row attributes * @access public */ function updateCellAttributes($row, $col, $attributes) { $ret = $this->_tbody->updateCellAttributes($row, $col, $attributes); if (PEAR::isError($ret)) { return $ret; } } /** * Returns the attributes for a given cell * @param int $row Row index * @param int $col Column index * @return array * @access public */ function getCellAttributes($row, $col) { return $this->_tbody->getCellAttributes($row, $col); } /** * Sets the cell contents for an existing cell * * If the given indices do not exist and autoGrow is true then the given * row and/or col is automatically added. If autoGrow is false then an * error is returned. * @param int $row Row index * @param int $col Column index * @param mixed $contents May contain html or any object with a toHTML method; * if it is an array (with strings and/or objects), $col * will be used as start offset and the array elements * will be set to this and the following columns in $row * @param string $type (optional) Cell type either 'TH' or 'TD' * @access public * @throws PEAR_Error */ function setCellContents($row, $col, $contents, $type = 'TD') { $ret = $this->_tbody->setCellContents($row, $col, $contents, $type); if (PEAR::isError($ret)) { return $ret; } } /** * Returns the cell contents for an existing cell * @param int $row Row index * @param int $col Column index * @access public * @return mixed */ function getCellContents($row, $col) { return $this->_tbody->getCellContents($row, $col); } /** * Sets the contents of a header cell * @param int $row * @param int $col * @param mixed $contents * @param mixed $attributes Associative array or string of table row attributes * @access public */ function setHeaderContents($row, $col, $contents, $attributes = null) { $this->_tbody->setHeaderContents($row, $col, $contents, $attributes); } /** * Adds a table row and returns the row identifier * @param array $contents (optional) Must be a indexed array of valid cell contents * @param mixed $attributes (optional) Associative array or string of table row attributes * This can also be an array of attributes, in which case the attributes * will be repeated in a loop. * @param string $type (optional) Cell type either 'th' or 'td' * @param bool $inTR false if attributes are to be applied in TD tags * true if attributes are to be applied in TR tag * @return int * @access public */ function addRow($contents = null, $attributes = null, $type = 'td', $inTR = false) { $ret = $this->_tbody->addRow($contents, $attributes, $type, $inTR); return $ret; } /** * Sets the row attributes for an existing row * @param int $row Row index * @param mixed $attributes Associative array or string of table row attributes * This can also be an array of attributes, in which case the attributes * will be repeated in a loop. * @param bool $inTR false if attributes are to be applied in TD tags * true if attributes are to be applied in TR tag * @access public * @throws PEAR_Error */ function setRowAttributes($row, $attributes, $inTR = false) { $ret = $this->_tbody->setRowAttributes($row, $attributes, $inTR); if (PEAR::isError($ret)) { return $ret; } } /** * Updates the row attributes for an existing row * @param int $row Row index * @param mixed $attributes Associative array or string of table row attributes * @param bool $inTR false if attributes are to be applied in TD tags * true if attributes are to be applied in TR tag * @access public * @throws PEAR_Error */ function updateRowAttributes($row, $attributes = null, $inTR = false) { $ret = $this->_tbody->updateRowAttributes($row, $attributes, $inTR); if (PEAR::isError($ret)) { return $ret; } } /** * Returns the attributes for a given row as contained in the TR tag * @param int $row Row index * @return array * @access public */ function getRowAttributes($row) { return $this->_tbody->getRowAttributes($row); } /** * Alternates the row attributes starting at $start * @param int $start Row index of row in which alternating begins * @param mixed $attributes1 Associative array or string of table row attributes * @param mixed $attributes2 Associative array or string of table row attributes * @param bool $inTR false if attributes are to be applied in TD tags * true if attributes are to be applied in TR tag * @access public */ function altRowAttributes($start, $attributes1, $attributes2, $inTR = false) { $this->_tbody->altRowAttributes($start, $attributes1, $attributes2, $inTR); } /** * Adds a table column and returns the column identifier * @param array $contents (optional) Must be a indexed array of valid cell contents * @param mixed $attributes (optional) Associative array or string of table row attributes * @param string $type (optional) Cell type either 'th' or 'td' * @return int * @access public */ function addCol($contents = null, $attributes = null, $type = 'td') { return $this->_tbody->addCol($contents, $attributes, $type); } /** * Sets the column attributes for an existing column * @param int $col Column index * @param mixed $attributes (optional) Associative array or string of table row attributes * @access public */ function setColAttributes($col, $attributes = null) { $this->_tbody->setColAttributes($col, $attributes); } /** * Updates the column attributes for an existing column * @param int $col Column index * @param mixed $attributes (optional) Associative array or string of table row attributes * @access public */ function updateColAttributes($col, $attributes = null) { $this->_tbody->updateColAttributes($col, $attributes); } /** * Sets the attributes for all cells * @param mixed $attributes (optional) Associative array or string of table row attributes * @access public */ function setAllAttributes($attributes = null) { $this->_tbody->setAllAttributes($attributes); } /** * Updates the attributes for all cells * @param mixed $attributes (optional) Associative array or string of table row attributes * @access public */ function updateAllAttributes($attributes = null) { $this->_tbody->updateAllAttributes($attributes); } /** * Returns the table structure as HTML * @access public * @return string */ function toHtml() { $strHtml = ''; $tabs = $this->_getTabs(); $tab = $this->_getTab(); $lnEnd = $this->_getLineEnd(); if ($this->_comment) { $strHtml .= $tabs . "" . $lnEnd; } $strHtml .= $tabs . '_getAttrString($this->_attributes) . '>' . $lnEnd; if (!empty($this->_caption)) { $attr = $this->_caption['attr']; $contents = $this->_caption['contents']; $strHtml .= $tabs . $tab . '_getAttrString($attr) . '>'; if (is_array($contents)) { $contents = implode(', ', $contents); } $strHtml .= $contents; $strHtml .= '' . $lnEnd; } if (!empty($this->_colgroup)) { foreach ($this->_colgroup as $g => $col) { $attr = $this->_colgroup[$g]['attr']; $contents = $this->_colgroup[$g]['contents']; $strHtml .= $tabs . $tab . '_getAttrString($attr) . '>'; if (!empty($contents)) { $strHtml .= $lnEnd; if (!is_array($contents)) { $contents = array($contents); } foreach ($contents as $a => $colAttr) { $attr = $this->_parseAttributes($colAttr); $strHtml .= $tabs . $tab . $tab . '_getAttrString($attr) . '>' . $lnEnd; } $strHtml .= $tabs . $tab; } $strHtml .= '' . $lnEnd; } } if ($this->_useTGroups) { $tHeadColCount = 0; if ($this->_thead !== null) { $tHeadColCount = $this->_thead->getColCount(); } $tFootColCount = 0; if ($this->_tfoot !== null) { $tFootColCount = $this->_tfoot->getColCount(); } $tBodyColCount = 0; if ($this->_tbody !== null) { $tBodyColCount = $this->_tbody->getColCount(); } $maxColCount = max($tHeadColCount, $tFootColCount, $tBodyColCount); if ($this->_thead !== null) { $this->_thead->setColCount($maxColCount); if ($this->_thead->getRowCount() > 0) { $strHtml .= $tabs . $tab . '' . $lnEnd; $strHtml .= $this->_thead->toHtml($tabs, $tab); $strHtml .= $tabs . $tab . '' . $lnEnd; } } if ($this->_tfoot !== null) { $this->_tfoot->setColCount($maxColCount); if ($this->_tfoot->getRowCount() > 0) { $strHtml .= $tabs . $tab . '' . $lnEnd; $strHtml .= $this->_tfoot->toHtml($tabs, $tab); $strHtml .= $tabs . $tab . '' . $lnEnd; } } if ($this->_tbody !== null) { $this->_tbody->setColCount($maxColCount); if ($this->_tbody->getRowCount() > 0) { $strHtml .= $tabs . $tab . '' . $lnEnd; $strHtml .= $this->_tbody->toHtml($tabs, $tab); $strHtml .= $tabs . $tab . '' . $lnEnd; } } } else { $strHtml .= $this->_tbody->toHtml($tabs, $tab); } $strHtml .= $tabs . '' . $lnEnd; return $strHtml; } } ?>administrator/components/com_virtuemart/classes/PEAR/Table/Storage.php100644 0 0 67673 10547254314 23712 0ustar 0 0 ..., ... and .... * * PHP versions 4 * * LICENSE: This source file is subject to version 3.0 of the PHP license * that is available through the world-wide-web at the following URI: * http://www.php.net/license/3_0.txt. If you did not receive a copy of * the PHP License and are unable to obtain it through the web, please * send a note to license@php.net so we can mail you a copy immediately. * * @category HTML * @package HTML_Table * @author Adam Daniel * @author Bertrand Mansion * @copyright 2005 The PHP Group * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version CVS: $Id: Storage.php 617 2007-01-04 19:43:08Z soeren_nb $ * @link http://pear.php.net/package/HTML_Table */ /** * Storage class for HTML::Table data * * This class stores data for tables built with HTML_Table. When having * more than one instance, it can be used for grouping the table into the * parts ..., ... and .... * * @category HTML * @package HTML_Table * @author Adam Daniel * @author Bertrand Mansion * @author Mark Wiesemann * @copyright 2005 The PHP Group * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version Release: @package_version@ * @link http://pear.php.net/package/HTML_Table */ class HTML_Table_Storage extends HTML_Common { /** * Value to insert into empty cells * @var string * @access private */ var $_autoFill = ' '; /** * Automatically adds a new row or column if a given row or column index does not exist * @var bool * @access private */ var $_autoGrow = true; /** * Array containing the table structure * @var array * @access private */ var $_structure = array(); /** * Number of rows composing in the table * @var int * @access private */ var $_rows = 0; /** * Number of column composing the table * @var int * @access private */ var $_cols = 0; /** * Tracks the level of nested tables * @var int * @access private */ var $_nestLevel = 0; /** * Whether to use , and or not * @var bool * @access private */ var $_useTGroups = false; /** * Class constructor * @param array $attributes Associative array of table tag attributes * @param int $tabOffset * @param bool $useTGroups Whether to use , and * or not * @access public */ function HTML_Table_Storage($attributes = null, $tabOffset = 0, $useTGroups = false) { HTML_Common::HTML_Common($attributes, (int)$tabOffset); $this->_useTGroups = (boolean)$useTGroups; } /** * Sets the useTGroups value * @param boolean $useTGroups * @access public */ function setUseTGroups($useTGroups) { $this->_useTGroups = $useTGroups; } /** * Returns the useTGroups value * @access public * @return boolean */ function getUseTGroups() { return $this->_useTGroups; } /** * Sets the autoFill value * @param mixed $fill * @access public */ function setAutoFill($fill) { $this->_autoFill = $fill; } /** * Returns the autoFill value * @access public * @return mixed */ function getAutoFill() { return $this->_autoFill; } /** * Sets the autoGrow value * @param bool $fill * @access public */ function setAutoGrow($grow) { $this->_autoGrow = $grow; } /** * Returns the autoGrow value * @access public * @return mixed */ function getAutoGrow() { return $this->_autoGrow; } /** * Sets the number of rows in the table * @param int $rows * @access public */ function setRowCount($rows) { $this->_rows = $rows; } /** * Sets the number of columns in the table * @param int $cols * @access public */ function setColCount($cols) { $this->_cols = $cols; } /** * Returns the number of rows in the table * @access public * @return int */ function getRowCount() { return $this->_rows; } /** * Gets the number of columns in the table * * If a row index is specified, the count will not take * the spanned cells into account in the return value. * * @param int Row index to serve for cols count * @access public * @return int */ function getColCount($row = null) { if (!is_null($row)) { $count = 0; foreach ($this->_structure[$row] as $cell) { if (is_array($cell)) { $count++; } } return $count; } return $this->_cols; } /** * Sets a rows type 'TH' or 'TD' * @param int $row Row index * @param string $type 'TH' or 'TD' * @access public */ function setRowType($row, $type) { for ($counter = 0; $counter < $this->_cols; $counter++) { $this->_structure[$row][$counter]['type'] = $type; } } /** * Sets a columns type 'TH' or 'TD' * @param int $col Column index * @param string $type 'TH' or 'TD' * @access public */ function setColType($col, $type) { for ($counter = 0; $counter < $this->_rows; $counter++) { $this->_structure[$counter][$col]['type'] = $type; } } /** * Sets the cell attributes for an existing cell. * * If the given indices do not exist and autoGrow is true then the given * row and/or col is automatically added. If autoGrow is false then an * error is returned. * @param int $row Row index * @param int $col Column index * @param mixed $attributes Associative array or string of table row attributes * @access public * @throws PEAR_Error */ function setCellAttributes($row, $col, $attributes) { if (isset($this->_structure[$row][$col]) && $this->_structure[$row][$col] == '__SPANNED__') return; $attributes = $this->_parseAttributes($attributes); $err = $this->_adjustEnds($row, $col, 'setCellAttributes', $attributes); if (PEAR::isError($err)) { return $err; } $this->_structure[$row][$col]['attr'] = $attributes; $this->_updateSpanGrid($row, $col); } /** * Updates the cell attributes passed but leaves other existing attributes in tact * @param int $row Row index * @param int $col Column index * @param mixed $attributes Associative array or string of table row attributes * @access public */ function updateCellAttributes($row, $col, $attributes) { if (isset($this->_structure[$row][$col]) && $this->_structure[$row][$col] == '__SPANNED__') return; $attributes = $this->_parseAttributes($attributes); $err = $this->_adjustEnds($row, $col, 'updateCellAttributes', $attributes); if (PEAR::isError($err)) { return $err; } $this->_updateAttrArray($this->_structure[$row][$col]['attr'], $attributes); $this->_updateSpanGrid($row, $col); } /** * Returns the attributes for a given cell * @param int $row Row index * @param int $col Column index * @return array * @access public */ function getCellAttributes($row, $col) { if (isset($this->_structure[$row][$col]) && $this->_structure[$row][$col] != '__SPANNED__') { return $this->_structure[$row][$col]['attr']; } elseif (!isset($this->_structure[$row][$col])) { return PEAR::raiseError('Invalid table cell reference[' . $row . '][' . $col . '] in HTML_Table::getCellAttributes'); } return; } /** * Sets the cell contents for an existing cell * * If the given indices do not exist and autoGrow is true then the given * row and/or col is automatically added. If autoGrow is false then an * error is returned. * @param int $row Row index * @param int $col Column index * @param mixed $contents May contain html or any object with a toHTML method; * if it is an array (with strings and/or objects), $col * will be used as start offset and the array elements * will be set to this and the following columns in $row * @param string $type (optional) Cell type either 'TH' or 'TD' * @access public * @throws PEAR_Error */ function setCellContents($row, $col, $contents, $type = 'TD') { if (is_array($contents)) { foreach ($contents as $singleContent) { $ret = $this->_setSingleCellContents($row, $col, $singleContent, $type); if (PEAR::isError($ret)) { return $ret; } $col++; } } else { $ret = $this->_setSingleCellContents($row, $col, $contents, $type); if (PEAR::isError($ret)) { return $ret; } } } /** * Sets the cell contents for a single existing cell * * If the given indices do not exist and autoGrow is true then the given * row and/or col is automatically added. If autoGrow is false then an * error is returned. * @param int $row Row index * @param int $col Column index * @param mixed $contents May contain html or any object with a toHTML method; * if it is an array (with strings and/or objects), $col * will be used as start offset and the array elements * will be set to this and the following columns in $row * @param string $type (optional) Cell type either 'TH' or 'TD' * @access private * @throws PEAR_Error */ function _setSingleCellContents($row, $col, $contents, $type = 'TD') { if (isset($this->_structure[$row][$col]) && $this->_structure[$row][$col] == '__SPANNED__') return; $err = $this->_adjustEnds($row, $col, 'setCellContents'); if (PEAR::isError($err)) { return $err; } $this->_structure[$row][$col]['contents'] = $contents; $this->_structure[$row][$col]['type'] = $type; } /** * Returns the cell contents for an existing cell * @param int $row Row index * @param int $col Column index * @access public * @return mixed */ function getCellContents($row, $col) { if (isset($this->_structure[$row][$col]) && $this->_structure[$row][$col] == '__SPANNED__') return; if (!isset($this->_structure[$row][$col])) { return PEAR::raiseError('Invalid table cell reference[' . $row . '][' . $col . '] in HTML_Table::getCellContents'); } return $this->_structure[$row][$col]['contents']; } /** * Sets the contents of a header cell * @param int $row * @param int $col * @param mixed $contents * @param mixed $attributes Associative array or string of table row attributes * @access public */ function setHeaderContents($row, $col, $contents, $attributes = null) { $this->setCellContents($row, $col, $contents, 'TH'); if (!is_null($attributes)) { $this->updateCellAttributes($row, $col, $attributes); } } /** * Adds a table row and returns the row identifier * @param array $contents (optional) Must be a indexed array of valid cell contents * @param mixed $attributes (optional) Associative array or string of table row attributes * This can also be an array of attributes, in which case the attributes * will be repeated in a loop. * @param string $type (optional) Cell type either 'th' or 'td' * @param bool $inTR false if attributes are to be applied in TD tags * true if attributes are to be applied in TR tag * @return int * @access public */ function addRow($contents = null, $attributes = null, $type = 'td', $inTR = false) { if (isset($contents) && !is_array($contents)) { return PEAR::raiseError('First parameter to HTML_Table::addRow must be an array'); } if (is_null($contents)) { $contents = array(); } $type = strtolower($type); $row = $this->_rows++; foreach ($contents as $col => $content) { if ($type == 'td') { $this->setCellContents($row, $col, $content); } elseif ($type == 'th') { $this->setHeaderContents($row, $col, $content); } } $this->setRowAttributes($row, $attributes, $inTR); return $row; } /** * Sets the row attributes for an existing row * @param int $row Row index * @param mixed $attributes Associative array or string of table row attributes * This can also be an array of attributes, in which case the attributes * will be repeated in a loop. * @param bool $inTR false if attributes are to be applied in TD tags * true if attributes are to be applied in TR tag * @access public * @throws PEAR_Error */ function setRowAttributes($row, $attributes, $inTR = false) { if (!$inTR) { $multiAttr = $this->_isAttributesArray($attributes); for ($i = 0; $i < $this->_cols; $i++) { if ($multiAttr) { $this->setCellAttributes($row, $i, $attributes[$i - ((ceil(($i + 1) / count($attributes))) - 1) * count($attributes)]); } else { $this->setCellAttributes($row, $i, $attributes); } } } else { $attributes = $this->_parseAttributes($attributes); $err = $this->_adjustEnds($row, 0, 'setRowAttributes', $attributes); if (PEAR::isError($err)) { return $err; } $this->_structure[$row]['attr'] = $attributes; } } /** * Updates the row attributes for an existing row * @param int $row Row index * @param mixed $attributes Associative array or string of table row attributes * @param bool $inTR false if attributes are to be applied in TD tags * true if attributes are to be applied in TR tag * @access public * @throws PEAR_Error */ function updateRowAttributes($row, $attributes = null, $inTR = false) { if (!$inTR) { $multiAttr = $this->_isAttributesArray($attributes); for ($i = 0; $i < $this->_cols; $i++) { if ($multiAttr) { $this->updateCellAttributes($row, $i, $attributes[$i - ((ceil(($i + 1) / count($attributes))) - 1) * count($attributes)]); } else { $this->updateCellAttributes($row, $i, $attributes); } } } else { $attributes = $this->_parseAttributes($attributes); $err = $this->_adjustEnds($row, 0, 'updateRowAttributes', $attributes); if (PEAR::isError($err)) { return $err; } $this->_updateAttrArray($this->_structure[$row]['attr'], $attributes); } } /** * Returns the attributes for a given row as contained in the TR tag * @param int $row Row index * @return array * @access public */ function getRowAttributes($row) { if (isset($this->_structure[$row]['attr'])) { return $this->_structure[$row]['attr']; } return; } /** * Alternates the row attributes starting at $start * @param int $start Row index of row in which alternating begins * @param mixed $attributes1 Associative array or string of table row attributes * @param mixed $attributes2 Associative array or string of table row attributes * @param bool $inTR false if attributes are to be applied in TD tags * true if attributes are to be applied in TR tag * @access public */ function altRowAttributes($start, $attributes1, $attributes2, $inTR = false) { for ($row = $start ; $row < $this->_rows ; $row++) { $attributes = ( ($row + $start) % 2 == 0 ) ? $attributes1 : $attributes2; $this->updateRowAttributes($row, $attributes, $inTR); } } /** * Adds a table column and returns the column identifier * @param array $contents (optional) Must be a indexed array of valid cell contents * @param mixed $attributes (optional) Associative array or string of table row attributes * @param string $type (optional) Cell type either 'th' or 'td' * @return int * @access public */ function addCol($contents = null, $attributes = null, $type = 'td') { if (isset($contents) && !is_array($contents)) { return PEAR::raiseError('First parameter to HTML_Table::addCol must be an array'); } if (is_null($contents)) { $contents = array(); } $type = strtolower($type); $col = $this->_cols++; foreach ($contents as $row => $content) { if ($type == 'td') { $this->setCellContents($row, $col, $content); } elseif ($type == 'th') { $this->setHeaderContents($row, $col, $content); } } $this->setColAttributes($col, $attributes); return $col; } /** * Sets the column attributes for an existing column * @param int $col Column index * @param mixed $attributes (optional) Associative array or string of table row attributes * @access public */ function setColAttributes($col, $attributes = null) { $multiAttr = $this->_isAttributesArray($attributes); for ($i = 0; $i < $this->_rows; $i++) { if ($multiAttr) { $this->setCellAttributes($i, $col, $attributes[$i - ((ceil(($i + 1) / count($attributes))) - 1) * count($attributes)]); } else { $this->setCellAttributes($i, $col, $attributes); } } } /** * Updates the column attributes for an existing column * @param int $col Column index * @param mixed $attributes (optional) Associative array or string of table row attributes * @access public */ function updateColAttributes($col, $attributes = null) { $multiAttr = $this->_isAttributesArray($attributes); for ($i = 0; $i < $this->_rows; $i++) { if ($multiAttr) { $this->updateCellAttributes($i, $col, $attributes[$i - ((ceil(($i + 1) / count($attributes))) - 1) * count($attributes)]); } else { $this->updateCellAttributes($i, $col, $attributes); } } } /** * Sets the attributes for all cells * @param mixed $attributes (optional) Associative array or string of table row attributes * @access public */ function setAllAttributes($attributes = null) { for ($i = 0; $i < $this->_rows; $i++) { $this->setRowAttributes($i, $attributes); } } /** * Updates the attributes for all cells * @param mixed $attributes (optional) Associative array or string of table row attributes * @access public */ function updateAllAttributes($attributes = null) { for ($i = 0; $i < $this->_rows; $i++) { $this->updateRowAttributes($i, $attributes); } } /** * Returns the table rows as HTML * @access public * @return string */ function toHtml($tabs = null, $tab = null) { $strHtml = ''; if (is_null($tabs)) { $tabs = $this->_getTabs(); } if (is_null($tab)) { $tab = $this->_getTab(); } $lnEnd = $this->_getLineEnd(); if ($this->_useTGroups) { $extraTab = $tab; } else { $extraTab = ''; } for ($i = 0 ; $i < $this->_rows ; $i++) { $attr = ''; if (isset($this->_structure[$i]['attr'])) { $attr = $this->_getAttrString($this->_structure[$i]['attr']); } $strHtml .= $tabs .$tab . $extraTab . '' . $lnEnd; for ($j = 0 ; $j < $this->_cols ; $j++) { $attr = ''; $contents = ''; $type = 'td'; if (isset($this->_structure[$i][$j]) && $this->_structure[$i][$j] == '__SPANNED__') { $strHtml .= $tabs . $tab . $tab . $extraTab . '' . $lnEnd; continue; } if (isset($this->_structure[$i][$j]['type'])) { $type = (strtolower($this->_structure[$i][$j]['type']) == 'th' ? 'th' : 'td'); } if (isset($this->_structure[$i][$j]['attr'])) { $attr = $this->_structure[$i][$j]['attr']; } if (isset($this->_structure[$i][$j]['contents'])) { $contents = $this->_structure[$i][$j]['contents']; } $strHtml .= $tabs . $tab . $tab . $extraTab . "<$type" . $this->_getAttrString($attr) . '>'; if (is_object($contents)) { // changes indent and line end settings on nested tables if (is_subclass_of($contents, 'html_common')) { $contents->setTab($tab . $extraTab); $contents->setTabOffset($this->_tabOffset + 3); $contents->_nestLevel = $this->_nestLevel + 1; $contents->setLineEnd($this->_getLineEnd()); } if (method_exists($contents, 'toHtml')) { $contents = $contents->toHtml(); } elseif (method_exists($contents, 'toString')) { $contents = $contents->toString(); } } if (is_array($contents)) { $contents = implode(', ', $contents); } if (isset($this->_autoFill) && $contents === '') { $contents = $this->_autoFill; } $strHtml .= $contents; $strHtml .= "" . $lnEnd; } $strHtml .= $tabs . $tab . $extraTab . '' . $lnEnd; } return $strHtml; } /** * Checks if rows or columns are spanned * @param int $row Row index * @param int $col Column index * @access private */ function _updateSpanGrid($row, $col) { if (isset($this->_structure[$row][$col]['attr']['colspan'])) { $colspan = $this->_structure[$row][$col]['attr']['colspan']; } if (isset($this->_structure[$row][$col]['attr']['rowspan'])) { $rowspan = $this->_structure[$row][$col]['attr']['rowspan']; } if (isset($colspan)) { for ($j = $col + 1; (($j < $this->_cols) && ($j <= ($col + $colspan - 1))); $j++) { $this->_structure[$row][$j] = '__SPANNED__'; } } if (isset($rowspan)) { for ($i = $row + 1; (($i < $this->_rows) && ($i <= ($row + $rowspan - 1))); $i++) { $this->_structure[$i][$col] = '__SPANNED__'; } } if (isset($colspan) && isset($rowspan)) { for ($i = $row + 1; (($i < $this->_rows) && ($i <= ($row + $rowspan - 1))); $i++) { for ($j = $col + 1; (($j <= $this->_cols) && ($j <= ($col + $colspan - 1))); $j++) { $this->_structure[$i][$j] = '__SPANNED__'; } } } } /** * Adjusts ends (total number of rows and columns) * @param int $row Row index * @param int $col Column index * @param string $method Method name of caller * Used to populate PEAR_Error if thrown. * @param array $attributes Assoc array of attributes * Default is an empty array. * @access private * @throws PEAR_Error */ function _adjustEnds($row, $col, $method, $attributes = array()) { $colspan = isset($attributes['colspan']) ? $attributes['colspan'] : 1; $rowspan = isset($attributes['rowspan']) ? $attributes['rowspan'] : 1; if (($row + $rowspan - 1) >= $this->_rows) { if ($this->_autoGrow) { $this->_rows = $row + $rowspan; } else { return PEAR::raiseError('Invalid table row reference[' . $row . '] in HTML_Table::' . $method); } } if (($col + $colspan - 1) >= $this->_cols) { if ($this->_autoGrow) { $this->_cols = $col + $colspan; } else { return PEAR::raiseError('Invalid table column reference[' . $col . '] in HTML_Table::' . $method); } } } /** * Tells if the parameter is an array of attribute arrays/strings * @param mixed $attributes Variable to test * @access private * @return bool */ function _isAttributesArray($attributes) { if (is_array($attributes) && isset($attributes[0])) { if (is_array($attributes[0]) || (is_string($attributes[0]) && count($attributes) > 1)) { return true; } } return false; } } ?>administrator/components/com_virtuemart/classes/PEAR/Table/index.html100644 0 0 0 11026265061 23427 0ustar 0 0 administrator/components/com_virtuemart/classes/PEAR/index.html100644 0 0 0 11026265061 22400 0ustar 0 0 administrator/components/com_virtuemart/classes/class.img2thumb.php100644 0 0 23660 11227154424 23513 0ustar 0 0 * @author Patrick Teague * @author Soeren Eberhardt *@version 1.0b *@date modified 11/22/2004 *@modifications * - added support for GDLib < 2.0.1 * - added support for reading gif images * - makes jpg thumbnails * - changed several groups of 'if' statements to single 'switch' statements * - commented out original code so modification could be identified. */ class Img2Thumb { // New modification /** * private variables - do not use * * @var int $bg_red 0-255 - red color variable for background filler * @var int $bg_green 0-255 - green color variable for background filler * @var int $bg_blue 0-255 - blue color variable for background filler * @var int $maxSize 0-1 - true/false - should thumbnail be filled to max pixels */ var $bg_red; var $bg_green; var $bg_blue; var $maxSize; /** * @var string Filename for the thumbnail */ var $fileout; /** * Constructor - requires following vars: * * @param string $filename image path * * These are additional vars: * * @param int $newxsize new maximum image width * @param int $newysize new maximum image height * @param string $fileout output image path * @param int $thumbMaxSize whether thumbnail should have background fill to make it exactly $newxsize x $newysize * @param int $bgred 0-255 - red color variable for background filler * @param int $bggreen 0-255 - green color variable for background filler * @param int $bgblue 0-255 - blue color variable for background filler * */ function Img2Thumb($filename, $newxsize=60, $newysize=60, $fileout='', $thumbMaxSize=0, $bgred=0, $bggreen=0, $bgblue=0) { // New modification - checks color int to be sure within range if($thumbMaxSize) { $this->maxSize = true; } else { $this->maxSize = false; } if($bgred>=0 || $bgred<=255) { $this->bg_red = $bgred; } else { $this->bg_red = 0; } if($bggreen>=0 || $bggreen<=255) { $this->bg_green = $bggreen; } else { $this->bg_green = 0; } if($bgblue>=0 || $bgblue<=255) { $this->bg_blue = $bgblue; } else { $this->bg_blue = 0; } $this->NewImgCreate($filename,$newxsize,$newysize,$fileout); } /** * * private function - do not call * */ function NewImgCreate($filename,$newxsize,$newysize,$fileout) { $type = $this->GetImgType($filename); $pathinfo = pathinfo( $fileout ); if( empty( $pathinfo['extension'])) { $fileout .= '.'.$type; } $this->fileout = $fileout; // get some memory vmRaiseMemoryLimit( '32M' ); switch($type) { case "gif": // unfortunately this function does not work on windows // via the precompiled php installation :( // it should work on all other systems however. if( function_exists("imagecreatefromgif") ) { $orig_img = imagecreatefromgif($filename); break; } else { echo 'Sorry, this server doesn\'t support imagecreatefromgif()'; exit; break; } case "jpg": $orig_img = imagecreatefromjpeg($filename); break; case "png": $orig_img = imagecreatefrompng($filename); break; } $new_img =$this->NewImgResize($orig_img,$newxsize,$newysize,$filename); if (!empty($fileout)) { $this-> NewImgSave($new_img,$fileout,$type); } else { $this->NewImgShow($new_img,$type); } ImageDestroy($new_img); ImageDestroy($orig_img); } /** * * private function - do not call * includes function ImageCreateTrueColor and ImageCopyResampled which are available only under GD 2.0.1 or higher ! */ function NewImgResize($orig_img,$newxsize,$newysize,$filename) { //getimagesize returns array // [0] = width in pixels // [1] = height in pixels // [2] = type // [3] = img tag "width=xx height=xx" values $orig_size = getimagesize($filename); $maxX = $newxsize; $maxY = $newysize; if (($orig_size[0]*$maxY)<($orig_size[1]*$maxX)) { $newxsize = $newysize * ($orig_size[0]/$orig_size[1]); $adjustX = ($maxX - $newxsize)/2; $adjustY = 0; } else { $newysize = $newxsize / ($orig_size[0]/$orig_size[1]); $adjustX = 0; $adjustY = ($maxY - $newysize)/2; } /* Original code removed to allow for maxSize thumbnails $im_out = ImageCreateTrueColor($newxsize,$newysize); ImageCopyResampled($im_out, $orig_img, 0, 0, 0, 0, $newxsize, $newysize,$orig_size[0], $orig_size[1]); */ // New modification - creates new image at maxSize if( $this->maxSize ) { if( function_exists("imagecreatetruecolor") ) $im_out = imagecreatetruecolor($maxX,$maxY); else $im_out = imagecreate($maxX,$maxY); // Need to image fill just in case image is transparent, don't always want black background $bgfill = imagecolorallocate( $im_out, $this->bg_red, $this->bg_green, $this->bg_blue ); if( function_exists( "imageAntiAlias" )) { imageAntiAlias($im_out,true); } imagealphablending($im_out, false); if( function_exists( "imagesavealpha")) { imagesavealpha($im_out,true); } if( function_exists( "imagecolorallocatealpha")) { $transparent = imagecolorallocatealpha($im_out, 255, 255, 255, 127); } //imagefill( $im_out, 0,0, $bgfill ); if( function_exists("imagecopyresampled") ){ ImageCopyResampled($im_out, $orig_img, $adjustX, $adjustY, 0, 0, $newxsize, $newysize,$orig_size[0], $orig_size[1]); } else { ImageCopyResized($im_out, $orig_img, $adjustX, $adjustY, 0, 0, $newxsize, $newysize,$orig_size[0], $orig_size[1]); } } else { if( function_exists("imagecreatetruecolor") ) $im_out = ImageCreateTrueColor($newxsize,$newysize); else $im_out = imagecreate($newxsize,$newysize); if( function_exists( "imageAntiAlias" )) imageAntiAlias($im_out,true); imagealphablending($im_out, false); if( function_exists( "imagesavealpha")) imagesavealpha($im_out,true); if( function_exists( "imagecolorallocatealpha")) $transparent = imagecolorallocatealpha($im_out, 255, 255, 255, 127); if( function_exists("imagecopyresampled") ) ImageCopyResampled($im_out, $orig_img, 0, 0, 0, 0, $newxsize, $newysize,$orig_size[0], $orig_size[1]); else ImageCopyResized($im_out, $orig_img, 0, 0, 0, 0, $newxsize, $newysize,$orig_size[0], $orig_size[1]); } return $im_out; } /** * * private function - do not call * */ function NewImgSave($new_img,$fileout,$type) { if( !@is_dir( dirname($fileout))) { @mkdir( dirname($fileout) ); } switch($type) { case "gif": if( !function_exists("imagegif") ) { if (strtolower(substr($fileout,strlen($fileout)-4,4))!=".gif") { $fileout .= ".png"; } return imagepng($new_img,$fileout); } else { if (strtolower(substr($fileout,strlen($fileout)-4,4))!=".gif") { $fileout .= '.gif'; } return imagegif( $new_img, $fileout ); } break; case "jpg": if (strtolower(substr($fileout,strlen($fileout)-4,4))!=".jpg") $fileout .= ".jpg"; return imagejpeg($new_img, $fileout, 100); break; case "png": if (strtolower(substr($fileout,strlen($fileout)-4,4))!=".png") $fileout .= ".png"; return imagepng($new_img,$fileout); break; } } /** * * private function - do not call * */ function NewImgShow($new_img,$type) { /* Original code removed in favor of 'switch' statement if ($type=="png") { header ("Content-type: image/png"); return imagepng($new_img); } if ($type=="jpg") { header ("Content-type: image/jpeg"); return imagejpeg($new_img); } */ switch($type) { case "gif": if( function_exists("imagegif") ) { header ("Content-type: image/gif"); return imagegif($new_img); break; } else $this->NewImgShow( $new_img, "jpg" ); case "jpg": header ("Content-type: image/jpeg"); return imagejpeg($new_img); break; case "png": header ("Content-type: image/png"); return imagepng($new_img); break; } } /** * * private function - do not call * * 1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, * 5 = PSD, 6 = BMP, * 7 = TIFF(intel byte order), * 8 = TIFF(motorola byte order), * 9 = JPC, 10 = JP2, 11 = JPX, * 12 = JB2, 13 = SWC, 14 = IFF */ function GetImgType($filename) { $info = getimagesize($filename); /* Original code removed in favor of 'switch' statement if($size[2]==2) return "jpg"; elseif($size[2]==3) return "png"; */ switch($info[2]) { case 1: return "gif"; break; case 2: return "jpg"; break; case 3: return "png"; break; default: return false; } } } ?> administrator/components/com_virtuemart/classes/connectionTools.class.php100644 0 0 25512 11256702557 25003 0ustar 0 0 debug( 'Using the cURL library for communicating with '.$urlParts['host'] ); $CR = curl_init(); curl_setopt($CR, CURLOPT_URL, $url); // just to get sure the script doesn't die curl_setopt($CR, CURLOPT_TIMEOUT, 30 ); if( !empty( $headers )) { // Add additional headers if provided curl_setopt($CR, CURLOPT_HTTPHEADER, $headers); } curl_setopt($CR, CURLOPT_FAILONERROR, true); if( $postData ) { curl_setopt($CR, CURLOPT_POSTFIELDS, $postData ); curl_setopt($CR, CURLOPT_POST, 1); } if( is_resource($fileToSaveData)) { curl_setopt($CR, CURLOPT_FILE, $fileToSaveData ); } else { curl_setopt($CR, CURLOPT_RETURNTRANSFER, 1); } // Do we need to set up the proxy? if( !empty($proxyURL) ) { $vmLogger->debug( 'Setting up proxy: '.$proxyURL['host'].':'.VM_PROXY_PORT ); //curl_setopt($CR, CURLOPT_HTTPPROXYTUNNEL, true); curl_setopt($CR, CURLOPT_PROXY, $proxyURL['host'] ); curl_setopt($CR, CURLOPT_PROXYPORT, VM_PROXY_PORT ); // Check if the proxy needs authentication if( trim( @VM_PROXY_USER ) != '') { $vmLogger->debug( 'Using proxy authentication!' ); curl_setopt($CR, CURLOPT_PROXYUSERPWD, VM_PROXY_USER.':'.VM_PROXY_PASS ); } } if( $urlParts['scheme'] == 'https') { // No PEER certificate validation...as we don't have // a certificate file for it to authenticate the host www.ups.com against! curl_setopt($CR, CURLOPT_SSL_VERIFYPEER, 0); //curl_setopt($CR, CURLOPT_SSLCERT , "/usr/locale/xxxx/clientcertificate.pem"); } $result = curl_exec( $CR ); $error = curl_error( $CR ); if( !empty( $error ) && stristr( $error, '502') && !empty( $proxyURL )) { $vmLogger->debug( 'Switching to NTLM authenticaton.'); curl_setopt( $CR, CURLOPT_PROXYAUTH, CURLAUTH_NTLM ); $result = curl_exec( $CR ); $error = curl_error( $CR ); } curl_close( $CR ); if( !empty( $error )) { $vmLogger->err( $error ); return false; } else { return $result; } } else { if( $postData ) { if( !empty( $proxyURL )) { // If we have something to post we need to write into a socket if( $proxyURL['scheme'] == 'https'){ $protocol = 'ssl'; } else { $protocol = 'http'; } $fp = fsockopen("$protocol://".$proxyURL['host'], VM_PROXY_PORT, $errno, $errstr, $timeout = 30); } else { // If we have something to post we need to write into a socket if( $urlParts['scheme'] == 'https'){ $protocol = 'ssl'; } else { $protocol = $urlParts['scheme']; } $fp = fsockopen("$protocol://".$urlParts['host'], $urlParts['port'], $errno, $errstr, $timeout = 30); } } else { if( !empty( $proxyURL )) { // Do a read-only fopen transaction $fp = fopen( $proxyURL['scheme'].'://'.$proxyURL['host'].':'.VM_PROXY_PORT, 'rb' ); } else { // Do a read-only fopen transaction $fp = @fopen( $urlParts['scheme'].'://'.$urlParts['host'].':'.$urlParts['port'].$urlParts['path'], 'rb' ); } } if(!$fp){ //error, plesae tell us which one $errmsg = "Possible server error!"; if( !empty($errstr )) { $errmsg .= " - $errstr ($errno)\n"; } $vmLogger->err( $errmsg ); return false; } else { $vmLogger->debug( 'Connection opened to '.$urlParts['host']); } if( $postData ) { $vmLogger->debug('Now posting the variables.' ); //send the server request if( !empty( $proxyURL )) { fputs($fp, "POST ".$urlParts['host'].':'.$urlParts['port'].$urlParts['path']." HTTP/1.0\r\n"); fputs($fp, "Host: ".$proxyURL['host']."\r\n"); if( trim( @VM_PROXY_USER )!= '') { fputs($fp, "Proxy-Authorization: Basic " . base64_encode (VM_PROXY_USER.':'.VM_PROXY_PASS ) . "\r\n\r\n"); } } else { fputs($fp, 'POST '.$urlParts['path']." HTTP/1.0\r\n"); fputs($fp, 'Host:'. $urlParts['host']."\r\n"); } fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n"); fputs($fp, "Content-length: ".strlen($postData)."\r\n"); fputs($fp, "Connection: close\r\n\r\n"); fputs($fp, $postData . "\r\n\r\n"); } else { if( !empty( $proxyURL )) { fputs($fp, "GET ".$urlParts['host'].':'.$urlParts['port'].$urlParts['path']." HTTP/1.0\r\n"); fputs($fp, "Host: ".$proxyURL['host']."\r\n"); if( trim( @VM_PROXY_USER )!= '') { fputs($fp, "Proxy-Authorization: Basic " . base64_encode (VM_PROXY_USER.':'.VM_PROXY_PASS ) . "\r\n\r\n"); } } else { fputs($fp, 'GET '.$urlParts['path']." HTTP/1.0\r\n"); fputs($fp, 'Host:'. $urlParts['host']."\r\n"); } } // Add additional headers if provided foreach( $headers as $header ) { fputs($fp, $header."\r\n"); } $data = ""; while (!feof($fp)) { $data .= @fgets ($fp, 4096); } fclose( $fp ); // If didnt get content-lenght, something is wrong, return false. if ( trim($data) == '' ) { $vmLogger->err('An error occured while communicating with the server '.$urlParts['host'].'. It didn\'t reply (correctly). Please try again later, thank you.' ); return false; } $result = trim( $data ); if( is_resource($fileToSaveData )) { fwrite($fileToSaveData, $result ); return true; } else { return $result; } } } /** * Set headers and send the file to the client * * @author Andreas Gohr * @param string The full path to the file * @param string The Mime Type of the file */ function sendFile($file,$mime, $overrideFileName=''){ global $vm_mainframe; // send headers header("Content-Type: $mime"); list($start,$len) = vmConnector::http_rangeRequest(filesize($file)); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Accept-Ranges: bytes'); //application mime type is downloadable if(strtolower(substr($mime,0,11)) == 'application'){ if( $overrideFileName == '') { $filename = basename($file); } else { $filename = $overrideFileName; } header('Content-Disposition: attachment; filename="'.$filename.'";'); } $chunksize = 1*(1024*1024); // send file contents $fp = @fopen($file,"rb"); if($fp){ fseek($fp,$start); //seek to start of range $chunk = ($len > $chunksize) ? $chunksize : $len; while (!feof($fp) && $chunk > 0) { @set_time_limit(0); // large files can take a lot of time print fread($fp, $chunk); flush(); $len -= $chunk; $chunk = ($len > $chunksize) ? $chunksize : $len; } fclose($fp); }else{ header("HTTP/1.0 500 Internal Server Error"); print "Could not read $file - bad permissions?"; $vm_mainframe->close(true); } } /** * Checks and sets headers to handle range requets * * @author Andreas Gohr * @return array The start byte and the amount of bytes to send * @param int The file size */ function http_rangeRequest($size, $exitOnError=true ){ global $vm_mainframe; if(!isset($_SERVER['HTTP_RANGE'])){ // no range requested - send the whole file header("Content-Length: $size"); return array(0,$size); } $t = explode('=', $_SERVER['HTTP_RANGE']); if (!$t[0]=='bytes') { // we only understand byte ranges - send the whole file header("Content-Length: $size"); return array(0,$size); } $r = explode('-', $t[1]); $start = (int)$r[0]; $end = (int)$r[1]; if (!$end) $end = $size - 1; if ($start > $end || $start > $size || $end > $size){ if( $exitOnError ) { header('HTTP/1.1 416 Requested Range Not Satisfiable'); print 'Bad Range Request!'; $vm_mainframe->close(true); } else { return array(0,$size); } } $tot = $end - $start + 1; header('HTTP/1.1 206 Partial Content'); header("Content-Range: bytes {$start}-{$end}/{$size}"); header("Content-Length: $tot"); return array($start,$tot); } } ?>administrator/components/com_virtuemart/classes/currency/class_currency_display.php100644 0 0 16655 11141402617 27110 0ustar 0 0 id = $id; $this->symbol = $symbol; $this->nbDecimal = $nbDecimal; $this->decimal = $decimal; $this->thousands = $thousands; $this->positivePos = $positivePos; $this->negativePos = $negativePos; } // ================ function getSymbol(){ return($this->symbol); } // ================ function getId(){ return($this->id); } // ================ function getValue($nb, $decimals=''){ $res = ""; // Warning ! number_format function performs implicit rounding // Rounding is not handled in this DISPLAY class // that's why you have to use the right decimal value. // Workaround :number_format accepts either 1, 2 or 4 parameters. // this cause problem when no thousands separator is given : in this // case, an unwanted ',' is displayed. // That's why we have to do the work ourserlve. // Note : when no decimal il given (i.e. 3 parameters), everything works fine if( $decimals === '') { $decimals = $this->nbDecimal; } if ($this->thousands != ''){ $res=number_format($nb,$decimals,$this->decimal,$this->thousands); } else { // If decimal is equal to defaut thousand separator, apply a trick if ($this->decimal==','){ $res=number_format($nb,$decimals,$this->decimal,'|'); $res=str_replace('|','',$res); } else { // Else a simple substitution is enough $res=number_format($nb,$decimals,$this->decimal,$this->thousands); $res=str_replace(',','',$res); } } return($res); } // ================ function getFullValue($nb, $decimals='', $symbol = '') { global $vendor_currency; $res = ""; if( $symbol != '' ) { $old_symbol = $this->symbol; $this->symbol = $symbol; } switch($this->symbol) { case 'USD': $this->symbol='$';break; case 'EUR': $this->symbol='€';break; case 'GBP': $this->symbol='£';break; case 'JPY': $this->symbol='¥';break; case 'AUD': $this->symbol='AUD $';break; case 'CAD': $this->symbol='CAD $';break; case 'HKD': $this->symbol='HKD $';break; case 'NZD': $this->symbol='NZD $';break; case 'SGD': $this->symbol='SGD $';break; } // Currency symbol position if ($nb == abs($nb)){ $res=$this->getValue($nb, $decimals); // Positive number switch ($this->positivePos){ case 0: // 0 = '00Symb' $res=$res.$this->symbol; break; case 2: // 2 = 'Symb00' $res=$this->symbol.$res; break; case 3: // 3 = 'Symb 00' $res=$this->symbol.' '.$res; break; case 1: default : // 1 = '00 Symb' $res=$res.' '.$this->symbol; break; } } else { // Negative number $res=$this->getValue(abs($nb), $decimals); switch ($this->negativePos){ case 0: // 0 = '(Symb00)' $res='('.$this->symbol.$res.')'; break; case 1: // 1 = '-Symb00' $res='-'.$this->symbol.$res; break; case 2: // 2 = 'Symb-00' $res=$this->symbol.'-'.$res; break; case 3: // 3 = 'Symb00-' $res=$this->symbol.$res.'-'; break; case 4: // 4 = '(00Symb)' $res='('.$res.$this->symbol.')'; break; case 5: // 5 = '-00Symb' $res='-'.$res.$this->symbol; break; case 6: // 6 = '00-Symb' $res=$res.'-'.$this->symbol; break; case 7: // 7 = '00Symb-' $res=$res.$this->symbol.'-'; break; case 9: // 9 = '-Symb 00' $res='-'.$this->symbol.' '.$res; break; case 10: // 10 = '00 Symb-' $res=$res.' '.$this->symbol.'-'; break; case 11: // 11 = 'Symb 00-' $res=$this->symbol.' '.$res.'-'; break; case 12: // 12 = 'Symb -00' $res=$this->symbol.' -'.$res; break; case 13: // 13 = '00- Symb' $res=$res.'- '.$this->symbol; break; case 14: // 14 = '(Symb 00)' $res='('.$this->symbol.' '.$res.')'; break; case 15: // 15 = '(00 Symb)' $res='('.$res.' '.$this->symbol.')'; break; case 8: default : // 8 = '-00 Symb' $res='-'.$res.' '.$this->symbol; break; } } if( $symbol != '' ) { $this->symbol = $old_symbol; } return($res); } // ================ /CURRENCY DISPLAY ========================= // ============================================================ } // end class } ?> administrator/components/com_virtuemart/classes/currency/convertECB.php100644 0 0 14037 11260665051 24333 0ustar 0 0 document_address; $val = ''; if(file_exists($archivefile_name) && filesize( $archivefile_name ) > 0 ) { // timestamp for the Filename $file_datestamp = date('Ymd', filemtime($archivefile_name)); // check if today is a weekday - no updates on weekends if( date( 'w' ) > 0 && date( 'w' ) < 6 // compare filedate and actual date && $file_datestamp != $date_now_local // if localtime is greater then ecb-update-time go on to update and write files && $time_now_local > $time_ecb_update) { $curr_filename = $ecb_filename; } else { $curr_filename = $archivefile_name; $this->last_updated = $file_datestamp; $this->archive = false; } } else { $curr_filename = $ecb_filename; } if( !is_writable( $store_path )) { $this->archive = false; $vmLogger->debug( "The file $archivefile_name can't be created. The directory $store_path is not writable" ); } if( $curr_filename == $ecb_filename ) { // Fetch the file from the internet require_once( CLASSPATH.'connectionTools.class.php'); $contents = vmConnector::handleCommunication( $curr_filename ); $this->last_updated = date('Ymd'); } else { $contents = @file_get_contents( $curr_filename ); } if( $contents ) { // if archivefile does not exist if( $this->archive ) { // now write new file file_put_contents( $archivefile_name, $contents ); } $contents = str_replace (" parseXML( $contents, false, true ) ) { $vmLogger->err( 'Failed to parse the Currency Converter XML document.'); $_SESSION['product_currency'] = $GLOBALS['product_currency'] = $vendor_currency; return false; } $currency_list = $xmlDoc->getElementsByTagName( "Cube" ); // Loop through the Currency List for ($i = 0; $i < $currency_list->getLength(); $i++) { $currNode =& $currency_list->item($i); $currency[$currNode->getAttribute("currency")] = $currNode->getAttribute("rate"); unset( $currNode ); } $GLOBALS['converter_array'] = $currency; } else { $GLOBALS['converter_array'] = -1; $vmLogger->err( 'Failed to retrieve the Currency Converter XML document.'); $_SESSION['product_currency'] = $GLOBALS['product_currency'] = $vendor_currency; return false; } } return true; } /** * Converts an amount from one currency into another using * the rate conversion table from the European Central Bank * * @param float $amountA * @param string $currA defaults to $vendor_currency * @param string $currB defaults to $GLOBALS['product_currency'] (and that defaults to $vendor_currency) * @return mixed The converted amount when successful, false on failure */ function convert( $amountA, $currA='', $currB='' ) { global $vendor_currency; // global $vendor_currency is DEFAULT! if( !$currA ) { $currA = $vendor_currency; } if( !$currB ) { $currB = $GLOBALS['product_currency']; } // If both currency codes match, do nothing if( $currA == $currB ) { return $amountA; } if( !$this->init()) { $GLOBALS['product_currency'] = $vendor_currency; return $amountA; } $valA = isset( $GLOBALS['converter_array'][$currA] ) ? $GLOBALS['converter_array'][$currA] : 1; $valB = isset( $GLOBALS['converter_array'][$currB] ) ? $GLOBALS['converter_array'][$currB] : 1; $val = $amountA * $valB / $valA; //$vmLogger->debug('Converted '.$amountA.' '.$currA.' to '.$val.' '.$currB); return $val; } // end function convertecb } ?> administrator/components/com_virtuemart/classes/currency/index.html100644 0 0 0 11026265061 23503 0ustar 0 0 administrator/components/com_virtuemart/classes/euvatcheck.class.php100644 0 0 11270 11254654365 23742 0ustar 0 0 '', 'vatNumber' => ''); /** @var array contains the data to pass to the VIES */ var $validvatid = false; /** @var boolean whether or not the field should be processed */ var $output = false; function VmEUVatCheck($uservatid) { global $vmLogger; /* Load the SOAP library */ require_once('nusoap/nusoap.php'); /* Check for proxy settings */ if( trim( @VM_PROXY_URL ) != '') { if( !stristr(VM_PROXY_URL, 'http')) { $proxyURL['host'] = VM_PROXY_URL; $proxyURL['scheme'] = 'http'; } else $proxyURL = parse_url(VM_PROXY_URL); } else $proxyURL = ''; /* Use the proxy and initialise the client */ if( !empty($proxyURL) ) { $vmLogger->debug( 'Setting up proxy: '.$proxyURL['host'].':'.VM_PROXY_PORT ); /* Proxy without authentication */ $this->client = new nusoap_client($this->viesurl, true, $proxyURL['host'], VM_PROXY_PORT); /* proxy with authentication */ if( trim( @VM_PROXY_USER ) != '') { $vmLogger->debug( 'Using proxy authentication!' ); $this->client = new nusoap_client($this->viesurl, true, $proxyURL['host'], VM_PROXY_PORT, VM_PROXY_USER, VM_PROXY_PASS); } } /* Do not use the proxy and initialise the client */ else { $this->client = new nusoap_client($this->viesurl, true); } /* Check if there is no error on initialisation */ $err = $this->client->getError(); /* We have an error, return false since we can't check the VAT ID */ if ($err) { return false; } else { /* See if we can use cURL */ if (function_exists( 'curl_init' ) && function_exists( 'curl_exec' )) $this->client->setUseCurl(true); /* Set the parameters to pass to VIES */ $countrycode = substr($uservatid, 0, 2); $vatnumber = substr($uservatid, 2); $param = array('countryCode' => $countrycode, 'vatNumber' => $vatnumber); /* Call the VIES to check the VAT ID */ $this->client->call('checkVat', $param); /* Check if anything has gone wrong */ if ($this->client->fault) { $vmLogger->debug( 'There was a problem with the VAT ID Check!' ); return false; } else { /* See if we received an error */ if ($this->client->getError()) { // There was an error, return false as we cannot check the VAT ID $vmLogger->debug( $this->client->getError() ); return false; } /* We have a valid response, process the response */ else { $vmLogger->debug( 'EU VAT ID Check completed.' ); /* Strip all garbage before the actual XML content */ $xmltxt = trim(substr($this->client->response, strpos ($this->client->response, 'parser = xml_parser_create(); xml_set_object($this->parser,$this); xml_set_element_handler($this->parser,"startElement","endElement"); xml_set_character_data_handler($this->parser, "characterData"); xml_parse($this->parser, $xmltxt); xml_parser_free($this->parser); /* Data is processed, return the outcome */ // return $this->validvatid; } } } } /** * What to do when the parser finds a start element * * @param $parser object * @param $element_name string name of the element found */ function startElement($parser, $element_name, $attributes) { switch($element_name) { case "VALID" : $this->output = true; break; default: $this->output = false; break; } } /** * What to do when the parser finds a closing element * * @param $parser object * @param $element_name string name of the element found */ function endElement($parser, $element_name) { } /** * What to do when the parser finds data in the element * * @param $parser object * @param $xml_data string data found in between tags */ function characterData($parser, $xml_data) { if ($this->output) { if ($xml_data) { if ($xml_data == "false") $this->validvatid = false; else if ($xml_data == "true") $this->validvatid = true; } $this->output = false; } } } ?> administrator/components/com_virtuemart/classes/htmlTools.class.php100644 0 0 152152 11254672536 23632 0ustar 0 0 writeSearchHeader($VM_LANG->_('PHPSHOP_PRODUCT_LIST_LBL'), IMAGEURL."ps_image/product_code.png", $modulename, "product_list"); * * // start the list table * $listObj->startTable(); * * // these are the columns in the table * $columns = Array( "#" => "width=\"20\"", * "" => "width=\"20\"",* * $VM_LANG->_('PHPSHOP_PRODUCT_LIST_NAME') => '', * $VM_LANG->_('PHPSHOP_PRODUCT_LIST_SKU') => '', * _E_REMOVE => "width=\"5%\"" * ); * $listObj->writeTableHeader( $columns ); * * ###BEGIN LOOPING THROUGH RECORDS ########## * * $listObj->newRow(); * * // The row number * $listObj->addCell( $pageNav->rowNumber( $i ) ); * * // The Checkbox * $listObj->addCell( mosHTML::idBox( $i, $db->f("product_id"), false, "product_id" ) ); * ... * ###FINISH THE RECENT LOOP######## * $listObj->addCell( $ps_html->deleteButton( "product_id", $db->f("product_id"), "productDelete", $keyword, $limitstart ) ); * * $i++; * * #### * $listObj->writeTable(); * $listObj->endTable(); * $listObj->writeFooter( $keyword ); * * @package VirtueMart * @subpackage Classes * @author soeren */ class listFactory { /** @var int the number of columns in the table */ var $columnCount = 0; /** @var array css classes for alternating rows (row0 and row1 ) */ var $alternateColors; /** @var int The column number */ var $x = -1; /** @var int The row number */ var $y = -1; /** @var array The table cells */ var $cells = Array(); /** @var vmPageNavigation The Page Navigation Object */ var $pageNav; /** @var int The smallest number of results that shows the page navigation */ var $_resultsToShowPageNav = 6; function listFactory( $pageNav=null ) { if( defined('_VM_IS_BACKEND')) { $this->alternateColors = array( 0 => 'row0', 1 => 'row1' ); } else { $this->alternateColors = array( 0 => 'sectiontableentry1', 1 => 'sectiontableentry2' ); } $this->pageNav = $pageNav; } /** * Writes the start of the button bar table */ function startTable() { ?> columnCount = intval( $columnNames ); else { $this->columnCount = count( $columnNames ); echo ''; foreach( $columnNames as $name => $attributes ) { $name = html_entity_decode( $name ); echo "\n"; } echo "\n"; } } /** * Adds a new row to the list * * @param string $class The additional CSS class name * @param string $id The ID of the HTML tr element * @param string $attributes Additional HTML attributes for the tr element */ function newRow( $class='', $id='', $attributes='') { $this->y++; $this->x = 0; if( $class != '') { $this->cells[$this->y]['class'] = $class; } if( $id != '') { $this->cells[$this->y]['id'] = $id; } if( $attributes != '' ) { $this->cells[$this->y]['attributes'] = $attributes; } } function addCell( $data, $attributes="" ) { $this->cells[$this->y][$this->x]["data"] = $data; $this->cells[$this->y][$this->x]["attributes"] = $attributes; $this->x++; } /** * Writes a table row with data * Array * $row[0]["data"] = "Cell Value"; * $row[0]["attributes"] = "align=\"center\""; */ function writeTable() { if( !is_array( $this->cells )) return false; else { $i = 0; foreach( $this->cells as $row ) { echo "alternateColors[$i]; if( !empty($row['class'])) { echo ' '.$row['class']; } echo '"'; if( !empty($row['id'])) { echo ' id="'.$row['id'].'" '; } if( !empty($row['attributes'])) { echo $row['attributes']; } echo ">\n"; foreach( $row as $cell ) { if( $cell["data"] == 'i' || !isset( $cell["data"] ) || !is_array($cell)) continue; $value = $cell["data"]; $attributes = $cell["attributes"]; echo "\n"; } echo "\n"; $i == 0 ? $i++ : $i--; } } } function endTable() { echo "
$name
$value
\n"; } /** * This creates a header above the list table, containing a search box * @param The Label for the list (will be used as list heading!) * @param The core module name (e.g. "product") * @param The page name (e.g. "product_list" ) * @param Additional varaibles to include as hidden input fields */ function writeSearchHeader( $title, $image="", $modulename, $pagename) { global $sess, $keyword, $VM_LANG; if( !empty( $keyword )) { $keyword = urldecode( $keyword ); } else { $keyword = ""; } $search_date = vmGet( $_REQUEST, 'search_date', null); $show = vmGet( $_REQUEST, "show", "" ); $header = ''; $header .= ' '; if( defined( "_VM_IS_BACKEND") || @$_REQUEST['pshop_mode'] == "admin" ) { $header .= "\n"; } if(( $title != "" ) || !empty( $pagename )) { $header .= ''; if( $title != "" ) { $style = ($image != '') ? 'style="background:url('.$image.') no-repeat;text-indent: 30px;line-height: 50px;"' : ''; $header .= ''."\n"; $GLOBALS['vm_mainframe']->setPageTitle( $title ); } if( !empty( $pagename )) $header .= ''; $header .= "\n

'.$title.'


\n"; } if ( !empty($search_date) ) // Changed search by date $header .= ''; if( !empty($show) ) { $header .= "\n"; } echo $header; } /** * This creates a list footer (page navigation) * @param The core module name (e.g. "product") * @param The page name (e.g. "product_list" ) * @param The Keyword from a search by keyword * @param Additional varaibles to include as hidden input fields */ function writeFooter($keyword, $extra="") { $footer= ""; if( $this->pageNav !== null ) { if( $this->_resultsToShowPageNav <= $this->pageNav->total ) { $footer = $this->pageNav->getListFooter(); } } else { $footer = ""; } if(!empty( $extra )) { $extrafields = explode("&", $extra); array_shift($extrafields); foreach( $extrafields as $key => $value) { $field = explode("=", $value); $footer .= ''."\n"; } } $footer .= ''; echo $footer; } } /** * This is the class for creating regular forms used in VirtueMart * * Usage: * //First create the object and let it print a form heading * $formObj = &new formFactory( "My Form" ); * //Then Start the form * $formObj->startForm(); * // Add necessary hidden fields * $formObj->hiddenField( 'country_id', $country_id ); * * // Write your form with mixed tags and text fields * // and finally close the form: * $formObj->finishForm( $funcname, $modulename.'.country_list' ); * * @package virtuemart * @subpackage Core * @author soeren */ class formFactory { /** * Constructor * Prints the Form Heading if provided */ function formFactory( $title = '' ) { if( $title != "" ) { echo '

'.$title."

\n"; $GLOBALS['vm_mainframe']->setPageTitle( $title ); } } /** * Writes the form start tag */ function startForm( $formname = 'adminForm', $extra = "" ) { $action = (!defined('_VM_IS_BACKEND' ) && !empty($_REQUEST['next_page'])) ? 'index.php' : $_SERVER['PHP_SELF']; echo '
'; } function hiddenField( $name, $value ) { echo ' '; } /** * Writes necessary hidden input fields * and closes the form */ function finishForm( $func, $page='' ) { $no_menu = vmRequest::getInt('no_menu'); $html = ' '; if( $no_menu ) { $html .= ''; } else { $html .= ''; } $html .= ''; $html .= ''; $html .= ''; if( defined( "_VM_IS_BACKEND") || @$_REQUEST['pshop_mode'] == "admin" ) { $html .= ''; } $html .= '
'; echo $html; } } /** * Tab Creation handler * @package VirtueMart * @subpackage core * @author soeren * Modified to use Panel-in-Panel functionality */ class vmTabPanel { /** @var int Use cookies */ var $useCookies = 0; /** @var string Panel ID */ var $panel_id; var $tabs; /** * Constructor * Includes files needed for displaying tabs and sets cookie options * @param int useCookies, if set to 1 cookie will hold last used tab between page refreshes * @param int show_js, if set to 1 the Javascript Link and Stylesheet will not be printed */ function vmTabPanel($useCookies, $show_js, $panel_id) { vmCommonHTML::loadExtjs(); $this->useCookies = $useCookies; $this->panel_id = $panel_id; $this->tabs = array(); } /** * creates a tab pane and creates JS obj * @param string The Tab Pane Name */ function startPane($id) { echo '
'; $this->pane_id = $id; } /** * Ends Tab Pane */ function endPane() { echo "
"; $scripttag = " tabinit_{$this->panel_id} = function() { Ext.QuickTips.init(); var state = Ext.state.Manager; var tabs_{$this->panel_id} = new Ext.TabPanel({ renderTo: '{$this->pane_id}', activeTab: 0, deferredRender: false, enableTabScroll: true, autoScroll: true, listeners : { 'beforerender' : { fn: function() { $$('textarea.mce_editable').each(function(elem) { if(tinyMCE.get(elem.id)) tinyMCE.execCommand('mceRemoveControl',false,elem.id);}) } }, 'afterrender' : { fn: function() { $$('textarea.mce_editable').each(function(elem) { tinyMCE.execCommand('mceAddControl',false,elem.id);}) }, scope: this } }, autoWidth: true, items: ["; $num = 0; $numTabs = count( $this->tabs ); foreach ( $this->tabs as $id => $title ) { $scripttag .= "{ autoHeight: true, contentEl: '$id', title: '".addslashes($title)."' , tabTip: '".addslashes(strip_tags($title))."' }"; $num++; if( $num < $numTabs ) { $scripttag .= ",\n"; } } $scripttag .= "] });"; reset($this->tabs); if( $this->useCookies ) { $scripttag .= "tabs_{$this->panel_id}.activate(state.get('{$this->panel_id}-active', '".key($this->tabs)."'));"; } else { $scripttag .= "tabs_{$this->panel_id}.activate( '".key($this->tabs)."'); "; } if( $this->useCookies ) { $scripttag .= " Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); tabs_{$this->panel_id}.on('tabchange', function(tp, tab){ state.set('{$this->panel_id}-active', tab.id); }); "; } $scripttag .= "}; if( Ext.isIE6 || Ext.isIE7 ) { Ext.EventManager.addListener( window, 'load', tabinit_{$this->panel_id} ); } else { Ext.onReady( tabinit_{$this->panel_id} ); } "; echo vmCommonHTML::scriptTag('', $scripttag ); } /* * Creates a tab with title text and starts that tabs page * @param tabText - This is what is displayed on the tab * @param paneid - This is the parent pane to build this tab on */ function startTab( $tabText, $paneid ) { echo "
"; $this->tabs[$paneid] = $tabText; } /* * Ends a tab page */ function endTab() { echo "
"; } } class mShopTabs extends vmTabPanel { } class vmMooAjax { /** * This is used to print out Javascript code for the moo.ajax script * * @param string $url * @param string $updateId * @param string $onComplete A JS function name to be called after the HTTP transport has been finished * @param array VM_COMPONENT_NAMEs * @param string $varName The name of a variable the ajax object is assigned to */ function writeAjaxUpdater( $url, $updateId, $onComplete, $method='post', $vmDirs=array(), $varName='' ) { echo vmMooAjax::getAjaxUpdater($url, $updateId, $onComplete, $methods, $vmDirs, $varName); } function getAjaxUpdater( $url, $updateId, $onComplete, $method='post', $vmDirs=array(), $varName='' ) { global $mosConfig_live_site; vmCommonHTML::loadMooTools(); $path = defined('_VM_IS_BACKEND' ) ? '/administrator/' : '/'; $vmDirs['method'] = $method; $html = ''; if( $varName ) { $html .= 'var '.$varName.' = '; } if( !strstr( $url, $mosConfig_live_site) && !strstr($url, 'http' )) { $url = $mosConfig_live_site.$path.$url; } $html .= "new ajax('$url', {\n"; foreach (VM_COMPONENT_NAMEs as $key => $val) { if( strstr( $val, '.')) { $html .= "$key: $val,\n"; } else { $html .= "$key: '$val',\n"; } } if( $updateId != '' ) { $html .= "update: '$updateId'"; if( $onComplete ) { $html .= ",\n"; } } if( $onComplete ) { $html .= "onComplete: $onComplete"; } $html .= ' });'; return $html; } } /** * This is the class offering functions for common HTML tasks * */ class vmCommonHTML { /** * function to create a hyperlink * * @param string $link * @param string $text * @param string $target * @param string $title * @param string $attributes * @return string */ function hyperLink( $link, $text, $target='', $title='', $attributes='' ) { if( $target ) { $target = ' target="'.$target.'"'; } if( $title ) { $title = ' title="'.$title.'"'; } if( $attributes ) { $attributes = ' ' . $attributes; } return ''.$text.''; } /** * Function to create an image tag * * @param string $src * @param string $alt * @param int $height * @param int $width * @param string $title * @param int $border * @param string $attributes * @return string */ function imageTag( $src, $alt='', $align='', $height='', $width='', $title='', $border='0', $attributes='' ) { if( $align ) { $align = ' align="'.$align.'"'; } if( $height ) { $height = ' height="'.$height.'"'; } if( $width ) { $width = ' width="'.$width.'"'; } if( $title ) { $title = ' title="'.$title.'"'; } if( $attributes ) { $attributes = ' ' . $attributes; } if( strpos($attributes, 'border=')===false) { $border = ' border="'.$border.'"'; } // Prevent doubled attributes if( strpos($attributes, 'alt=')===false) { $alt = ' alt="'.$alt.'"'; } return ''; } /** * Returns a properly formatted XHTML List * * @param array $listitems * @param string $type Can be ul, ol, ... * @param string $style * @return string */ function getList( $listitems, $type = 'ul', $style='' ) { if( $style ) { $style = 'style="'.$style.'"'; } $html = '<' . $type ." $style>\n"; foreach( $listitems as $item ) { $html .= '
  • ' . $item . "
  • \n"; } $html .= '\n"; return $html; } /** * Returns a script tag. The referenced script will be fetched by a * PHP script called "fetchscript.php" * That allows use gzip compression, so bigger Javascripts don't steal our bandwith * * @param string $src The script src reference * @param string $content A Javascript Text to include in a script tag * @return string */ function scriptTag( $src='', $content = '' ) { global $mosConfig_gzip, $mosConfig_live_site; if( $src == '' && $content == '' ) return; if( $src ) { if( isset( $_REQUEST['usefetchscript'])) { $use_fetchscript = vmRequest::getBool( 'usefetchscript', 1 ); vmRequest::setVar( 'usefetchscript', $use_fetchscript, 'session' ); } else { $use_fetchscript = vmRequest::getBool( 'usefetchscript', 1, 'session' ); } $url_params = ''; if( stristr( $src, 'com_virtuemart' ) && !stristr( $src, '.php' ) && $use_fetchscript ) { $urlpos = strpos( $src, '?' ); if( $urlpos ) { $url_params = '&'.substr( $src, $urlpos ); $src = substr( $src, 0, $urlpos); } $base_source = str_replace( URL, '', $src ); $base_source = str_replace( SECUREURL, '', $base_source ); $base_source = str_replace( '/components/com_virtuemart', '', $base_source); $base_source = str_replace( 'components/com_virtuemart', '', $base_source); $src = $mosConfig_live_site.'/components/com_virtuemart/fetchscript.php?gzip='.$mosConfig_gzip.'&subdir[0]='.dirname( $base_source ) . '&file[0]=' . basename( $src ); } return ''."\n"; } if( $content ) { return "\n"; } } /** * Returns a link tag * * @param string $href * @param string $type * @param string $rel * @return string */ function linkTag( $href, $type='text/css', $rel = 'stylesheet', $media="screen, projection" ) { global $mosConfig_gzip, $mosConfig_live_site; if( isset( $_REQUEST['usefetchscript'])) { $use_fetchscript = vmRequest::getBool( 'usefetchscript', 1 ); vmRequest::setVar( 'usefetchscript', $use_fetchscript, 'session' ); } else { $use_fetchscript = vmRequest::getBool( 'usefetchscript', 1, 'session' ); } if( stristr( $href, 'com_virtuemart' ) && $use_fetchscript) { $base_href = str_replace( URL, '', $href ); $base_href = str_replace( SECUREURL, '', $base_href ); $base_href = str_replace( 'components/com_virtuemart/', '', $base_href); $href = $mosConfig_live_site.'/components/com_virtuemart/fetchscript.php?gzip='.$mosConfig_gzip.'&subdir[0]='.dirname( $base_href ) . '&file[0]=' . basename( $href ); } return ''."\n"; } /** * Writes a "Save Ordering" Button * @param int the number of rows */ function getSaveOrderButton( $num_rows, $funcname='reorder') { global $mosConfig_live_site, $VM_LANG; $n = $num_rows-1; $html = ' '.$VM_LANG->_('VM_SORT_SAVE_ORDER').''; $html .= ' '.$VM_LANG->_('VM_SORT_ALPHA').''; return $html; } function getOrderingField( $ordering ) { return ''; } function getYesNoIcon( $condition, $pos_alt = "Published", $neg_alt = "Unpublished" ) { global $mosConfig_live_site; if( $condition===true || strtoupper( $condition ) == "Y" || $condition == '1' ) { return ''.$pos_alt.''; } else { return ''.$neg_alt.''; } } /** * @param int The row index * @param int The record id * @param boolean * @param string The name of the form element * @return string */ function idBox( $rowNum, $recId, $checkedOut=false, $name='cid' ) { if ( $checkedOut ) { return ''; } else { return ''; } } /** * Manipulates an array and fills the $index with selected="selected" * Indexes within $disableArr will be filled with disabled="disabled" * * @param array $arr * @param int $index * @param string $att * @param array $disableArr */ function setSelectedArray( &$arr, $index, $att='selected', $disableArr=array() ) { if( !isset($arr[$index])) { return; } foreach( $arr as $key => $val ) { $arr[$key] = ''; if( $key == $index ) { $arr[$key] = $att.'="'.$att.'"'; } elseif( in_array( $key, $disableArr )) { $arr[$key] = 'disabled="disabled"'; } } } /** * tests for template/default pathway arrow separator * @author FTW Stroker * @static * @return string The separator for the pathway breadcrumbs */ function pathway_separator() { global $vm_mainframe,$mainframe, $mosConfig_absolute_path, $mosConfig_live_site; $imgPath = 'templates/' . $mainframe->getTemplate() . '/images/arrow.png'; if (file_exists( "$mosConfig_absolute_path/$imgPath" )){ $img = 'arrow'; } else { $imgPath = '/images/M_images/arrow.png'; if (file_exists( $mosConfig_absolute_path . $imgPath )){ $img = 'arrow'; } else { $img = '>'; } } return $img; } /** * Function to include the MooTools JS scripts in the HTML document * http://mootools.net * @static * @since VirtueMart 1.1.0 * */ function loadMooTools( $version='' ) { global $mosConfig_live_site, $vm_mainframe, $VM_LANG; if( !defined( "_MOOTOOLS_LOADED" )) { if( $version == '' ) { $version = 'mootools-release-1.11.js'; } $vm_mainframe->addScriptDeclaration( 'var cart_title = "'.$VM_LANG->_('PHPSHOP_CART_TITLE').'";var ok_lbl="'.$VM_LANG->_('CMN_CONTINUE').'";var cancel_lbl="'.$VM_LANG->_('CMN_CANCEL').'";var notice_lbl="'.$VM_LANG->_('PEAR_LOG_NOTICE').'";var live_site="'.$mosConfig_live_site.'";' ); $vm_mainframe->addScript( $mosConfig_live_site .'/components/'. VM_COMPONENT_NAME .'/js/mootools/'.$version ); $vm_mainframe->addScript( $mosConfig_live_site .'/components/'. VM_COMPONENT_NAME .'/js/mootools/mooPrompt.js' ); $vm_mainframe->addStyleSheet( $mosConfig_live_site .'/components/'. VM_COMPONENT_NAME .'/js/mootools/mooPrompt.css' ); define ( "_MOOTOOLS_LOADED", "1" ); } } /** * Function to load the javascript and stylsheet files for Slimbox, * a Lightbox derivate with mootools and prototype.lite * @author http://www.digitalia.be/software/slimbox * * @param boolean $print */ function loadSlimBox( ) { global $mosConfig_live_site, $vm_mainframe; if( !defined( '_SLIMBOX_LOADED' )) { vmCommonHTML::loadMooTools(); $vm_mainframe->addScriptDeclaration( 'var slimboxurl = \''.$mosConfig_live_site.'/components/'. VM_COMPONENT_NAME .'/js/slimbox/\';'); $vm_mainframe->addScript( $mosConfig_live_site .'/components/'. VM_COMPONENT_NAME .'/js/slimbox/js/slimbox.js' ); $vm_mainframe->addStyleSheet( $mosConfig_live_site .'/components/'. VM_COMPONENT_NAME .'/js/slimbox/css/slimbox.css' ); define ( '_SLIMBOX_LOADED', '1' ); } } /** * Loads the CSS and Javascripts needed to run the Greybox * Source: http://orangoo.com/labs/?page_id=5 * */ function loadGreybox( ) { global $mosConfig_live_site, $vm_mainframe; if( !defined( '_GREYBOX_LOADED' )) { $vm_mainframe->addScriptDeclaration( 'var GB_ROOT_DIR = \''.$mosConfig_live_site .'/components/'. VM_COMPONENT_NAME .'/js/greybox/\';', 'top' ); $vm_mainframe->addScript( $mosConfig_live_site .'/components/'. VM_COMPONENT_NAME .'/js/greybox/AJS.js' ); $vm_mainframe->addScript( $mosConfig_live_site .'/components/'. VM_COMPONENT_NAME .'/js/greybox/AJS_fx.js' ); $vm_mainframe->addScript( $mosConfig_live_site .'/components/'. VM_COMPONENT_NAME .'/js/greybox/gb_scripts.js' ); $vm_mainframe->addStyleSheet( $mosConfig_live_site .'/components/'. VM_COMPONENT_NAME .'/js/greybox/gb_styles.css' ); define ( '_GREYBOX_LOADED', '1' ); } } /** * Loads all necessary script files for Tigra Tree Menu * @static * @since VirtueMart 1.1.0 */ function loadTigraTree( ) { global $mosConfig_live_site, $vm_mainframe; if( !defined( "_TIGRATREE_LOADED" )) { if( vmIsJoomla( '1.5' )) { $js_src = $mosConfig_live_site.'/modules/mod_virtuemart'; } else { $js_src = $mosConfig_live_site.'/modules'; } $vm_mainframe->addScript( $js_src .'/tigratree/tree_tpl.js.php' ); $vm_mainframe->addScript( $js_src .'/tigratree/tree.js' ); define ( "_TIGRATREE_LOADED", "1" ); } } function loadYUI( ) { global $mosConfig_live_site, $vm_mainframe; if( !defined( "_YUI_LOADED" )) { $vm_mainframe->addScript( $mosConfig_live_site .'/components/'. VM_COMPONENT_NAME .'/js/extjs2/yui-utilities.js' ); define ( "_YUI_LOADED", "1" ); } } function loadExtjs() { global $mosConfig_live_site, $vm_mainframe; vmCommonHTML::loadYUI(); if( !defined( "_EXTJS_LOADED" )) { $vm_mainframe->addScript( $mosConfig_live_site .'/components/'. VM_COMPONENT_NAME .'/js/extjs2/yui-utilities.js' ); $vm_mainframe->addScript( $mosConfig_live_site .'/components/'. VM_COMPONENT_NAME .'/js/extjs2/ext-yui-adapter.js' ); $vm_mainframe->addScript( $mosConfig_live_site .'/components/'. VM_COMPONENT_NAME .'/js/extjs2/ext-all.js' ); $vm_mainframe->addScriptDeclaration( 'Ext.BLANK_IMAGE_URL = "'.$mosConfig_live_site.'/components/'. VM_COMPONENT_NAME .'/js/extjs2/images/default/s.gif";', 'bottom' ); $vm_mainframe->addStyleSheet( $mosConfig_live_site .'/components/'. VM_COMPONENT_NAME .'/js/extjs2/css/ext-all.css' ); $vm_mainframe->addStyleSheet( $mosConfig_live_site .'/components/'. VM_COMPONENT_NAME .'/js/extjs2/css/xtheme-gray.css' ); define ( "_EXTJS_LOADED", "1" ); } } /** * Returns a properly formatted image link that opens a LightBox2/Slimbox * * @param string $image_link Can be the image src or a complete image tag * @param string $text The Link Text, e.g. 'Click here!' * @param string $title The Link title, will be used as Image Caption * @param string $image_group The image group name when you want to use the gallery functionality * @param string $mootools Set to 'true' if you're using slimbox or another MooTools based image viewing library * @return string */ function getLightboxImageLink( $image_link, $text, $title='', $image_group='' ) { vmCommonHTML::loadSlimBox(); if( $image_group ) { $image_group = '['.$image_group.']'; } $link = vmCommonHTML::hyperLink( $image_link, $text, '', $title, 'rel="lightbox'.$image_group.'"' ); return $link; } function getGreyboxPopUpLink( $url, $text, $target='_blank', $title='', $attributes='', $height=500, $width=600, $no_js_url='' ) { vmCommonHTML::loadGreybox(); if( $no_js_url == '') { $no_js_url = $url; } $link = vmCommonHTML::hyperLink( $no_js_url, $text, $target, $title, $attributes.' onclick="try{ if( !parent.GB ) return GB_showCenter(\''.$title.'\', \''.$url.'\', '.$height.', '.$width.');} catch(e) { }"' ); return $link; } /** * Returns a div element of the class "shop_error" * containing $msg to print out an error * * @param string $msg * @return string HTML code */ function getInfoField( $msg ) { $html = '
    '.$msg.'
    '; return $html; } /** * Returns a div element to indicate success or failure of a function execution after an ajax call * and a div element with all the log messages * * @param boolean $success * @param vmLog_Display $vmLogger */ function getSuccessIndicator( $success, $vmDisplayLogger ) { /*@MWM1*/ echo ''; echo '
    '; $vmDisplayLogger->printLog(); /*@MWM1: Log/Debug enhancements*/ echo '
    '; } /** * Returns a div element of the class "shop_error" * containing $msg to print out an error * * @param string $msg * @return string HTML code */ function getErrorField( $msg ) { $html = '
    '.$msg.'
    '; return $html; } /** * Writes a PDF icon * * @param string $link * @param boolean $use_icon */ function PdfIcon( $link, $use_icon=true ) { global $VM_LANG, $mosConfig_live_site; if ( PSHOP_PDF_BUTTON_ENABLE == '1' && !vmGet( $_REQUEST, 'pop' ) ) { $link .= '&pop=1'; if ( $use_icon ) { $text = vmCommonHTML::ImageCheck( 'pdf_button.png', '/images/M_images/', NULL, NULL, $VM_LANG->_('CMN_PDF'), $VM_LANG->_('CMN_PDF') ); } else { $text = $VM_LANG->_('CMN_PDF') .' '; } return vmPopupLink($link, $text, 640, 480, '_blank', $VM_LANG->_('CMN_PDF')); } } /** * Writes an Email icon * * @param string $link * @param boolean $use_icon */ function EmailIcon( $product_id, $use_icon=true ) { global $VM_LANG, $mosConfig_live_site, $sess; if ( @VM_SHOW_EMAILFRIEND == '1' && !vmGet( $_REQUEST, 'pop' ) && $product_id > 0 ) { $link = $sess->url( 'index2.php?page=shop.recommend&product_id='.$product_id.'&pop=1'.(vmIsJoomla('1.5') ? '&tmpl=component' : '') ); if ( $use_icon ) { $text = vmCommonHTML::ImageCheck( 'emailButton.png', '/images/M_images/', NULL, NULL, $VM_LANG->_('CMN_EMAIL'), $VM_LANG->_('CMN_EMAIL') ); } else { $text = ' '. $VM_LANG->_('CMN_EMAIL'); } return vmPopupLink($link, $text, 640, 480, '_blank', $VM_LANG->_('CMN_EMAIL'), 'screenX=100,screenY=200'); } } function PrintIcon( $link='', $use_icon=true, $add_text='' ) { global $VM_LANG, $mosConfig_live_site, $mosConfig_absolute_path, $cur_template, $Itemid; if ( @VM_SHOW_PRINTICON == '1' ) { if( !$link ) { $query_string = str_replace( 'only_page=1', 'only_page=0', vmAmpReplace(vmGet($_SERVER,'QUERY_STRING')) ); $link = 'index2.php?'.$query_string.'&pop=1'.(vmIsJoomla('1.5') ? '&tmpl=component' : ''); } // checks template image directory for image, if non found default are loaded if ( $use_icon ) { $text = vmCommonHTML::ImageCheck( 'printButton.png', '/images/M_images/', NULL, NULL, $VM_LANG->_('CMN_PRINT'), $VM_LANG->_('CMN_PRINT') ); $text .= shopMakeHtmlSafe($add_text); } else { $text = '| '. $VM_LANG->_('CMN_PRINT'). ' |'; } $isPopup = vmGet( $_GET, 'pop' ); if ( $isPopup ) { // Print Preview button - used when viewing page $html = ' '. $text .' '; return $html; } else { // Print Button - used in pop-up window return vmPopupLink($link, $text, 640, 480, '_blank', $VM_LANG->_('CMN_PRINT')); } } } /** * Checks to see if an image exists in the current templates image directory * if it does it loads this image. Otherwise the default image is loaded. * Also can be used in conjunction with the menulist param to create the chosen image * load the default or use no image */ function ImageCheck( $file, $directory='/images/M_images/', $param=NULL, $param_directory='/images/M_images/', $alt=NULL, $name=NULL, $type=1, $align='middle', $title=NULL, $admin=NULL ) { global $mosConfig_absolute_path, $mosConfig_live_site, $mainframe; $cur_template = $mainframe->getTemplate(); $name = ( $name ? ' name="'. $name .'"' : '' ); $title = ( $title ? ' title="'. $title .'"' : '' ); $alt = ( $alt ? ' alt="'. $alt .'"' : ' alt=""' ); $align = ( $align ? ' align="'. $align .'"' : '' ); // change directory path from frontend or backend if ($admin) { $path = '/administrator/templates/'. $cur_template .'/images/'; } else { $path = '/templates/'. $cur_template .'/images/'; } if ( $param ) { $image = $mosConfig_live_site. $param_directory . $param; if ( $type ) { $image = ''; } } else if ( $param == -1 ) { $image = ''; } else { if ( file_exists( $mosConfig_absolute_path . $path . $file ) ) { $image = $mosConfig_live_site . $path . $file; } else { // outputs only path to image $image = $mosConfig_live_site. $directory . $file; } // outputs actual html tag if ( $type ) { $image = ''; } } return $image; } /** * this function parses all the text through all content plugins * * @param string $text * @param string $type */ function ParseContentByPlugins( $text, $type = 'content' ) { global $_MAMBOTS; if( VM_CONTENT_PLUGINS_ENABLE == '1') { if( vmIsJoomla('1.0')) { $_MAMBOTS->loadBotGroup( $type ); $row = new stdClass(); $row->text = $text; $params = new mosParameters(''); $_MAMBOTS->trigger( 'onPrepareContent', array( &$row, &$params, 0 ), true ); $text = $row->text; } elseif( vmIsJoomla('1.5')) { $params =& $GLOBALS['mainframe']->getParams('com_content'); $dispatcher =& JDispatcher::getInstance(); JPluginHelper::importPlugin($type); $row = new stdClass(); $row->text = $text; $results = $dispatcher->trigger('onPrepareContent', array (&$row, & $params, 0 )); $text = $row->text; } } return $text; } /** * This class allows us to create fieldsets like in Community builder * @author Copyright 2004 - 2005 MamboJoe/JoomlaJoe, Beat and CB team * * @param array $arr * @param string $tag_name * @param string $tag_attribs * @param string $key * @param string $text * @param mixed $selected * @param mixed $required * @return string HTML form code */ // begin class vmCommonHTML extends mosHTML { function radioListArr( &$arr, $tag_name, $tag_attribs, $key, $text, $selected, $required=0 ) { reset( $arr ); $html = array(); $n=count( $arr ); for ($i=0; $i < $n; $i++ ) { $k = stripslashes($arr[$i]->$key); $t = stripslashes($arr[$i]->$text); $id = isset($arr[$i]->id) ? $arr[$i]->id : null; $extra = ''; $extra .= $id ? " id=\"" . $arr[$i]->id . "\"" : ''; if (is_array( $selected )) { foreach ($selected as $obj) { $k2 = stripslashes($obj->$key); if ($k == $k2) { $extra .= " checked=\"checked\""; break; } } } else { $extra .= ($k == stripslashes($selected) ? " checked=\"checked\"" : ''); } $html[] = " " . ""; } return $html; } function radioList( $arr, $tag_name, $tag_attribs, $key, $text, $selected, $required=0 ) { return "\n\t".implode("\n\t ", vmCommonHTML::radioListArr( $arr, $tag_name, $tag_attribs, $key, $text, $selected, $required ))."\n"; } function radioListTable( $arr, $tag_name, $tag_attribs, $key, $text, $selected, $cols=0, $rows=1, $size=0, $required=0 ) { $cellsHtml = vmCommonHTML::radioListArr( $arr, $tag_name, $tag_attribs, $key, $text, $selected, $required ); return vmCommonHTML::list2Table( $cellsHtml, $cols, $rows, $size ); } /** * Writes a yes/no radio list * @param string The value of the HTML name attribute * @param string Additional HTML attributes for the "; if(!$required) $html .= "\n\t"; $n=count( $arr ); for ($i=0; $i < $n; $i++ ) { $k = stripslashes($arr[$i]->$key); $t = stripslashes($arr[$i]->$text); $id = isset($arr[$i]->id) ? $arr[$i]->id : null; $extra = ''; $extra .= $id ? " id=\"" . $arr[$i]->id . "\"" : ''; if (is_array( $selected )) { foreach ($selected as $obj) { $k2 = stripslashes($obj->$key); if ($k == $k2) { $extra .= " selected=\"selected\""; break; } } } else { $extra .= ($k == stripslashes($selected) ? " selected=\"selected\"" : ''); } $html .= "\n\t"; } $html .= "\n\n"; return $html; } function checkboxListArr( $arr, $tag_name, $tag_attribs, $key='value', $text='text',$selected=null, $required=0 ) { global $VM_LANG; reset( $arr ); $html = array(); $n=count( $arr ); for ($i=0; $i < $n; $i++ ) { $k = $arr[$i]->$key; $t = $arr[$i]->$text; $id = isset($arr[$i]->id) ? $arr[$i]->id : null; $extra = ''; $extra .= $id ? " id=\"" . $arr[$i]->id . "\"" : ''; if (is_array( $selected )) { foreach ($selected as $obj) { $k2 = $obj->$key; if ($k == $k2) { $extra .= " checked=\"checked\""; break; } } } else { $extra .= ($k == $selected ? " checked=\"checked\"" : ''); } $tmp = "" . ""; $html[] = $tmp; } return $html; } function checkboxList( $arr, $tag_name, $tag_attribs, $key='value', $text='text',$selected=null, $required=0 ) { return "\n\t".implode("\n\t", vmCommonHTML::checkboxListArr( $arr, $tag_name, $tag_attribs, $key, $text,$selected, $required ))."\n"; } function checkboxListTable( $arr, $tag_name, $tag_attribs, $key='value', $text='text',$selected=null, $cols=0, $rows=0, $size=0, $required=0 ) { $cellsHtml = vmCommonHTML::checkboxListArr( $arr, $tag_name, $tag_attribs, $key, $text,$selected, $required ); return vmCommonHTML::list2Table( $cellsHtml, $cols, $rows, $size ); } // private methods: function list2Table ( $cellsHtml, $cols, $rows, $size ) { $cells = count($cellsHtml); if ($size == 0) { $localstyle = ""; //" style='width:100%'"; } else { $size = (($size-($size % 3)) / 3 ) * 2; // int div 3 * 2 width/heigh ratio $localstyle = " style='width:".$size."em;'"; } $return=""; if ($cells) { if ($rows) { $return = "\n\t"; $cols = ($cells-($cells % $rows)) / $rows; // int div if ($cells % $rows) $cols++; $lineIdx=0; for ($lineIdx=0 ; $lineIdx < min($rows, $cells) ; $lineIdx++) { $return .= "\n\t\t"; for ($i=$lineIdx ; $i < $cells; $i += $rows) { $return .= ""; } $return .= "\n"; } $return .= "\t
    ".$cellsHtml[$i]."
    \n"; } else if ($cols) { $return = "\n\t"; $idx=0; while ($cells) { $return .= "\n\t\t"; for ($i=0, $n=min($cells,$cols); $i < $n; $i++, $cells-- ) { $return .= ""; } $return .= "\n"; } $return .= "\t
    ".$cellsHtml[$idx++]."
    \n"; } else { $return = "\n\t".implode("\n\t ", $cellsHtml)."\n"; } } return $return; } // end class vmCommonHTML, thanks folks! } /** * Utility function to provide ToolTips * * @param string $tooltip ToolTip text * @param string $title The Box title * @param string $image * @param int $width * @param string $text * @param string $href * @param string $link * @return string HTML code for ToolTip */ function vmToolTip( $tooltip, $title='Tip!', $image = "{mosConfig_live_site}/images/M_images/con_info.png", $width='350', $text='', $href='#', $link=false ) { global $mosConfig_live_site, $database; defined( 'vmToolTipCalled') or define('vmToolTipCalled', 1); $tooltip = str_replace('"','"',$tooltip); $tooltip = $database->getEscaped($tooltip); $tooltip = str_replace("'","\'",$tooltip); if ( !empty($width) ) { $width = ',WIDTH, -'.$width; } if ( $title ) { $title = ',TITLE,\''.$title .'\''; } $image = str_replace( "{mosConfig_live_site}", $mosConfig_live_site, $image); if( $image != '' ) { $text = vmCommonHTML::imageTag( $image, '', 'top' ). ' '.$text; } $style = 'style="text-decoration: none; color: #333;"'; if ( $href ) { $style = ''; } if ( $link ) { $tip = vmCommonHTML::hyperLink( $href, $text, '','', "onmouseover=\"Tip( '$tooltip' );\" onmouseout=\"UnTip()\" ". $style ); } else { $tip = "". $text .""; } return $tip; } /** * @deprecated */ function mm_ToolTip( $tooltip, $title='Tip!', $image = "{mosConfig_live_site}/images/M_images/con_info.png", $width='', $text='', $href='#', $link=false ) { return vmToolTip( $tooltip, $title, $image, $width, $text, $href, $link ); } /** * Utility function to provide persistant HelpToolTips * * @param unknown_type $tip * @param unknown_type $linktext */ function vmHelpToolTip( $tip, $linktext = ' [?] ' ) { global $mosConfig_live_site; if( !defined( 'vmHelpToolTipCalled')) { echo ' '; define('vmHelpToolTipCalled', 1); } $tip = str_replace( "\n", "", str_replace( "<", "<", str_replace( ">", ">", str_replace( "&", "&", @htmlentities( $tip, ENT_QUOTES ))))); $varname = 'a'.md5( $tip ); echo ' '; echo ''.$linktext.' '; } /** * Converts all special chars to html entities * * @param string $string * @param string $quote_style * @param boolean $only_special_chars Only Convert Some Special Chars ? ( <, >, &, ... ) * @return string */ function shopMakeHtmlSafe( $string, $quote_style='ENT_QUOTES', $use_entities=false ) { if( defined( $quote_style )) { $quote_style = constant($quote_style); } if( $use_entities ) { $string = @htmlentities( $string, constant($quote_style), vmGetCharset() ); } else { $string = @htmlspecialchars( $string, $quote_style, vmGetCharset() ); } return $string; } function mm_showMyFileName( $filename ) { if (vmShouldDebug()) { /*@MWM1: Logging/Debugging Enhancements */ echo vmToolTip( '
    Begin of File: '. wordwrap( $filename, 70, '
    ', true ).'
    '); } } /** * Wraps HTML Code or simple Text into Javascript * and uses the noscript Tag to support browsers with JavaScript disabled **/ function mm_writeWithJS( $textToWrap, $noscriptText ) { $text = ""; if( !empty( $textToWrap )) { $text = "\n"; } if( !empty( $noscriptText )) { $text .= "\n"; } return $text; } /** * A function to create a XHTML compliant and JS-disabled-safe pop-up link * * @param string $link The HREF attribute * @param string $text The link text * @param int $popupWidth * @param int $popupHeight * @param string $target The value of the target attribute * @param string $title * @param string $windowAttributes * @return string */ function vmPopupLink( $link, $text, $popupWidth=640, $popupHeight=480, $target='_blank', $title='', $windowAttributes='' ) { if( $windowAttributes ) { $windowAttributes = ','.$windowAttributes; } return vmCommonHTML::hyperLink( $link, $text, '', $title, "onclick=\"void window.open('$link', '$target', 'status=no,toolbar=no,scrollbars=yes,titlebar=no,menubar=no,resizable=yes,width=$popupWidth,height=$popupHeight,directories=no,location=no".$windowAttributes."');return false;\"" ); } /** * Creates a formatted address using the store address format * * @param array $address_details */ function vmFormatAddress( $address_details, $use_html=false ) { global $vendor_address_format; $store_address = str_replace( '{storename}', @$address_details['name'], $vendor_address_format ); $store_address = str_replace( '{address_1}', @$address_details['address_1'], $store_address ); $store_address = str_replace( '{address_2}', @$address_details['address_2'], $store_address ); $store_address = str_replace( '{state}', @$address_details['state'], $store_address ); $store_address = str_replace( '{statename}', @$address_details['state_name'], $store_address ); $store_address = str_replace( '{city}', @$address_details['city'], $store_address ); $store_address = str_replace( '{zip}', @$address_details['zip'], $store_address ); $store_address = str_replace( '{country}', @$address_details['country'], $store_address ); $store_address = str_replace( '{phone}', @$address_details['phone'], $store_address ); $store_address = str_replace( '{email}', @$address_details['email'], $store_address ); $store_address = str_replace( '{fax}', @$address_details['fax'], $store_address ); $store_address = str_replace( '{url}', @$address_details['url'], $store_address ); if( $use_html ) { $store_address = nl2br( $store_address ); } else { $store_address = strip_tags( $store_address ); } return $store_address; } ?> administrator/components/com_virtuemart/classes/imageTools.class.php100644 0 0 37713 11227154424 23724 0ustar 0 0 debug( 'Had to create the directory '.$path); } if( !is_writable($path) && !empty( $_FILES[$field_name]["tmp_name"]) ) { $vmLogger->err( 'Cannot write to '.$table_name.' image directory: '.$path ); return false; } // Check for upload errors require_once( CLASSPATH. 'ps_product_files.php'); ps_product_files::checkUploadedFile( $field_name ); // proof of concept fix by jmarsik 20090422 - safely move the uploaded file from upload_tmp_dir to temporary location (hopefully) included in open_basedir, following code will be much happier :) // if the file is not moved, following code will try to manipulate it using functions that check open_basedir (for example copy, file_exists, unlink, getimagesize) if( !empty ( $_FILES[$field_name]["tmp_name"] ) && is_uploaded_file($_FILES[$field_name]["tmp_name"]) ) { $tmpfile_moved_from_uploaded_file = $path . "tmpForThumb_" . basename($_FILES[$field_name]["tmp_name"]); $vmLogger->debug("Moving file from " . $_FILES[$field_name]["tmp_name"] . " to " . $tmpfile_moved_from_uploaded_file . " (helps when upload_tmp_dir is not in open_basedir)"); move_uploaded_file($_FILES[$field_name]["tmp_name"], $tmpfile_moved_from_uploaded_file); $_FILES[$field_name]["tmp_name"] = $tmpfile_moved_from_uploaded_file; } $tmp_field_name = str_replace( "thumb", "full", $field_name ); // Class for resizing Thumbnails require_once( CLASSPATH . "class.img2thumb.php"); if( @$d[$tmp_field_name.'_action'] == 'auto_resize' ) { // proof of concept fix by jmarsik 20090422 - safely move the uploaded file from upload_tmp_dir to temporary location (hopefully) included in open_basedir, following code will be much happier :) // if the file is not moved, following code will try to manipulate it using functions that check open_basedir (for example copy, file_exists, unlink, getimagesize) if( !empty ( $_FILES[$tmp_field_name]["tmp_name"] ) && is_uploaded_file($_FILES[$tmp_field_name]["tmp_name"]) ) { $tmpfile_moved_from_uploaded_file = $path . "tmpForThumb_" . basename($_FILES[$tmp_field_name]["tmp_name"]); $vmLogger->debug("Moving file from " . $_FILES[$tmp_field_name]["tmp_name"] . " to " . $tmpfile_moved_from_uploaded_file . " (helps when upload_tmp_dir is not in open_basedir)"); move_uploaded_file($_FILES[$tmp_field_name]["tmp_name"], $tmpfile_moved_from_uploaded_file); $_FILES[$tmp_field_name]["tmp_name"] = $tmpfile_moved_from_uploaded_file; } // Resize the Full Image if( !empty ( $_FILES[$tmp_field_name]["tmp_name"] )) { $full_file = $_FILES[$tmp_field_name]["tmp_name"]; $image_info = getimagesize($full_file); } elseif( !empty($d[$tmp_field_name."_url"] )) { $tmp_file_from_url = $full_file = ps_product_files::getRemoteFile($d[$tmp_field_name."_url"]); if( $full_file ) { $vmLogger->debug( 'Successfully fetched the image file from '.$d[$tmp_field_name."_url"].' for later resizing' ); $image_info = getimagesize($full_file); } } if( !empty( $image_info )) { if( $image_info[2] == 1) { if( function_exists("imagegif") ) { $ext = ".gif"; $noimgif=""; } else { $ext = ".jpg"; $noimgif = ".gif"; } } elseif( $image_info[2] == 2) { $ext = ".jpg"; $noimgif=""; } elseif( $image_info[2] == 3) { $ext = ".png"; $noimgif=""; } $vmLogger->debug( 'The resized Thumbnail will have extension '.$noimgif.$ext ); /* Generate Image Destination File Name */ if( !empty( $d[$table_name.'_name'] )) { $filename = substr( $d[$table_name.'_name'], 0, 16 ); $filename = vmSafeFileName( $filename ); } else { $filename = md5( 'virtuemart' ); } $to_file_thumb = uniqid( $filename.'_' ); $fileout = IMAGEPATH."$table_name/resized/$to_file_thumb".'_'.PSHOP_IMG_WIDTH.'x'.PSHOP_IMG_HEIGHT.$noimgif.$ext; if( !file_exists( dirname( $fileout ))) { mkdir( dirname( $fileout )); $vmLogger->debug('Created Directory '.dirname( $fileout )); } $neu = new Img2Thumb( $full_file, PSHOP_IMG_WIDTH, PSHOP_IMG_HEIGHT, $fileout, 0, 255, 255, 255 ); $thumbname = 'resized/'.basename( $fileout ); $vmLogger->debug( 'Finished creating the thumbnail '.$thumbname ); if( isset($tmp_file_from_url) ) unlink( realpath($tmp_file_from_url) ); $tmp_field_name = str_replace( "full", "thumb", $tmp_field_name ); $tmp_field_name = str_replace( "_url", "", $tmp_field_name ); $_FILES[$tmp_field_name]['tmp_name'] = $fileout; $_FILES[$tmp_field_name]['name'] = $thumbname; $d[$tmp_field_name] = $thumbname; $curr_file = isset($_REQUEST[$tmp_field_name."_curr"]) ? $_REQUEST[$tmp_field_name."_curr"] : ""; if (!empty($curr_file)) { $delete = str_replace("\\", "/", realpath($path."/".$curr_file)); $d["image_commands"][] = array( 'command' => 'unlink', 'param1' => $delete ); $vmLogger->debug( 'Preparing: delete old thumbnail image: '.$delete ); /* Remove the resized image if exists */ if( PSHOP_IMG_RESIZE_ENABLE=="1" ) { $pathinfo = pathinfo( $delete ); isset($pathinfo["dirname"]) or $pathinfo["dirname"] = ""; isset($pathinfo["extension"]) or $pathinfo["extension"] = ""; $filehash = basename( $delete, ".".$pathinfo["extension"] ); $resizedfilename = $pathinfo["dirname"]."/resized/".$filehash."_".PSHOP_IMG_WIDTH."x".PSHOP_IMG_HEIGHT.".".$pathinfo["extension"]; $d["image_commands"][] = array( 'command' => 'unlink', 'param1' => $resizedfilename ); $vmLogger->debug( 'Preparing: delete resized thumbnail '.$resizedfilename ); } } } } $temp_file = isset($_FILES[$field_name]['tmp_name']) ? $_FILES[$field_name]['tmp_name'] : ""; $file_type = isset($_FILES[$field_name]['type']) ? $_FILES[$field_name]['type'] : ""; $orig_file = isset($_FILES[$field_name]["name"]) ? $_FILES[$field_name]['name'] : ""; $curr_file = isset($_REQUEST[$field_name."_curr"]) ? $_REQUEST[$field_name."_curr"] : ""; /* Generate text to display in error messages */ if (eregi("thumb",$field_name)) { $image_type = "thumbnail image"; } elseif (eregi("full",$field_name)) { $image_type = "full image"; } else { $image_type = ereg_replace("_"," ",$field_name); } /* If User types "none" in Image Upload Field */ if ( @$d[$field_name."_action"] == "delete") { /* If there is a current image file */ if (!empty($curr_file)) { $delete = str_replace("\\", "/", realpath($path."/".$curr_file)); $d["image_commands"][] = array( 'command' => 'unlink', 'param1' => $delete ); $vmLogger->debug( 'Preparing: delete old '.$image_type.' '.$delete ); /* Remove the resized image if exists */ if( PSHOP_IMG_RESIZE_ENABLE=="1" && $image_type == "thumbnail image") { $pathinfo = pathinfo( $delete ); isset($pathinfo["dirname"]) or $pathinfo["dirname"] = ""; isset($pathinfo["extension"]) or $pathinfo["extension"] = ""; $filehash = basename( $delete, ".".$pathinfo["extension"] ); $resizedfilename = $pathinfo["dirname"]."/resized/".$filehash."_".PSHOP_IMG_WIDTH."x".PSHOP_IMG_HEIGHT.".".$pathinfo["extension"]; $d["image_commands"][] = array( 'command' => 'unlink', 'param1' => $resizedfilename ); $vmLogger->debug( 'Preparing: delete resized thumbnail '.$resizedfilename ); } } $d[$field_name] = ""; return true; } /* If upload fails */ elseif($orig_file and $temp_file == "none") { $vmLogger->err( $image_type.' upload failed.'); return false; } else { // If nothing was entered in the Upload box, there is no image to process if (!$orig_file ) { $d[$field_name] = $curr_file; return true; } } if( empty( $temp_file )) { $vmLogger->err( 'The File Upload was not successful: there\'s no uploaded temporary file!' ); return false; } /* Generate Image Destination File Name */ if( !empty( $d[$table_name.'_name'] )) { $filename = substr( $d[$table_name.'_name'], 0, 16 ); $filename = vmSafeFileName( $filename ); } else { $filename = md5( 'virtuemart' ); } $to_file = uniqid( $filename.'_' ); /* Check image file format */ if( $orig_file != "none" ) { $to_file .= $ext = '.'.Img2Thumb::GetImgType( $temp_file ); if( !$to_file ) { $vmLogger->err( $image_type.' file is invalid: '.$file_type.'.' ); return false; } } /* ** If it gets to this point then there is an uploaded file in the system ** and it is a valid image file. */ /* If Updating */ if (!empty($curr_file)) { /* Command to remove old image file */ $delete = str_replace( "\\", "/", realpath($path)."/".$curr_file); $d["image_commands"][] = array( 'command' => 'unlink', 'param1' => $delete ); /* Remove the resized image if exists */ if( PSHOP_IMG_RESIZE_ENABLE=="1" && $image_type == "thumbnail image") { $pathinfo = pathinfo( $delete ); $filehash = basename( $delete, ".".$pathinfo["extension"] ); $resizedfilename = $pathinfo["dirname"]."/resized/".$filehash."_".PSHOP_IMG_WIDTH."x".PSHOP_IMG_HEIGHT.".".$pathinfo["extension"]; $d["image_commands"][] = array( 'command' => 'unlink', 'param1' => $resizedfilename ); $vmLogger->debug( 'Preparing: delete resized thumbnail '.$resizedfilename ); } } /* Command to move uploaded file into destination directory */ // Command to move uploaded file into destination directory $d["image_commands"][] = array( 'command' => 'move_uploaded_file', 'param1' => $temp_file, 'param2' => $path.$to_file ); $d["image_commands"][] = array( 'command' => 'unlink', 'param1' => $temp_file ); if( empty( $d[$field_name] )) { /* Return new image file name */ $d[$field_name] = $to_file; } return true; } /** * The function that safely executes $d['image_commands'] and catches errors * * @param array $d * @return boolean True when all image commands were executed successfully, false when not */ function process_images(&$d) { global $vmLogger; require_once(CLASSPATH.'ps_product_files.php'); if (!empty($d["image_commands"])) { foreach( $d['image_commands'] as $exec ) { switch( $exec['command'] ) { case 'unlink': if( file_exists( $exec['param1']) ) { $ret = unlink( $exec['param1'] ); } else { $ret = true; } break; case 'move_uploaded_file': if( is_uploaded_file( $exec['param1']) ) { $ret = move_uploaded_file( $exec['param1'], $exec['param2'] ); } else { $ret = copy( $exec['param1'], $exec['param2'] ); } @chmod( $exec['param2'], 0666 ); break; } if ($ret == false) { $vmLogger->err ( 'The following image update command failed: '. $exec['command'] ); return false; } else { $vmLogger->debug( 'Successfully processed image command: '.$exec['command'] ); } } $d["image_commands"] = array(); } return true; } /** * Resizes an image to a given size * * @since VirtueMart 1.1.0 * @author soeren * * @static * * @param string $sourceFile * @param string $resizedFile * @param int $width * @param int $height * @param boolean $enlargeSmallerImg * @return boolean */ function resizeImage($sourceFile, $resizedFile, $height, $width, $enlargeSmallerImg=false ) { global $vmLogger; if( $width <= 0 || $height <= 0 ) { if( is_callable(array($vmLogger,'err'))) { $vmLogger->err( 'An invalid image height or weight was specified!'); return false; } } // We must take care of images which are already smaller than the size they are to be resized to // In most case it is not wanted to enlarge them $imgArr = @getimagesize( $sourceFile ); $isSmallerThanResizeto = $imgArr[0] < $width && $imgArr[1] < $height; if( $isSmallerThanResizeto && !$enlargeSmallerImg ) { if( $sourceFile != $resizedFile ) { @copy( $sourceFile, $resizedFile ); } $vmLogger->debug( 'The image '.basename( $sourceFile ).' was not resized because would have been enlarged.'); return false; } // Class for resizing Thumbnails require_once( CLASSPATH . "class.img2thumb.php"); $Img2Thumb = new Img2Thumb( $sourceFile, $width, $height, $resizedFile, 0, 255, 255, 255 ); if( is_file( $resizedFile )) { return true; } else { return false; } } /** * Returns the filename of an image's resized copy in the /resized folder * @since VirtueMart 1.1.0 * @author soeren * @static * @param string $filename * @param string $section * @param string $ext * @return string */ function getResizedFilename( $filename, $section='product', $ext='', $height=0, $width=0 ) { $fileinfo = pathinfo( $filename ); if( $ext == '' ) { $ext = $fileinfo['extension']; } $width = ( $width > 0 ) ? (int)$width : PSHOP_IMG_WIDTH; $height = ( $height > 0 ) ? (int)$height : PSHOP_IMG_HEIGHT; $basename = str_replace( "_".$height."x".$width, '', basename( $filename, '.'.$ext ) ); return IMAGEPATH.$section.'/resized/'.$basename."_".$height."x".$width.'.'.$ext; } }administrator/components/com_virtuemart/classes/index.html100644 0 0 0 10547254314 21657 0ustar 0 0 administrator/components/com_virtuemart/classes/language.class.php100644 0 0 22053 11037430547 23375 0ustar 0 0 >2)&5; $new_i=$new_c1*256+$new_c2; if ($new_i==1025){ $out_i=168; } else { if ($new_i==1105){ $out_i=184; } else { $out_i=$new_i-848; } } $out.=chr($out_i); $byte2=false; } if (($i>>5)==6) { $c1=$i; $byte2=true; } } return $out; } /** * Abstract lanuages/translation handler class */ class vmAbstractLanguage { /** @var boolean If true, highlights string not found */ var $_debug = false; var $modules = array(); var $key_varname = ''; function vmAbstractLanguage() { $this->setDebug(); } /** * Translator function * @param string Name of the Class Variable * @param boolean Encode String to HTML entities? * @return string The value of $var (as an HTML Entitiy-encoded string if $htmlentities) */ function _( $var, $htmlentities=false ) { global $modulename; $module = $modulename; $key = strtoupper( $var ); // if language module not yet loaded, load now if (!isset($this->modules[$module])) { $this->load($module); } $text = false; $module = $this->exists($key); if( $module === false && $key[0] == '_' ) { $key = substr( $key, 1 ); $module = $this->exists($key); } if ($module!==false) { $text = $this->modules[$module][$key]; if( $htmlentities ) { $text = htmlentities( $text, ENT_QUOTES, $this->getCharset($module)); // some symbols are not converted correctly... doing manually $text = str_replace(chr(128),'€',$text); // enable the use of HTML tags in language file... is this really good? $text = str_replace('<','<',$text); $text = str_replace('>','>',$text); return $text; } else { $text = $this->convert($text,$module); return stripslashes( $text ); } } elseif( $this->_debug ) { $GLOBALS['vmLogger']->debug( "$var is missing in language file."); } return ''; } /** * Merges the class vars of another class --> TO BE REMOVED... ? * @param string The name of the class to merge * @return boolean True if successful, false is failed */ function merge( $classname ) { if (class_exists( $classname )) { foreach (get_class_vars( $classname ) as $k=>$v) { if (is_string( $v )) { if ($k[0] != '_') { $this->$k = $v; } } } } else { return false; } } /** * Set the debug mode */ function setDebug() { if( function_exists('vmshoulddebug')) { $this->_debug = vmShouldDebug() || $GLOBALS['mosConfig_debug'] == '1'; } else { $this->_debug = DEBUG || $GLOBALS['mosConfig_debug'] == '1'; } } /** * Set the charset of a language module (normally specified in language file) * @param string The name of the module * @param string Forced charset (optional) * @return none */ function setCharset($module,$charset='') { if( !empty( $charset )) { $this->modules[$module]['CHARSET'] = $charset; } else { $this->modules[$module]['CHARSET'] = vmGetCharset(); } } /** * Get the charset of a languge module * @param string The name of the module * @return string The charset code */ function getCharset($module='common') { return $this->modules[$module]['CHARSET']; } /** * Convert a string, using the convert function set for this module * @param string The string to be converted * @param string The name of the module * @return string The converted string */ function convert($string,$module='common') { $func = $this->modules[$module]['CONVERT_FUNC']; if( !function_exists( $func )) { $func = 'strval'; } return $func($string); } /** * This safely converts an iso-8859 string into an utf-8 encoded * string. It does not convert when the string is already utf-8 encoded * * @param string $text iso-8859 encoded text * @param string $charset This is a k.o.-Argument. If it is NOT equal to 'utf-8', no conversion will take place * @return string */ function safe_utf8_encode( $text, $charset ) { if( strtolower($charset) == 'utf-8' && !vmAbstractLanguage::seems_utf8( $text )) { // safely decode and reencode the string $text = utf8_encode($text); } // This converts the currency symbol from HTML entity to the utf-8 symbol // example: € => € $text = vmHtmlEntityDecode( $text, null, vmGetCharset() ); return $text; } /** * a simple function that can help, if you want to know * if a string could be UTF-8 or not * @author bmorel at ssi dot fr * @param unknown_type $Str * @return boolean */ function seems_utf8($Str) { for ($i=0; $imodules[$module][$key])) { return $module; } elseif (isset($this->modules['common'][$key])) { return 'common'; } else { foreach ( $this->modules as $lang_module ) { if( isset( $lang_module[$key])) { return $lang_module[$this->key_varname]; } } return false; } } /** * Load the language file of a specified module * @param string The language module to load * @return boolean True if file exists, false is non exists */ function load($module) { global $mosConfig_lang; if( empty( $module )) return false; $module = basename( $module ); if (file_exists( ADMINPATH. 'languages/'.$module.'/'.strtolower($mosConfig_lang).'.php' )) { require_once( ADMINPATH. 'languages/'.$module.'/'.strtolower($mosConfig_lang).'.php' ); return true; } else if (file_exists( ADMINPATH. 'languages/'.$module.'/english.php' )) { require_once( ADMINPATH. 'languages/'.$module.'/english.php' ); return true; } else { // setting the module to false, to know that has already tried to load this $this->modules[$module] = false; return false; } } /** * Initialize the strings array of a language module * @param string The language module to init * @param array The array of language strings * @return none */ function initModule($module,&$vars) { $this->modules[$module] =& $vars; $this->modules[$module][$this->key_varname] = $module; $this->modules[$module]['CONVERT_FUNC'] = 'strval'; if( empty( $this->modules[$module]['CHARSET'] )) $this->setCharset($module); // get global charset setting $iso = explode( '=', @constant('_ISO') ); // If $iso[1] is NOT empty, it is Mambo or Joomla! 1.0.x - otherwise Joomla! >= 1.5 $charset = !empty( $iso[1] ) ? $iso[1] : 'utf-8'; // Prepare the convert function if necessary if( strtolower($charset)=='utf-8' && stristr($this->modules[$module]['CHARSET'], 'iso-8859-1' ) ) { $this->modules[$module]['CONVERT_FUNC'] = 'utf8_encode'; } elseif( stristr($charset, 'iso-8859-1') && strtolower($this->modules[$module]['CHARSET'])=='utf-8' ) { $this->modules[$module]['CONVERT_FUNC'] = 'utf8_decode'; } elseif( strpos($charset, '1251') && strtolower($this->modules[$module]['CHARSET'])=='utf-8' ) { $this->modules[$module]['CONVERT_FUNC'] = 'utf8_to_cp1251'; } } } class mosAbstractLanguage extends vmAbstractLanguage { } class vmLanguage extends vmAbstractLanguage { } class phpShopLanguage extends vmLanguage { } ?> administrator/components/com_virtuemart/classes/mainframe.class.php100644 0 0 36565 11220223435 23554 0ustar 0 0 getUserState( $key ); $cur_state = (!is_null($old_state)) ? $old_state : $default; $new_state = vmRequest::getVar($request, null, 'default', $type); // Save the new value only if it was set in this request if ($new_state !== null) { $this->setUserState($key, $new_state); } else { $new_state = $cur_state; } return $new_state; } /** * Adds a linked script to the page * * @param string $url URL to the linked script * @param string $type Type of script. Defaults to 'text/javascript' * @access public */ function addScript($url, $position = 'middle', $type="text/javascript") { static $included_scripts = array(); if( vmIsJoomla('1.0') && (strstr($_SERVER['SCRIPT_NAME'],'index3.php') || strstr($_SERVER['SCRIPT_NAME'],'index2.php')) || !vmIsJoomla() && defined('_VM_IS_BACKEND')) { echo vmCommonHTML::scriptTag($url); return; } if( isset($included_scripts[$url])) return; else $included_scripts[$url] = 1; $this->_scripts[] = array( 'url' => $url, 'content' => '', 'type' => $type, 'position' => strtolower($position)); } /** * Adds a script to the page * * @access public * @param string $content Script * @param string $type Scripting mime (defaults to 'text/javascript') * @param string $position Set to when the script should be loaded. Positions are top, middle, bottom * @return void */ function addScriptDeclaration($content, $position = 'middle', $type = 'text/javascript') { if( vmIsJoomla('1.0') && strstr($_SERVER['SCRIPT_NAME'],'index3.php') || !vmIsJoomla() && defined('_VM_IS_BACKEND')) { echo vmCommonHTML::scriptTag('', $content); return; } $this->_scripts[] = array( 'url' => '', 'content' => $content, 'type' => strtolower($type), 'position' => strtolower($position)); } /** * Adds a linked stylesheet to the page * * @param string $url URL to the linked style sheet * @param string $type Mime encoding type * @param string $media Media type that this stylesheet applies to * @access public */ function addStyleSheet($url, $type = 'text/css', $media = null, $attribs = array()) { if( vmIsJoomla('1.0') && (strstr($_SERVER['SCRIPT_NAME'],'index3.php') || strstr($_SERVER['SCRIPT_NAME'],'index2.php')) || !vmIsJoomla() && defined('_VM_IS_BACKEND') ) { echo vmCommonHTML::linkTag($url, $type, 'stylesheet', $media ); return; } if( isset($this->_styleSheets[$url])) return; $this->_styleSheets[$url]['url'] = $url; $this->_styleSheets[$url]['mime'] = $type; $this->_styleSheets[$url]['media'] = $media; $this->_styleSheets[$url]['attribs'] = $attribs; } /** * Adds a stylesheet declaration to the page * * @param string $content Style declarations * @param string $type Type of stylesheet (defaults to 'text/css') * @access public * @return void */ function addStyleDeclaration($content, $type = 'text/css') { if( vmIsJoomla('1.0') && strstr($_SERVER['SCRIPT_NAME'],'index3.php') || !vmIsJoomla() && defined('_VM_IS_BACKEND')) { echo ''; return; } $this->_style[][strtolower($type)] = $content; } function addResponseScript($content) { $this->_response_scripts[] = $content; } function scriptRedirect($location) { $this->addResponseScript('document.location=\''.$location.'\''); } function errorAlert( $text, $action='window.history.go(-1);', $mode=1 ) { global $mainframe, $mosConfig_live_site; $text = nl2br( $text ); $text = str_replace( '\'', "\'", $text ); $text = strip_tags( $text ); switch ( $mode ) { case 2: echo ' \n"; break; case 1: default: echo ' \n"; echo ''; break; } $this->close(true); } function render( $print = false ) { global $mainframe, $mosConfig_gzip, $mosConfig_live_site; foreach ( $this->_style as $style ) { $tag = ''; if( $print ) { echo $tag; } else { $mainframe->addCustomHeadTag( $tag ); } } if( isset( $_REQUEST['usefetchscript'])) { $use_fetchscript = vmRequest::getBool( 'usefetchscript', true ); vmRequest::setVar( 'usefetchscript', $use_fetchscript, 'session' ); } else { $use_fetchscript = vmRequest::getBool( 'usefetchscript', true, 'session' ); } // Gather all the linked Scripts into ONE link $i = 0; $appendix = ''; $loadorder = array(); foreach( $this->_scripts as $script ) { $src = $script['url']; $type = $script['type']; $content = $script['content']; $position = $script['position']; $urlpos = strpos( $src, '?' ); $url_params = ''; $js_file = false; $js_statement = false; if( $urlpos && (stristr( $src, VM_COMPONENT_NAME ) && !stristr( $src, '.php' ) && $use_fetchscript) ) { $url_params = '&'.substr( $src, $urlpos ); $src = substr( $src, 0, $urlpos); } /* Group the JS files together */ if( stristr( $src, VM_COMPONENT_NAME ) && !stristr( $src, '.php' ) && $use_fetchscript) { $base_source = str_replace( $GLOBALS['real_mosConfig_live_site'], '', $src ); $base_source = str_replace( $GLOBALS['mosConfig_live_site'], '', $base_source ); $base_source = str_replace( '/components/'.VM_COMPONENT_NAME, '', $base_source); $base_source = str_replace( 'components/'.VM_COMPONENT_NAME, '', $base_source); $js_file = '&subdir['.$i.']='.dirname( $base_source ) . '&file['.$i.']=' . basename( $src ); $i++; } /* Group the JS statements together */ else { $js_statement = array('type'=>$type, 'src'=>$src, 'content' => $content); } /* Group the statements according to their position */ /* JS files */ if ($js_file) { if (!isset($loadorder[$position]['js_file']['appendix'])) $loadorder[$position]['js_file']['appendix'] = ''; $loadorder[$position]['js_file']['appendix'] .= $js_file; } $js_file = false; /* JS statements */ if ($js_statement) { $loadorder[$position]['js_statement'][] = $js_statement; } $js_statement = false; } /* Add the JS to the output */ $processorder = array('top', 'middle', 'bottom'); foreach ($processorder as $key => $pos) { if (isset($loadorder[$pos])) { if (isset($loadorder[$pos]['js_file'])) { /* JS files */ $src = $mosConfig_live_site.'/components/'.VM_COMPONENT_NAME.'/fetchscript.php?gzip='.$mosConfig_gzip; $src .= $loadorder[$pos]['js_file']['appendix']; $tag = ''; if( $print ) { echo $tag; } else { $mainframe->addCustomHeadTag( $tag ); } } if (isset($loadorder[$pos]['js_statement'])) { /* JS statements */ foreach ($loadorder[$pos]['js_statement'] AS $statement_key => $otherscript) { if( !empty($otherscript['src'])) { $tag = ''; } else { $tag = ''; } if( $print ) { echo $tag; } else { $mainframe->addCustomHeadTag( $tag ); } } } } } // Gather all the linked Stylesheets into ONE link $i = 0; $appendix = ''; $url_params = ''; foreach( $this->_styleSheets as $stylesheet ) { $urlpos = strpos( $stylesheet['url'], '?' ); if( $urlpos ) { $url_params .= '&'.substr( $stylesheet['url'], $urlpos ); $stylesheet['url'] = substr( $stylesheet['url'], 0, $urlpos); } if( stristr( $stylesheet['url'], VM_COMPONENT_NAME ) && !stristr( $stylesheet['url'], '.php' ) && $stylesheet['media'] == null && $use_fetchscript ) { $base_source = str_replace( $GLOBALS['real_mosConfig_live_site'], '', $stylesheet['url'] ); $base_source = str_replace( $GLOBALS['mosConfig_live_site'], '', $base_source ); $base_source = str_replace( '/components/'.VM_COMPONENT_NAME, '', $base_source); $base_source = str_replace( 'components/'.VM_COMPONENT_NAME, '', $base_source); $appendix .= '&subdir['.$i.']='.dirname( $base_source ) . '&file['.$i.']=' . basename( $stylesheet['url'] ); $i++; } else { $tag = ''; if( $print ) { echo $tag; } else { $mainframe->addCustomHeadTag( $tag ); } } } if( $i> 0 ) { $src = $mosConfig_live_site.'/components/com_virtuemart/fetchscript.php?gzip='.$mosConfig_gzip; $src .= $appendix; $tag = ''; if( $print ) { echo $tag; } else { $mainframe->addCustomHeadTag( $tag ); } } } function close( $exit=false ) { global $mosConfig_live_site, $mainframe; if( !$exit ) { if( defined( 'vmToolTipCalled')) { echo vmCommonHTML::scriptTag( $mosConfig_live_site.'/components/'.VM_COMPONENT_NAME.'/js/wz_tooltip.js' ); } if( defined( '_LITEBOX_LOADED')) { echo vmCommonHTML::scriptTag( '', 'var prev_onload = document.body.onload; window.onload = function() { if( prev_onload ) prev_onload(); initLightbox(); }' ); } $this->render(); } else { if( !empty( $this->_response_scripts )) { echo vmCommonHTML::scriptTag('', implode("\n", $this->_response_scripts )); } if( is_callable( array( $mainframe, 'close' ) ) ) { $mainframe->close(); } else { session_write_close(); exit; } } } /** * Appends items to the CMS pathway * * @param string $pathway_items Array of pathway objects ($name, $link) * @access public */ function vmAppendPathway( $pathway ) { global $mainframe; // Remove the link on the last pathway item $pathway[ count($pathway) - 1 ]->link = ''; if( vmIsJoomla('1.5') ) { $cmsPathway =& $mainframe->getPathway(); foreach( $pathway AS $item) { $item->link = str_replace('&', '&', $item->link); // make sure that ' (apostrophe) is converted to ' $item->name = html_entity_decode( $item->name, ENT_QUOTES ); $cmsPathway->addItem( $item->name, $item->link ); } } else { $tpl = vmTemplate::getInstance(); $tpl->set( 'pathway', $pathway ); $vmPathway = $tpl->fetch( 'common/pathway.tpl.php' ); $mainframe->appendPathWay( $vmPathway ); } } /** * Sets the page title * * @param string $title */ function setPageTitle( $title ) { global $mainframe; $title = strip_tags(str_replace(' ',' ', $title)); $title = trim($title); if( defined( '_VM_IS_BACKEND')) { echo vmCommonHTML::scriptTag('', "// "); } elseif( vmIsJoomla('1.5') ) { $document=& JFactory::getDocument(); $document->setTitle($title); } else { $mainframe->setPageTitle( $title ); } } /** * Returns a pathway item * * @param string $name * @param string $link * @access public * @return object A pathway item object */ function vmPathwayItem( $name, $link = '' ) { $item = new stdClass(); $item->name = vmHtmlEntityDecode( $name ); $item->link = $link; return $item; } } // Check if there is an extended class in the Themes and if it is allowed to use them // If the class is called outside Virtuemart, we have to make sure to load the settings // Thomas Kahl - Feb. 2009 if (!defined('VM_ALLOW_EXTENDED_CLASSES') && file_exists(dirname(__FILE__).'/../virtuemart.cfg.php')) { include_once(dirname(__FILE__).'/../virtuemart.cfg.php'); } // If settings are loaded, extended Classes are allowed and the class exisits... if (defined('VM_ALLOW_EXTENDED_CLASSES') && defined('VM_THEMEPATH') && VM_ALLOW_EXTENDED_CLASSES && file_exists(VM_THEMEPATH.'user_class/'.basename(__FILE__))) { // Load the theme-user_class as extended include_once(VM_THEMEPATH.'user_class/'.basename(__FILE__)); } else { // Otherwise we have to use the original classname to extend the core-class class vmMainframe extends vm_vmMainFrame {} } ?> administrator/components/com_virtuemart/classes/menuBar.class.php100644 0 0 44611 11146612233 23202 0ustar 0 0 _('CMN_NEW'); } $bar =& JToolBar::getInstance('toolbar'); $bar->appendButton('Custom', ' ' . '
    ' . $alt .'
    '); } /** * Writes a save button for a given option * Save operation leads to a save and then close action * @param string An override for the task * @param string An override for the alt text */ function save( $task='save', $alt='' ) { global $VM_LANG; if( $alt == '') { $alt = $VM_LANG->_('CMN_SAVE'); } $bar =& JToolBar::getInstance('toolbar'); $bar->appendButton('Custom', '
    ' . $alt .'
    ' ); } /** * Writes a back button * @param string An override for the task * @param string An override for the alt text */ function back( $task='back', $alt='' ) { global $VM_LANG; if( $alt == '') { $alt = $VM_LANG->_('BACK'); } $bar =& JToolBar::getInstance('toolbar'); $bar->appendButton('Custom', '
    ' . $alt .'
    ' ); } /** * Writes a save button for a given option * Save operation leads to a save and then close action * @param string An override for the task * @param string An override for the alt text */ function apply( $task='apply', $alt='' ) { global $page, $VM_LANG; if( $alt == '') { $alt = $VM_LANG->_('E_APPLY'); } $bar =& JToolBar::getInstance('toolbar'); $bar->appendButton('Custom', "
    $alt
    " ); } /** * Writes a common 'publish' button for a list of records * @param string An override for the task * @param string An override for the alt text */ function publishList( $func, $task='publish', $alt='' ) { global $VM_LANG; if ($alt=='') { $alt=$VM_LANG->_('CMN_PUBLISH'); } $bar =& JToolBar::getInstance('toolbar'); $bar->appendButton( 'Custom', ' _('CMN_PLEASESELECT_PUBLISH')) . '\'); } else {vm_submitListFunc(\''. $task. '\', \'adminForm\', \''. $func .'\');}" >
    ' . $alt .'
    ' ); } /** * Writes a common 'unpublish' button for a list of records * @param string An override for the task * @param string An override for the alt text */ function unpublishList( $func, $task='unpublish', $alt='' ) { global $VM_LANG; if ($alt=='') { $alt=$VM_LANG->_('CMN_UNPUBLISH'); } $bar =& JToolBar::getInstance('toolbar'); $bar->appendButton( 'Custom', ' _('CMN_PLEASESELECT_UNPUBLISH')) . '\'); } else {vm_submitListFunc(\''. $task. '\', \'adminForm\', \''. $func .'\');}" >
    ' . $alt .'
    ' ); } /** * Writes a common 'delete' button for a list of records * @param string Postscript for the 'are you sure' message * @param string An override for the task * @param string An override for the alt text */ function deleteList( $func, $task='remove', $alt='' ) { global $VM_LANG; if( $alt == '') { $alt = $VM_LANG->_('E_REMOVE'); } $bar =& JToolBar::getInstance('toolbar'); $bar->appendButton( 'Custom', '_('CMN_PLEASESELECT_DELETE')) . '\'); } else if (confirm(\'' . str_replace("'","\\'",$VM_LANG->_('CMN_CONFIRM_DELETE_ITEMS')) .'\')){ vm_submitListFunc(\''. $task.'\', \'adminForm\', \''. $func.'\' );}">
    ' . $alt .'
    ' ); } /** * Writes a cancel button and invokes a cancel operation (eg a checkin) * @param string An override for the task * @param string An override for the alt text */ function cancel( $task='cancel', $alt='' ) { global $page, $VM_LANG; if( $alt == '') { $alt = $VM_LANG->_('CMN_CANCEL'); } $no_menu = vmGet( $_REQUEST, 'no_menu' ); $bar =& JToolBar::getInstance('toolbar'); if ($page == "store.store_form") { $my_page = "store.index"; } elseif ($page == "admin.user_address_form") { $my_page = "admin.user_form"; } elseif ($page == "admin.show_cfg") { $my_page = "store.index"; } elseif ( $page == 'admin.theme_config_form' ) { $my_page = 'admin.show_cfg'; } else { $my_page = str_replace('form','list',$page); } if( $no_menu ) { $js = "vm_windowClose();"; } else { $js = "vm_submitButton('$task', 'adminForm', '$my_page');"; } $bar->appendButton( 'Custom', "
    $alt
    " ); } /** * Writes a custom option and task button for the button bar * @param string The task to perform (picked up by the switch($task) blocks * @param string The image to display (FULL URL!) * @param string The image to display when moused over * @param string The alt text for the icon image * @param boolean True if required to check that a standard list item is checked */ function custom( $task='', $page, $icon='', $iconOver='', $alt='', $listSelect=true, $formName="adminForm", $func = "" ) { global $VM_LANG; $bar =& JToolBar::getInstance('toolbar'); if ($listSelect) { if( empty( $func )) $href = "javascript:if (document.adminForm.boxchecked.value == 0){ alert('" . str_replace("'","\\'",$VM_LANG->_('CMN_PLEASESELECT_TO')) . " $alt');}else{vm_submitButton('$task','$formName', '$page')}"; else $href = "javascript:if (document.adminForm.boxchecked.value == 0){ alert('" . str_replace("'","\\'",$VM_LANG->_('CMN_PLEASESELECT_TO')) . " $alt');}else{vm_submitListFunc('$task','$formName', '$func')}"; } else { $href = "javascript:vm_submitButton('$task','$formName', '$page')"; } if( empty( $task )) { $image_name = uniqid( "img_" ); } else { $image_name = $task; } if ($icon && $iconOver) { $bar->appendButton('Custom', " \"$alt\"  
    $alt
    " ); } else { // The button is just a link then! $bar->appendButton('Custom', " $alt" ); } } /** * Writes a link for the button bar * @param string The task to perform (picked up by the switch($task) blocks * @param string The image to display (FULL URL!) * @param string The image to display when moused over * @param string The alt text for the icon image * @param boolean True if required to check that a standard list item is checked */ function customHref( $href='', $icon='', $iconOver='', $alt='' ) { $bar =& JToolBar::getInstance('toolbar'); if ($icon && $iconOver) { $bar->appendButton('Custom', " \"$alt\"  
    $alt
    " ); } else { $bar->appendButton('Custom', " $alt" ); } } } /** * This class is used for the Ext-based Toolbar (ExtJS), which is only the case in "Extended Layout" mode * This toolbar is a custom replacement for the Mambo/Joomla! toolbar * @author soeren * @since 1.1 * */ class vmToolBar { var $buttons = ''; /** * Returns a reference to a global vmToolBar object, only creating it if it * doesn't already exist. * * This method must be invoked as: *
      $toolbar = &vmToolBar::getInstance([$name);
    * * @access public * @param string $name The name of the toolbar. * @return vmToolBar The vmToolBar object. */ function & getInstance($name) { static $instances; if (!isset ($instances)) { $instances = array (); } if (empty ($instances[$name])) { $instances[$name] = new vmToolBar(); } return $instances[$name]; } function appendButton( $text, $action_name, $click_action ) { $text = '
     
     ' . $text; $this->buttons .= "vmTb.addButton({text: '$text', handler: new Function('".addslashes($click_action)."')});\n"; } /** * Renders the Ext Toolbar for VirtueMart * means: it assembles the javascript to add the buttons/separators/links to the toolbar * */ function render() { if( $this->buttons != '' ) { vmCommonHTML::loadExtjs(); $toolbarscript = "var renderVMTb = function() { var vmTb = new Ext.Toolbar({renderTo: \"vm-toolbar\"});\n" . $this->buttons //. "\nif( self.history.length > 1 ) { vmTb.addSeparator(); vmTb.addButton({text: '
    _BACK}\"> 
    {$GLOBALS['VM_LANG']->_BACK}', handler: new Function('history.back();') }); }" . "\nvmTb.addSeparator();\n vmTb.addButton({text: '
    _('RELOAD')."\"> 
    ".$GLOBALS['VM_LANG']->_('RELOAD')."', handler: new Function('location.reload();') }); }; if( Ext.isIE6 || Ext.isIE7 ) { Ext.EventManager.addListener( window, 'load', renderVMTb ); } else { Ext.onReady( renderVMTb ); }"; echo vmCommonHTML::scriptTag('', $toolbarscript ); } // } /** * Writes the common 'new' icon for the button bar * @param string An override for the task * @param string An override for the alt text */ function addNew( $task='new', $page, $alt='', $formName="adminForm" ) { global $VM_LANG; if( $alt == '') { $alt = $VM_LANG->_('CMN_NEW'); } $this->appendButton($alt, $task, "document.adminForm.toggle.onclick();vm_submitButton('$task','$formName','$page')" ); } /** * Writes a save button for a given option * Save operation leads to a save and then close action * @param string An override for the task * @param string An override for the alt text */ function save( $task='save', $alt='' ) { global $VM_LANG; if( $alt == '') { $alt = $VM_LANG->_('CMN_SAVE'); } $this->appendButton($alt, $task, "submitbutton('$task')" ); } /** * Writes an apply button for a given option * Save operation leads to a save and then reopen form action * @param string An override for the task * @param string An override for the alt text */ function apply( $task='apply', $alt='' ) { global $page, $VM_LANG; if( $alt == '') { $alt = $VM_LANG->_('E_APPLY'); } $this->appendButton($alt, $task, "vm_submitButton('$task', 'adminForm', '$page')" ); } function back() { global $VM_LANG; $this->appendButton($VM_LANG->_('BACK'), 'back', "window.history.back();" ); } /** * Writes a common 'publish' button for a list of records * @param string An override for the task * @param string An override for the alt text */ function publishList( $func, $task='publish', $alt='' ) { global $VM_LANG; if ($alt=='') { $alt=$VM_LANG->_('CMN_PUBLISH'); } $this->appendButton($alt, $task, "if (document.adminForm.boxchecked.value == 0){ Ext.Msg.alert('".$VM_LANG->_('PEAR_LOG_NOTICE')."', '" . $VM_LANG->_('CMN_PLEASESELECT_PUBLISH',false) . "'); } else {vm_submitListFunc('$task', 'adminForm', '$func');}"); } /** * Writes a common 'unpublish' button for a list of records * @param string An override for the task * @param string An override for the alt text */ function unpublishList( $func, $task='unpublish', $alt='' ) { global $VM_LANG; if ($alt=='') { $alt=$VM_LANG->_('CMN_UNPUBLISH'); } $this->appendButton( $alt, $task, "if (document.adminForm.boxchecked.value == 0){ Ext.Msg.alert('".$VM_LANG->_('PEAR_LOG_NOTICE')."', '" . $VM_LANG->_('CMN_PLEASESELECT_UNPUBLISH',false) . "'); } else {vm_submitListFunc('$task', 'adminForm', '$func');}" ); } /** * Writes a common 'delete' button for a list of records * @param string Postscript for the 'are you sure' message * @param string An override for the task * @param string An override for the alt text */ function deleteList( $func, $task='remove', $alt='' ) { global $VM_LANG; if( $alt == '') { $alt = $VM_LANG->_('E_REMOVE'); } $this->appendButton( $alt, $task, "if (document.adminForm.boxchecked.value == 0){ Ext.Msg.alert('".$VM_LANG->_('PEAR_LOG_NOTICE')."', '" . $VM_LANG->_('CMN_PLEASESELECT_DELETE') . "'); } else if (confirm('Are you sure you want to delete selected items?')){ vm_submitListFunc('$task', 'adminForm', '$func' );}" ); } /** * Writes a cancel button and invokes a cancel operation (eg a checkin) * @param string An override for the task * @param string An override for the alt text */ function cancel( $task='cancel', $alt='' ) { global $page, $VM_LANG; if( $alt == '') { $alt = $VM_LANG->_('CMN_CANCEL'); } if ($page == "store.store_form") { $my_page = "store.index"; } elseif ($page == "admin.user_address_form") { $my_page = "admin.user_form"; } elseif ($page == "admin.show_cfg") { $my_page = "store.index"; } elseif ( $page == 'admin.theme_config_form' ) { $my_page = 'admin.show_cfg'; } else { $my_page = str_replace('form','list',$page); } $js = "vm_submitButton('$task', 'adminForm', '$my_page');"; $this->appendButton( $alt, $task, $js ); } /** * Writes a custom option and task button for the button bar * @param string The task to perform (picked up by the switch($task) blocks * @param string The image to display (FULL URL!) * @param string The image to display when moused over * @param string The alt text for the icon image * @param boolean True if required to check that a standard list item is checked */ function custom( $task='', $page, $action_name='', $alt='', $listSelect=true, $formName="adminForm", $func = "" ) { global $VM_LANG; if ($listSelect) { if( empty( $func )) { $js = "if (document.adminForm.boxchecked.value == 0){ Ext.Msg.alert('".$VM_LANG->_('PEAR_LOG_NOTICE')."', '" . $VM_LANG->_('CMN_PLEASESELECT_TO') . " $alt');}else{vm_submitButton('$task','$formName', '$page')}"; } else { $js = "if (document.adminForm.boxchecked.value == 0){ Ext.Msg.alert('".$VM_LANG->_('PEAR_LOG_NOTICE')."', '" . $VM_LANG->_('CMN_PLEASESELECT_TO') . " $alt');}else{vm_submitListFunc('$task','$formName', '$func')}"; } } else { $js = "vm_submitButton('$task','$formName', '$page')"; } if( empty( $task )) { $image_name = uniqid( "img_" ); } else { $image_name = $task; } if ($action_name) { $this->appendButton($alt, $task, $js ); } else { // The button is just a link then! $this->appendButton($alt, $task, "document.location='$js'" ); } } /** * Writes a link for the button bar * @param string The task to perform (picked up by the switch($task) blocks * @param string The image to display (FULL URL!) * @param string The image to display when moused over * @param string The alt text for the icon image * @param boolean True if required to check that a standard list item is checked */ function customHref( $href='', $icon='', $alt='' ) { if ($icon ) { $this->appendButton($alt, $icon, "document.location='$href'" ); } else { $this->appendButton($alt, 'none', "document.location='$href'" ); } } function divider() { $this->buttons .= "vmTb.addSeparator();\n"; } }administrator/components/com_virtuemart/classes/nusoap/class.wsdlcache.php100644 0 0 12726 11032504255 25053 0ustar 0 0 * @author Ingo Fischer * @version $Id: class.wsdlcache.php,v 1.7 2007/04/17 16:34:03 snichol Exp $ * @access public */ class nusoap_wsdlcache { /** * @var resource * @access private */ var $fplock; /** * @var integer * @access private */ var $cache_lifetime; /** * @var string * @access private */ var $cache_dir; /** * @var string * @access public */ var $debug_str = ''; /** * constructor * * @param string $cache_dir directory for cache-files * @param integer $cache_lifetime lifetime for caching-files in seconds or 0 for unlimited * @access public */ function nusoap_wsdlcache($cache_dir='.', $cache_lifetime=0) { $this->fplock = array(); $this->cache_dir = $cache_dir != '' ? $cache_dir : '.'; $this->cache_lifetime = $cache_lifetime; } /** * creates the filename used to cache a wsdl instance * * @param string $wsdl The URL of the wsdl instance * @return string The filename used to cache the instance * @access private */ function createFilename($wsdl) { return $this->cache_dir.'/wsdlcache-' . md5($wsdl); } /** * adds debug data to the class level debug string * * @param string $string debug data * @access private */ function debug($string){ $this->debug_str .= get_class($this).": $string\n"; } /** * gets a wsdl instance from the cache * * @param string $wsdl The URL of the wsdl instance * @return object wsdl The cached wsdl instance, null if the instance is not in the cache * @access public */ function get($wsdl) { $filename = $this->createFilename($wsdl); if ($this->obtainMutex($filename, "r")) { // check for expired WSDL that must be removed from the cache if ($this->cache_lifetime > 0) { if (file_exists($filename) && (time() - filemtime($filename) > $this->cache_lifetime)) { unlink($filename); $this->debug("Expired $wsdl ($filename) from cache"); $this->releaseMutex($filename); return null; } } // see what there is to return if (!file_exists($filename)) { $this->debug("$wsdl ($filename) not in cache (1)"); $this->releaseMutex($filename); return null; } $fp = @fopen($filename, "r"); if ($fp) { $s = implode("", @file($filename)); fclose($fp); $this->debug("Got $wsdl ($filename) from cache"); } else { $s = null; $this->debug("$wsdl ($filename) not in cache (2)"); } $this->releaseMutex($filename); return (!is_null($s)) ? unserialize($s) : null; } else { $this->debug("Unable to obtain mutex for $filename in get"); } return null; } /** * obtains the local mutex * * @param string $filename The Filename of the Cache to lock * @param string $mode The open-mode ("r" or "w") or the file - affects lock-mode * @return boolean Lock successfully obtained ?! * @access private */ function obtainMutex($filename, $mode) { if (isset($this->fplock[md5($filename)])) { $this->debug("Lock for $filename already exists"); return false; } $this->fplock[md5($filename)] = fopen($filename.".lock", "w"); if ($mode == "r") { return flock($this->fplock[md5($filename)], LOCK_SH); } else { return flock($this->fplock[md5($filename)], LOCK_EX); } } /** * adds a wsdl instance to the cache * * @param object wsdl $wsdl_instance The wsdl instance to add * @return boolean WSDL successfully cached * @access public */ function put($wsdl_instance) { $filename = $this->createFilename($wsdl_instance->wsdl); $s = serialize($wsdl_instance); if ($this->obtainMutex($filename, "w")) { $fp = fopen($filename, "w"); if (! $fp) { $this->debug("Cannot write $wsdl_instance->wsdl ($filename) in cache"); $this->releaseMutex($filename); return false; } fputs($fp, $s); fclose($fp); $this->debug("Put $wsdl_instance->wsdl ($filename) in cache"); $this->releaseMutex($filename); return true; } else { $this->debug("Unable to obtain mutex for $filename in put"); } return false; } /** * releases the local mutex * * @param string $filename The Filename of the Cache to lock * @return boolean Lock successfully released * @access private */ function releaseMutex($filename) { $ret = flock($this->fplock[md5($filename)], LOCK_UN); fclose($this->fplock[md5($filename)]); unset($this->fplock[md5($filename)]); if (! $ret) { $this->debug("Not able to release lock for $filename"); } return $ret; } /** * removes a wsdl instance from the cache * * @param string $wsdl The URL of the wsdl instance * @return boolean Whether there was an instance to remove * @access public */ function remove($wsdl) { $filename = $this->createFilename($wsdl); if (!file_exists($filename)) { $this->debug("$wsdl ($filename) not in cache to be removed"); return false; } // ignore errors obtaining mutex $this->obtainMutex($filename, "w"); $ret = unlink($filename); $this->debug("Removed ($ret) $wsdl ($filename) from cache"); $this->releaseMutex($filename); return $ret; } } /** * For backward compatibility */ class wsdlcache extends nusoap_wsdlcache { } ?> administrator/components/com_virtuemart/classes/nusoap/index.html100644 0 0 0 11032504255 23154 0ustar 0 0 administrator/components/com_virtuemart/classes/nusoap/nusoap.php100644 0 0 1066125 11263442227 23370 0ustar 0 0 globalDebugLevel = 9; /** * * nusoap_base * * @author Dietrich Ayala * @author Scott Nichol * @version $Id: nusoap.php,v 1.114 2007/11/06 15:17:46 snichol Exp $ * @access public */ class nusoap_base { /** * Identification for HTTP headers. * * @var string * @access private */ var $title = 'NuSOAP'; /** * Version for HTTP headers. * * @var string * @access private */ var $version = '0.7.3'; /** * CVS revision for HTTP headers. * * @var string * @access private */ var $revision = '$Revision: 1.114 $'; /** * Current error string (manipulated by getError/setError) * * @var string * @access private */ var $error_str = ''; /** * Current debug string (manipulated by debug/appendDebug/clearDebug/getDebug/getDebugAsXMLComment) * * @var string * @access private */ var $debug_str = ''; /** * toggles automatic encoding of special characters as entities * (should always be true, I think) * * @var boolean * @access private */ var $charencoding = true; /** * the debug level for this instance * * @var integer * @access private */ var $debugLevel; /** * set schema version * * @var string * @access public */ var $XMLSchemaVersion = 'http://www.w3.org/2001/XMLSchema'; /** * charset encoding for outgoing messages * * @var string * @access public */ var $soap_defencoding = 'ISO-8859-1'; //var $soap_defencoding = 'UTF-8'; /** * namespaces in an array of prefix => uri * * this is "seeded" by a set of constants, but it may be altered by code * * @var array * @access public */ var $namespaces = array( 'SOAP-ENV' => 'http://schemas.xmlsoap.org/soap/envelope/', 'xsd' => 'http://www.w3.org/2001/XMLSchema', 'xsi' => 'http://www.w3.org/2001/XMLSchema-instance', 'SOAP-ENC' => 'http://schemas.xmlsoap.org/soap/encoding/' ); /** * namespaces used in the current context, e.g. during serialization * * @var array * @access private */ var $usedNamespaces = array(); /** * XML Schema types in an array of uri => (array of xml type => php type) * is this legacy yet? * no, this is used by the nusoap_xmlschema class to verify type => namespace mappings. * @var array * @access public */ var $typemap = array( 'http://www.w3.org/2001/XMLSchema' => array( 'string'=>'string','boolean'=>'boolean','float'=>'double','double'=>'double','decimal'=>'double', 'duration'=>'','dateTime'=>'string','time'=>'string','date'=>'string','gYearMonth'=>'', 'gYear'=>'','gMonthDay'=>'','gDay'=>'','gMonth'=>'','hexBinary'=>'string','base64Binary'=>'string', // abstract "any" types 'anyType'=>'string','anySimpleType'=>'string', // derived datatypes 'normalizedString'=>'string','token'=>'string','language'=>'','NMTOKEN'=>'','NMTOKENS'=>'','Name'=>'','NCName'=>'','ID'=>'', 'IDREF'=>'','IDREFS'=>'','ENTITY'=>'','ENTITIES'=>'','integer'=>'integer','nonPositiveInteger'=>'integer', 'negativeInteger'=>'integer','long'=>'integer','int'=>'integer','short'=>'integer','byte'=>'integer','nonNegativeInteger'=>'integer', 'unsignedLong'=>'','unsignedInt'=>'','unsignedShort'=>'','unsignedByte'=>'','positiveInteger'=>''), 'http://www.w3.org/2000/10/XMLSchema' => array( 'i4'=>'','int'=>'integer','boolean'=>'boolean','string'=>'string','double'=>'double', 'float'=>'double','dateTime'=>'string', 'timeInstant'=>'string','base64Binary'=>'string','base64'=>'string','ur-type'=>'array'), 'http://www.w3.org/1999/XMLSchema' => array( 'i4'=>'','int'=>'integer','boolean'=>'boolean','string'=>'string','double'=>'double', 'float'=>'double','dateTime'=>'string', 'timeInstant'=>'string','base64Binary'=>'string','base64'=>'string','ur-type'=>'array'), 'http://soapinterop.org/xsd' => array('SOAPStruct'=>'struct'), 'http://schemas.xmlsoap.org/soap/encoding/' => array('base64'=>'string','array'=>'array','Array'=>'array'), 'http://xml.apache.org/xml-soap' => array('Map') ); /** * XML entities to convert * * @var array * @access public * @deprecated * @see expandEntities */ var $xmlEntities = array('quot' => '"','amp' => '&', 'lt' => '<','gt' => '>','apos' => "'"); /** * constructor * * @access public */ function nusoap_base() { $this->debugLevel = $GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel; } /** * gets the global debug level, which applies to future instances * * @return integer Debug level 0-9, where 0 turns off * @access public */ function getGlobalDebugLevel() { return $GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel; } /** * sets the global debug level, which applies to future instances * * @param int $level Debug level 0-9, where 0 turns off * @access public */ function setGlobalDebugLevel($level) { $GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel = $level; } /** * gets the debug level for this instance * * @return int Debug level 0-9, where 0 turns off * @access public */ function getDebugLevel() { return $this->debugLevel; } /** * sets the debug level for this instance * * @param int $level Debug level 0-9, where 0 turns off * @access public */ function setDebugLevel($level) { $this->debugLevel = $level; } /** * adds debug data to the instance debug string with formatting * * @param string $string debug data * @access private */ function debug($string){ if ($this->debugLevel > 0) { $this->appendDebug($this->getmicrotime().' '.get_class($this).": $string\n"); } } /** * adds debug data to the instance debug string without formatting * * @param string $string debug data * @access public */ function appendDebug($string){ if ($this->debugLevel > 0) { // it would be nice to use a memory stream here to use // memory more efficiently $this->debug_str .= $string; } } /** * clears the current debug data for this instance * * @access public */ function clearDebug() { // it would be nice to use a memory stream here to use // memory more efficiently $this->debug_str = ''; } /** * gets the current debug data for this instance * * @return debug data * @access public */ function &getDebug() { // it would be nice to use a memory stream here to use // memory more efficiently return $this->debug_str; } /** * gets the current debug data for this instance as an XML comment * this may change the contents of the debug data * * @return debug data as an XML comment * @access public */ function &getDebugAsXMLComment() { // it would be nice to use a memory stream here to use // memory more efficiently while (strpos($this->debug_str, '--')) { $this->debug_str = str_replace('--', '- -', $this->debug_str); } $ret = ""; return $ret; } /** * expands entities, e.g. changes '<' to '<'. * * @param string $val The string in which to expand entities. * @access private */ function expandEntities($val) { if ($this->charencoding) { $val = str_replace('&', '&', $val); $val = str_replace("'", ''', $val); $val = str_replace('"', '"', $val); $val = str_replace('<', '<', $val); $val = str_replace('>', '>', $val); } return $val; } /** * returns error string if present * * @return mixed error string or false * @access public */ function getError(){ if($this->error_str != ''){ return $this->error_str; } return false; } /** * sets error string * * @return boolean $string error string * @access private */ function setError($str){ $this->error_str = $str; } /** * detect if array is a simple array or a struct (associative array) * * @param mixed $val The PHP array * @return string (arraySimple|arrayStruct) * @access private */ function isArraySimpleOrStruct($val) { $keyList = array_keys($val); foreach ($keyList as $keyListValue) { if (!is_int($keyListValue)) { return 'arrayStruct'; } } return 'arraySimple'; } /** * serializes PHP values in accordance w/ section 5. Type information is * not serialized if $use == 'literal'. * * @param mixed $val The value to serialize * @param string $name The name (local part) of the XML element * @param string $type The XML schema type (local part) for the element * @param string $name_ns The namespace for the name of the XML element * @param string $type_ns The namespace for the type of the element * @param array $attributes The attributes to serialize as name=>value pairs * @param string $use The WSDL "use" (encoded|literal) * @param boolean $soapval Whether this is called from soapval. * @return string The serialized element, possibly with child elements * @access public */ function serialize_val($val,$name=false,$type=false,$name_ns=false,$type_ns=false,$attributes=false,$use='encoded',$soapval=false) { $this->debug("in serialize_val: name=$name, type=$type, name_ns=$name_ns, type_ns=$type_ns, use=$use, soapval=$soapval"); $this->appendDebug('value=' . $this->varDump($val)); $this->appendDebug('attributes=' . $this->varDump($attributes)); if (is_object($val) && get_class($val) == 'soapval' && (! $soapval)) { $this->debug("serialize_val: serialize soapval"); $xml = $val->serialize($use); $this->appendDebug($val->getDebug()); $val->clearDebug(); $this->debug("serialize_val of soapval returning $xml"); return $xml; } // force valid name if necessary if (is_numeric($name)) { $name = '__numeric_' . $name; } elseif (! $name) { $name = 'noname'; } // if name has ns, add ns prefix to name $xmlns = ''; if($name_ns){ $prefix = 'nu'.rand(1000,9999); $name = $prefix.':'.$name; $xmlns .= " xmlns:$prefix=\"$name_ns\""; } // if type is prefixed, create type prefix if($type_ns != '' && $type_ns == $this->namespaces['xsd']){ // need to fix this. shouldn't default to xsd if no ns specified // w/o checking against typemap $type_prefix = 'xsd'; } elseif($type_ns){ $type_prefix = 'ns'.rand(1000,9999); $xmlns .= " xmlns:$type_prefix=\"$type_ns\""; } // serialize attributes if present $atts = ''; if($attributes){ foreach($attributes as $k => $v){ $atts .= " $k=\"".$this->expandEntities($v).'"'; } } // serialize null value if (is_null($val)) { $this->debug("serialize_val: serialize null"); if ($use == 'literal') { // TODO: depends on minOccurs $xml = "<$name$xmlns$atts/>"; $this->debug("serialize_val returning $xml"); return $xml; } else { if (isset($type) && isset($type_prefix)) { $type_str = " xsi:type=\"$type_prefix:$type\""; } else { $type_str = ''; } $xml = "<$name$xmlns$type_str$atts xsi:nil=\"true\"/>"; $this->debug("serialize_val returning $xml"); return $xml; } } // serialize if an xsd built-in primitive type if($type != '' && isset($this->typemap[$this->XMLSchemaVersion][$type])){ $this->debug("serialize_val: serialize xsd built-in primitive type"); if (is_bool($val)) { if ($type == 'boolean') { $val = $val ? 'true' : 'false'; } elseif (! $val) { $val = 0; } } else if (is_string($val)) { $val = $this->expandEntities($val); } if ($use == 'literal') { $xml = "<$name$xmlns$atts>$val"; $this->debug("serialize_val returning $xml"); return $xml; } else { $xml = "<$name$xmlns xsi:type=\"xsd:$type\"$atts>$val"; $this->debug("serialize_val returning $xml"); return $xml; } } // detect type and serialize $xml = ''; switch(true) { case (is_bool($val) || $type == 'boolean'): $this->debug("serialize_val: serialize boolean"); if ($type == 'boolean') { $val = $val ? 'true' : 'false'; } elseif (! $val) { $val = 0; } if ($use == 'literal') { $xml .= "<$name$xmlns$atts>$val"; } else { $xml .= "<$name$xmlns xsi:type=\"xsd:boolean\"$atts>$val"; } break; case (is_int($val) || is_long($val) || $type == 'int'): $this->debug("serialize_val: serialize int"); if ($use == 'literal') { $xml .= "<$name$xmlns$atts>$val"; } else { $xml .= "<$name$xmlns xsi:type=\"xsd:int\"$atts>$val"; } break; case (is_float($val)|| is_double($val) || $type == 'float'): $this->debug("serialize_val: serialize float"); if ($use == 'literal') { $xml .= "<$name$xmlns$atts>$val"; } else { $xml .= "<$name$xmlns xsi:type=\"xsd:float\"$atts>$val"; } break; case (is_string($val) || $type == 'string'): $this->debug("serialize_val: serialize string"); $val = $this->expandEntities($val); if ($use == 'literal') { $xml .= "<$name$xmlns$atts>$val"; } else { $xml .= "<$name$xmlns xsi:type=\"xsd:string\"$atts>$val"; } break; case is_object($val): $this->debug("serialize_val: serialize object"); if (get_class($val) == 'soapval') { $this->debug("serialize_val: serialize soapval object"); $pXml = $val->serialize($use); $this->appendDebug($val->getDebug()); $val->clearDebug(); } else { if (! $name) { $name = get_class($val); $this->debug("In serialize_val, used class name $name as element name"); } else { $this->debug("In serialize_val, do not override name $name for element name for class " . get_class($val)); } foreach(get_object_vars($val) as $k => $v){ $pXml = isset($pXml) ? $pXml.$this->serialize_val($v,$k,false,false,false,false,$use) : $this->serialize_val($v,$k,false,false,false,false,$use); } } if(isset($type) && isset($type_prefix)){ $type_str = " xsi:type=\"$type_prefix:$type\""; } else { $type_str = ''; } if ($use == 'literal') { $xml .= "<$name$xmlns$atts>$pXml"; } else { $xml .= "<$name$xmlns$type_str$atts>$pXml"; } break; break; case (is_array($val) || $type): // detect if struct or array $valueType = $this->isArraySimpleOrStruct($val); if($valueType=='arraySimple' || ereg('^ArrayOf',$type)){ $this->debug("serialize_val: serialize array"); $i = 0; if(is_array($val) && count($val)> 0){ foreach($val as $v){ if(is_object($v) && get_class($v) == 'soapval'){ $tt_ns = $v->type_ns; $tt = $v->type; } elseif (is_array($v)) { $tt = $this->isArraySimpleOrStruct($v); } else { $tt = gettype($v); } $array_types[$tt] = 1; // TODO: for literal, the name should be $name $xml .= $this->serialize_val($v,'item',false,false,false,false,$use); ++$i; } if(count($array_types) > 1){ $array_typename = 'xsd:anyType'; } elseif(isset($tt) && isset($this->typemap[$this->XMLSchemaVersion][$tt])) { if ($tt == 'integer') { $tt = 'int'; } $array_typename = 'xsd:'.$tt; } elseif(isset($tt) && $tt == 'arraySimple'){ $array_typename = 'SOAP-ENC:Array'; } elseif(isset($tt) && $tt == 'arrayStruct'){ $array_typename = 'unnamed_struct_use_soapval'; } else { // if type is prefixed, create type prefix if ($tt_ns != '' && $tt_ns == $this->namespaces['xsd']){ $array_typename = 'xsd:' . $tt; } elseif ($tt_ns) { $tt_prefix = 'ns' . rand(1000, 9999); $array_typename = "$tt_prefix:$tt"; $xmlns .= " xmlns:$tt_prefix=\"$tt_ns\""; } else { $array_typename = $tt; } } $array_type = $i; if ($use == 'literal') { $type_str = ''; } else if (isset($type) && isset($type_prefix)) { $type_str = " xsi:type=\"$type_prefix:$type\""; } else { $type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"".$array_typename."[$array_type]\""; } // empty array } else { if ($use == 'literal') { $type_str = ''; } else if (isset($type) && isset($type_prefix)) { $type_str = " xsi:type=\"$type_prefix:$type\""; } else { $type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"xsd:anyType[0]\""; } } // TODO: for array in literal, there is no wrapper here $xml = "<$name$xmlns$type_str$atts>".$xml.""; } else { // got a struct $this->debug("serialize_val: serialize struct"); if(isset($type) && isset($type_prefix)){ $type_str = " xsi:type=\"$type_prefix:$type\""; } else { $type_str = ''; } if ($use == 'literal') { $xml .= "<$name$xmlns$atts>"; } else { $xml .= "<$name$xmlns$type_str$atts>"; } foreach($val as $k => $v){ // Apache Map if ($type == 'Map' && $type_ns == 'http://xml.apache.org/xml-soap') { $xml .= ''; $xml .= $this->serialize_val($k,'key',false,false,false,false,$use); $xml .= $this->serialize_val($v,'value',false,false,false,false,$use); $xml .= ''; } else { $xml .= $this->serialize_val($v,$k,false,false,false,false,$use); } } $xml .= ""; } break; default: $this->debug("serialize_val: serialize unknown"); $xml .= 'not detected, got '.gettype($val).' for '.$val; break; } $this->debug("serialize_val returning $xml"); return $xml; } /** * serializes a message * * @param string $body the XML of the SOAP body * @param mixed $headers optional string of XML with SOAP header content, or array of soapval objects for SOAP headers, or associative array * @param array $namespaces optional the namespaces used in generating the body and headers * @param string $style optional (rpc|document) * @param string $use optional (encoded|literal) * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded) * @return string the message * @access public */ function serializeEnvelope($body,$headers=false,$namespaces=array(),$style='rpc',$use='encoded',$encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'){ // TODO: add an option to automatically run utf8_encode on $body and $headers // if $this->soap_defencoding is UTF-8. Not doing this automatically allows // one to send arbitrary UTF-8 characters, not just characters that map to ISO-8859-1 $this->debug("In serializeEnvelope length=" . strlen($body) . " body (max 1000 characters)=" . substr($body, 0, 1000) . " style=$style use=$use encodingStyle=$encodingStyle"); $this->debug("headers:"); $this->appendDebug($this->varDump($headers)); $this->debug("namespaces:"); $this->appendDebug($this->varDump($namespaces)); // serialize namespaces $ns_string = ''; foreach(array_merge($this->namespaces,$namespaces) as $k => $v){ $ns_string .= " xmlns:$k=\"$v\""; } if($encodingStyle) { $ns_string = " SOAP-ENV:encodingStyle=\"$encodingStyle\"$ns_string"; } // serialize headers if($headers){ if (is_array($headers)) { $xml = ''; foreach ($headers as $k => $v) { if (is_object($v) && get_class($v) == 'soapval') { $xml .= $this->serialize_val($v, false, false, false, false, false, $use); } else { $xml .= $this->serialize_val($v, $k, false, false, false, false, $use); } } $headers = $xml; $this->debug("In serializeEnvelope, serialized array of headers to $headers"); } $headers = "".$headers.""; } // serialize envelope return 'soap_defencoding .'"?'.">". '". $headers. "". $body. "". ""; } /** * formats a string to be inserted into an HTML stream * * @param string $str The string to format * @return string The formatted string * @access public * @deprecated */ function formatDump($str){ $str = htmlspecialchars($str); return nl2br($str); } /** * contracts (changes namespace to prefix) a qualified name * * @param string $qname qname * @return string contracted qname * @access private */ function contractQname($qname){ // get element namespace //$this->xdebug("Contract $qname"); if (strrpos($qname, ':')) { // get unqualified name $name = substr($qname, strrpos($qname, ':') + 1); // get ns $ns = substr($qname, 0, strrpos($qname, ':')); $p = $this->getPrefixFromNamespace($ns); if ($p) { return $p . ':' . $name; } return $qname; } else { return $qname; } } /** * expands (changes prefix to namespace) a qualified name * * @param string $qname qname * @return string expanded qname * @access private */ function expandQname($qname){ // get element prefix if(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; } } /** * returns the local part of a prefixed string * returns the original string, if not prefixed * * @param string $str The prefixed string * @return string The local part * @access public */ function getLocalPart($str){ if($sstr = strrchr($str,':')){ // get unqualified name return substr( $sstr, 1 ); } else { return $str; } } /** * returns the prefix part of a prefixed string * returns false, if not prefixed * * @param string $str The prefixed string * @return mixed The prefix or false if there is no prefix * @access public */ function getPrefix($str){ if($pos = strrpos($str,':')){ // get prefix return substr($str,0,$pos); } return false; } /** * pass it a prefix, it returns a namespace * * @param string $prefix The prefix * @return mixed The namespace, false if no namespace has the specified prefix * @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 $ns The namespace * @return mixed The prefix, false if the namespace has no prefixes * @access public */ function getPrefixFromNamespace($ns) { foreach ($this->namespaces as $p => $n) { if ($ns == $n || $ns == $p) { $this->usedNamespaces[$p] = $n; return $p; } } return false; } /** * returns the time in ODBC canonical form with microseconds * * @return string The time in ODBC canonical form with microseconds * @access public */ function getmicrotime() { if (function_exists('gettimeofday')) { $tod = gettimeofday(); $sec = $tod['sec']; $usec = $tod['usec']; } else { $sec = time(); $usec = 0; } return strftime('%Y-%m-%d %H:%M:%S', $sec) . '.' . sprintf('%06d', $usec); } /** * Returns a string with the output of var_dump * * @param mixed $data The variable to var_dump * @return string The output of var_dump * @access public */ function varDump($data) { ob_start(); var_dump($data); $ret_val = ob_get_contents(); ob_end_clean(); return $ret_val; } /** * represents the object as a string * * @return string * @access public */ function __toString() { return $this->varDump($this); } } // XML Schema Datatype Helper Functions //xsd:dateTime helpers /** * convert unix timestamp to ISO 8601 compliant date string * * @param string $timestamp Unix time stamp * @param boolean $utc Whether the time stamp is UTC or local * @access public */ function timestamp_to_iso8601($timestamp,$utc=true){ $datestr = date('Y-m-d\TH:i:sO',$timestamp); if($utc){ $eregStr = '([0-9]{4})-'. // centuries & years CCYY- '([0-9]{2})-'. // months MM- '([0-9]{2})'. // days DD 'T'. // separator T '([0-9]{2}):'. // hours hh: '([0-9]{2}):'. // minutes mm: '([0-9]{2})(\.[0-9]*)?'. // seconds ss.ss... '(Z|[+\-][0-9]{2}:?[0-9]{2})?'; // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's if(ereg($eregStr,$datestr,$regs)){ return sprintf('%04d-%02d-%02dT%02d:%02d:%02dZ',$regs[1],$regs[2],$regs[3],$regs[4],$regs[5],$regs[6]); } return false; } else { return $datestr; } } /** * convert ISO 8601 compliant date string to unix timestamp * * @param string $datestr ISO 8601 compliant date string * @access public */ function iso8601_to_timestamp($datestr){ $eregStr = '([0-9]{4})-'. // centuries & years CCYY- '([0-9]{2})-'. // months MM- '([0-9]{2})'. // days DD 'T'. // separator T '([0-9]{2}):'. // hours hh: '([0-9]{2}):'. // minutes mm: '([0-9]{2})(\.[0-9]+)?'. // seconds ss.ss... '(Z|[+\-][0-9]{2}:?[0-9]{2})?'; // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's if(ereg($eregStr,$datestr,$regs)){ // not utc if($regs[8] != 'Z'){ $op = substr($regs[8],0,1); $h = substr($regs[8],1,2); $m = substr($regs[8],strlen($regs[8])-2,2); if($op == '-'){ $regs[4] = $regs[4] + $h; $regs[5] = $regs[5] + $m; } elseif($op == '+'){ $regs[4] = $regs[4] - $h; $regs[5] = $regs[5] - $m; } } return gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]); // return strtotime("$regs[1]-$regs[2]-$regs[3] $regs[4]:$regs[5]:$regs[6]Z"); } else { return false; } } /** * sleeps some number of microseconds * * @param string $usec the number of microseconds to sleep * @access public * @deprecated */ function usleepWindows($usec) { $start = gettimeofday(); do { $stop = gettimeofday(); $timePassed = 1000000 * ($stop['sec'] - $start['sec']) + $stop['usec'] - $start['usec']; } while ($timePassed < $usec); } ?> * @version $Id: nusoap.php,v 1.114 2007/11/06 15:17:46 snichol Exp $ * @access public */ class nusoap_fault extends nusoap_base { /** * The fault code (client|server) * @var string * @access private */ var $faultcode; /** * The fault actor * @var string * @access private */ var $faultactor; /** * The fault string, a description of the fault * @var string * @access private */ var $faultstring; /** * The fault detail, typically a string or array of string * @var mixed * @access private */ var $faultdetail; /** * constructor * * @param string $faultcode (SOAP-ENV:Client | SOAP-ENV:Server) * @param string $faultactor only used when msg routed between multiple actors * @param string $faultstring human readable error message * @param mixed $faultdetail detail, typically a string or array of string */ function nusoap_fault($faultcode,$faultactor='',$faultstring='',$faultdetail=''){ parent::nusoap_base(); $this->faultcode = $faultcode; $this->faultactor = $faultactor; $this->faultstring = $faultstring; $this->faultdetail = $faultdetail; } /** * serialize a fault * * @return string The serialization of the fault instance. * @access public */ function serialize(){ $ns_string = ''; foreach($this->namespaces as $k => $v){ $ns_string .= "\n xmlns:$k=\"$v\""; } $return_msg = 'soap_defencoding.'"?>'. '\n". ''. ''. $this->serialize_val($this->faultcode, 'faultcode'). $this->serialize_val($this->faultactor, 'faultactor'). $this->serialize_val($this->faultstring, 'faultstring'). $this->serialize_val($this->faultdetail, 'detail'). ''. ''. ''; return $return_msg; } } /** * Backward compatibility */ class soap_fault extends nusoap_fault { } ?> * @author Scott Nichol * @version $Id: nusoap.php,v 1.114 2007/11/06 15:17:46 snichol Exp $ * @access public */ class nusoap_xmlschema extends nusoap_base { // files var $schema = ''; var $xml = ''; // namespaces var $enclosingNamespaces; // schema info var $schemaInfo = array(); var $schemaTargetNamespace = ''; // types, elements, attributes defined by the schema var $attributes = array(); var $complexTypes = array(); var $complexTypeStack = array(); var $currentComplexType = null; var $elements = array(); var $elementStack = array(); var $currentElement = null; var $simpleTypes = array(); var $simpleTypeStack = array(); var $currentSimpleType = null; // imports var $imports = array(); // parser vars var $parser; var $position = 0; var $depth = 0; var $depth_array = array(); var $message = array(); var $defaultNamespace = array(); /** * constructor * * @param string $schema schema document URI * @param string $xml xml document URI * @param string $namespaces namespaces defined in enclosing XML * @access public */ function nusoap_xmlschema($schema='',$xml='',$namespaces=array()){ parent::nusoap_base(); $this->debug('nusoap_xmlschema class instantiated, inside constructor'); // files $this->schema = $schema; $this->xml = $xml; // namespaces $this->enclosingNamespaces = $namespaces; $this->namespaces = array_merge($this->namespaces, $namespaces); // parse schema file if($schema != ''){ $this->debug('initial schema file: '.$schema); $this->parseFile($schema, 'schema'); } // parse xml file if($xml != ''){ $this->debug('initial xml file: '.$xml); $this->parseFile($xml, '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 file if($xml != ""){ $xmlStr = @join("",@file($xml)); if($xmlStr == ""){ $msg = 'Error reading XML from '.$xml; $this->setError($msg); $this->debug($msg); return false; } else { $this->debug("parsing $xml"); $this->parseString($xmlStr,$type); $this->debug("done parsing $xml"); 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 string if($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 parsing XML schema on line %d: %s', xml_get_current_line_number($this->parser), xml_error_string(xml_get_error_code($this->parser)) ); $this->debug($errstr); $this->debug("XML payload:\n" . $xml); $this->setError($errstr); } xml_parser_free($this->parser); } else{ $this->debug('no xml passed to parseString()!!'); $this->setError('no xml passed to parseString()!!'); } } /** * gets a type name for an unnamed type * * @param string Element name * @return string A type name for an unnamed type * @access private */ function CreateTypeName($ename) { $scope = ''; for ($i = 0; $i < count($this->complexTypeStack); $i++) { $scope .= $this->complexTypeStack[$i] . '_'; } return $scope . $ename . '_ContainedType'; } /** * 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; $this->message[$pos] = array('cdata' => ''); if ($depth > 0) { $this->defaultNamespace[$pos] = $this->defaultNamespace[$this->depth_array[$depth - 1]]; } else { $this->defaultNamespace[$pos] = false; } // get element prefix if($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 namespaces if(ereg("^xmlns",$k)){ //$this->xdebug("$k: $v"); //$this->xdebug('ns_prefix: '.$this->getPrefix($k)); if($ns_prefix = substr(strrchr($k,':'),1)){ //$this->xdebug("Add namespace[$ns_prefix] = $v"); $this->namespaces[$ns_prefix] = $v; } else { $this->defaultNamespace[$pos] = $v; if (! $this->getPrefixFromNamespace($v)) { $this->namespaces['ns'.(count($this->namespaces)+1)] = $v; } } if($v == 'http://www.w3.org/2001/XMLSchema' || $v == 'http://www.w3.org/1999/XMLSchema' || $v == 'http://www.w3.org/2000/10/XMLSchema'){ $this->XMLSchemaVersion = $v; $this->namespaces['xsi'] = $v.'-instance'; } } } foreach($attrs as $k => $v){ // 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 data switch($name){ case 'all': // (optional) compositor content for a complexType case 'choice': case 'group': case 'sequence': //$this->xdebug("compositor $name for currentComplexType: $this->currentComplexType and currentElement: $this->currentElement"); $this->complexTypes[$this->currentComplexType]['compositor'] = $name; //if($name == 'all' || $name == 'sequence'){ // $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct'; //} break; case 'attribute': // complexType attribute //$this->xdebug("parsing attribute $attrs[name] $attrs[ref] of value: ".$attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']); $this->xdebug("parsing attribute:"); $this->appendDebug($this->varDump($attrs)); if (!isset($attrs['form'])) { $attrs['form'] = $this->schemaInfo['attributeFormDefault']; } if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) { $v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; if (!strpos($v, ':')) { // no namespace in arrayType attribute value... if ($this->defaultNamespace[$pos]) { // ...so use the default $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'] = $this->defaultNamespace[$pos] . ':' . $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; } } } if(isset($attrs['name'])){ $this->attributes[$attrs['name']] = $attrs; $aname = $attrs['name']; } elseif(isset($attrs['ref']) && $attrs['ref'] == 'http://schemas.xmlsoap.org/soap/encoding/:arrayType'){ if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) { $aname = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; } else { $aname = ''; } } elseif(isset($attrs['ref'])){ $aname = $attrs['ref']; $this->attributes[$attrs['ref']] = $attrs; } if($this->currentComplexType){ // This should *always* be $this->complexTypes[$this->currentComplexType]['attrs'][$aname] = $attrs; } // arrayType attribute if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']) || $this->getLocalPart($aname) == 'arrayType'){ $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; $prefix = $this->getPrefix($aname); 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 'complexContent': // (optional) content for a complexType break; case 'complexType': array_push($this->complexTypeStack, $this->currentComplexType); if(isset($attrs['name'])){ // TODO: what is the scope of named complexTypes that appear // nested within other c complexTypes? $this->xdebug('processing named complexType '.$attrs['name']); //$this->currentElement = false; $this->currentComplexType = $attrs['name']; $this->complexTypes[$this->currentComplexType] = $attrs; $this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType'; // This is for constructs like // // // // // if(isset($attrs['base']) && ereg(':Array$',$attrs['base'])){ $this->xdebug('complexType is unusual array'); $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; } else { $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct'; } } else { $name = $this->CreateTypeName($this->currentElement); $this->xdebug('processing unnamed complexType for element ' . $this->currentElement . ' named ' . $name); $this->currentComplexType = $name; //$this->currentElement = false; $this->complexTypes[$this->currentComplexType] = $attrs; $this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType'; // This is for constructs like // // // // // if(isset($attrs['base']) && ereg(':Array$',$attrs['base'])){ $this->xdebug('complexType is unusual array'); $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; } else { $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct'; } } break; case 'element': array_push($this->elementStack, $this->currentElement); if (!isset($attrs['form'])) { $attrs['form'] = $this->schemaInfo['elementFormDefault']; } if(isset($attrs['type'])){ $this->xdebug("processing typed element ".$attrs['name']." of type ".$attrs['type']); if (! $this->getPrefix($attrs['type'])) { if ($this->defaultNamespace[$pos]) { $attrs['type'] = $this->defaultNamespace[$pos] . ':' . $attrs['type']; $this->xdebug('used default namespace to make type ' . $attrs['type']); } } // This is for constructs like // // // // // if ($this->currentComplexType && $this->complexTypes[$this->currentComplexType]['phpType'] == 'array') { $this->xdebug('arrayType for unusual array is ' . $attrs['type']); $this->complexTypes[$this->currentComplexType]['arrayType'] = $attrs['type']; } $this->currentElement = $attrs['name']; $ename = $attrs['name']; } elseif(isset($attrs['ref'])){ $this->xdebug("processing element as ref to ".$attrs['ref']); $this->currentElement = "ref to ".$attrs['ref']; $ename = $this->getLocalPart($attrs['ref']); } else { $type = $this->CreateTypeName($this->currentComplexType . '_' . $attrs['name']); $this->xdebug("processing untyped element " . $attrs['name'] . ' type ' . $type); $this->currentElement = $attrs['name']; $attrs['type'] = $this->schemaTargetNamespace . ':' . $type; $ename = $attrs['name']; } if (isset($ename) && $this->currentComplexType) { $this->xdebug("add element $ename to complexType $this->currentComplexType"); $this->complexTypes[$this->currentComplexType]['elements'][$ename] = $attrs; } elseif (!isset($attrs['ref'])) { $this->xdebug("add element $ename to elements array"); $this->elements[ $attrs['name'] ] = $attrs; $this->elements[ $attrs['name'] ]['typeClass'] = 'element'; } break; case 'enumeration': // restriction value list member $this->xdebug('enumeration ' . $attrs['value']); if ($this->currentSimpleType) { $this->simpleTypes[$this->currentSimpleType]['enumeration'][] = $attrs['value']; } elseif ($this->currentComplexType) { $this->complexTypes[$this->currentComplexType]['enumeration'][] = $attrs['value']; } break; case 'extension': // simpleContent or complexContent type extension $this->xdebug('extension ' . $attrs['base']); if ($this->currentComplexType) { $this->complexTypes[$this->currentComplexType]['extensionBase'] = $attrs['base']; } break; case 'import': if (isset($attrs['schemaLocation'])) { //$this->xdebug('import namespace ' . $attrs['namespace'] . ' from ' . $attrs['schemaLocation']); $this->imports[$attrs['namespace']][] = array('location' => $attrs['schemaLocation'], 'loaded' => false); } else { //$this->xdebug('import namespace ' . $attrs['namespace']); $this->imports[$attrs['namespace']][] = array('location' => '', 'loaded' => true); if (! $this->getPrefixFromNamespace($attrs['namespace'])) { $this->namespaces['ns'.(count($this->namespaces)+1)] = $attrs['namespace']; } } break; case 'list': // simpleType value list break; case 'restriction': // simpleType, simpleContent or complexContent value restriction $this->xdebug('restriction ' . $attrs['base']); if($this->currentSimpleType){ $this->simpleTypes[$this->currentSimpleType]['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->schemaInfo = $attrs; $this->schemaInfo['schemaVersion'] = $this->getNamespaceFromPrefix($prefix); if (isset($attrs['targetNamespace'])) { $this->schemaTargetNamespace = $attrs['targetNamespace']; } if (!isset($attrs['elementFormDefault'])) { $this->schemaInfo['elementFormDefault'] = 'unqualified'; } if (!isset($attrs['attributeFormDefault'])) { $this->schemaInfo['attributeFormDefault'] = 'unqualified'; } break; case 'simpleContent': // (optional) content for a complexType break; case 'simpleType': array_push($this->simpleTypeStack, $this->currentSimpleType); if(isset($attrs['name'])){ $this->xdebug("processing simpleType for name " . $attrs['name']); $this->currentSimpleType = $attrs['name']; $this->simpleTypes[ $attrs['name'] ] = $attrs; $this->simpleTypes[ $attrs['name'] ]['typeClass'] = 'simpleType'; $this->simpleTypes[ $attrs['name'] ]['phpType'] = 'scalar'; } else { $name = $this->CreateTypeName($this->currentComplexType . '_' . $this->currentElement); $this->xdebug('processing unnamed simpleType for element ' . $this->currentElement . ' named ' . $name); $this->currentSimpleType = $name; //$this->currentElement = false; $this->simpleTypes[$this->currentSimpleType] = $attrs; $this->simpleTypes[$this->currentSimpleType]['phpType'] = 'scalar'; } break; case 'union': // simpleType type list break; default: //$this->xdebug("do not have anything to do for element $name"); } } /** * end-element handler * * @param string $parser XML parser object * @param string $name element name * @access private */ function schemaEndElement($parser, $name) { // bring depth down a notch $this->depth--; // position of current element is equal to the last value left in depth_array for my depth if(isset($this->depth_array[$this->depth])){ $pos = $this->depth_array[$this->depth]; } // get element prefix if ($prefix = $this->getPrefix($name)){ // get unqualified name $name = $this->getLocalPart($name); } else { $prefix = ''; } // move on... if($name == 'complexType'){ $this->xdebug('done processing complexType ' . ($this->currentComplexType ? $this->currentComplexType : '(unknown)')); $this->currentComplexType = array_pop($this->complexTypeStack); //$this->currentElement = false; } if($name == 'element'){ $this->xdebug('done processing element ' . ($this->currentElement ? $this->currentElement : '(unknown)')); $this->currentElement = array_pop($this->elementStack); } if($name == 'simpleType'){ $this->xdebug('done processing simpleType ' . ($this->currentSimpleType ? $this->currentSimpleType : '(unknown)')); $this->currentSimpleType = array_pop($this->simpleTypeStack); } } /** * 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 - 1]; $this->message[$pos]['cdata'] .= $data; } /** * serialize the schema * * @access public */ function serializeSchema(){ $schemaPrefix = $this->getPrefixFromNamespace($this->XMLSchemaVersion); $xml = ''; // imports if (sizeof($this->imports) > 0) { foreach($this->imports as $ns => $list) { foreach ($list as $ii) { if ($ii['location'] != '') { $xml .= " <$schemaPrefix:import location=\"" . $ii['location'] . '" namespace="' . $ns . "\" />\n"; } else { $xml .= " <$schemaPrefix:import namespace=\"" . $ns . "\" />\n"; } } } } // complex types foreach($this->complexTypes as $typeName => $attrs){ $contentStr = ''; // serialize child elements if(isset($attrs['elements']) && (count($attrs['elements']) > 0)){ foreach($attrs['elements'] as $element => $eParts){ if(isset($eParts['ref'])){ $contentStr .= " <$schemaPrefix:element ref=\"$element\"/>\n"; } else { $contentStr .= " <$schemaPrefix:element name=\"$element\" type=\"" . $this->contractQName($eParts['type']) . "\""; foreach ($eParts as $aName => $aValue) { // handle, e.g., abstract, default, form, minOccurs, maxOccurs, nillable if ($aName != 'name' && $aName != 'type') { $contentStr .= " $aName=\"$aValue\""; } } $contentStr .= "/>\n"; } } // compositor wraps elements if (isset($attrs['compositor']) && ($attrs['compositor'] != '')) { $contentStr = " <$schemaPrefix:$attrs[compositor]>\n".$contentStr." \n"; } } // attributes if(isset($attrs['attrs']) && (count($attrs['attrs']) >= 1)){ foreach($attrs['attrs'] as $attr => $aParts){ $contentStr .= " <$schemaPrefix:attribute"; foreach ($aParts as $a => $v) { if ($a == 'ref' || $a == 'type') { $contentStr .= " $a=\"".$this->contractQName($v).'"'; } elseif ($a == 'http://schemas.xmlsoap.org/wsdl/:arrayType') { $this->usedNamespaces['wsdl'] = $this->namespaces['wsdl']; $contentStr .= ' wsdl:arrayType="'.$this->contractQName($v).'"'; } else { $contentStr .= " $a=\"$v\""; } } $contentStr .= "/>\n"; } } // if restriction if (isset($attrs['restrictionBase']) && $attrs['restrictionBase'] != ''){ $contentStr = " <$schemaPrefix:restriction base=\"".$this->contractQName($attrs['restrictionBase'])."\">\n".$contentStr." \n"; // complex or simple content if ((isset($attrs['elements']) && count($attrs['elements']) > 0) || (isset($attrs['attrs']) && count($attrs['attrs']) > 0)){ $contentStr = " <$schemaPrefix:complexContent>\n".$contentStr." \n"; } } // finalize complex type if($contentStr != ''){ $contentStr = " <$schemaPrefix:complexType name=\"$typeName\">\n".$contentStr." \n"; } else { $contentStr = " <$schemaPrefix:complexType name=\"$typeName\"/>\n"; } $xml .= $contentStr; } // simple types if(isset($this->simpleTypes) && count($this->simpleTypes) > 0){ foreach($this->simpleTypes as $typeName => $eParts){ $xml .= " <$schemaPrefix:simpleType name=\"$typeName\">\n <$schemaPrefix:restriction base=\"".$this->contractQName($eParts['type'])."\">\n"; if (isset($eParts['enumeration'])) { foreach ($eParts['enumeration'] as $e) { $xml .= " <$schemaPrefix:enumeration value=\"$e\"/>\n"; } } $xml .= " \n "; } } // elements if(isset($this->elements) && count($this->elements) > 0){ foreach($this->elements as $element => $eParts){ $xml .= " <$schemaPrefix:element name=\"$element\" type=\"".$this->contractQName($eParts['type'])."\"/>\n"; } } // attributes if(isset($this->attributes) && count($this->attributes) > 0){ foreach($this->attributes as $attr => $aParts){ $xml .= " <$schemaPrefix:attribute name=\"$attr\" type=\"".$this->contractQName($aParts['type'])."\"\n/>"; } } // finish 'er up $attr = ''; foreach ($this->schemaInfo as $k => $v) { if ($k == 'elementFormDefault' || $k == 'attributeFormDefault') { $attr .= " $k=\"$v\""; } } $el = "<$schemaPrefix:schema$attr targetNamespace=\"$this->schemaTargetNamespace\"\n"; foreach (array_diff($this->usedNamespaces, $this->enclosingNamespaces) as $nsp => $ns) { $el .= " xmlns:$nsp=\"$ns\""; } $xml = $el . ">\n".$xml."\n"; return $xml; } /** * adds debug data to the clas level debug string * * @param string $string debug data * @access private */ function xdebug($string){ $this->debug('<' . $this->schemaTargetNamespace . '> '.$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 * @deprecated */ function getPHPType($type,$ns){ if(isset($this->typemap[$ns][$type])){ //print "found type '$type' and ns $ns in typemap
    "; return $this->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 an associative array of information about a given type * returns false if no type exists by the given name * * For a complexType typeDef = array( * 'restrictionBase' => '', * 'phpType' => '', * 'compositor' => '(sequence|all)', * 'elements' => array(), // refs to elements array * 'attrs' => array() // refs to attributes array * ... and so on (see addComplexType) * ) * * For simpleType or element, the array has different keys. * * @param string $type * @return mixed * @access public * @see addComplexType * @see addSimpleType * @see addElement */ function getTypeDef($type){ //$this->debug("in getTypeDef for type $type"); if (substr($type, -1) == '^') { $is_element = 1; $type = substr($type, 0, -1); } else { $is_element = 0; } if((! $is_element) && isset($this->complexTypes[$type])){ $this->xdebug("in getTypeDef, found complexType $type"); return $this->complexTypes[$type]; } elseif((! $is_element) && isset($this->simpleTypes[$type])){ $this->xdebug("in getTypeDef, found simpleType $type"); if (!isset($this->simpleTypes[$type]['phpType'])) { // get info for type to tack onto the simple type // TODO: can this ever really apply (i.e. what is a simpleType really?) $uqType = substr($this->simpleTypes[$type]['type'], strrpos($this->simpleTypes[$type]['type'], ':') + 1); $ns = substr($this->simpleTypes[$type]['type'], 0, strrpos($this->simpleTypes[$type]['type'], ':')); $etype = $this->getTypeDef($uqType); if ($etype) { $this->xdebug("in getTypeDef, found type for simpleType $type:"); $this->xdebug($this->varDump($etype)); if (isset($etype['phpType'])) { $this->simpleTypes[$type]['phpType'] = $etype['phpType']; } if (isset($etype['elements'])) { $this->simpleTypes[$type]['elements'] = $etype['elements']; } } } return $this->simpleTypes[$type]; } elseif(isset($this->elements[$type])){ $this->xdebug("in getTypeDef, found element $type"); if (!isset($this->elements[$type]['phpType'])) { // get info for type to tack onto the element $uqType = substr($this->elements[$type]['type'], strrpos($this->elements[$type]['type'], ':') + 1); $ns = substr($this->elements[$type]['type'], 0, strrpos($this->elements[$type]['type'], ':')); $etype = $this->getTypeDef($uqType); if ($etype) { $this->xdebug("in getTypeDef, found type for element $type:"); $this->xdebug($this->varDump($etype)); if (isset($etype['phpType'])) { $this->elements[$type]['phpType'] = $etype['phpType']; } if (isset($etype['elements'])) { $this->elements[$type]['elements'] = $etype['elements']; } } elseif ($ns == 'http://www.w3.org/2001/XMLSchema') { $this->xdebug("in getTypeDef, element $type is an XSD type"); $this->elements[$type]['phpType'] = 'scalar'; } } return $this->elements[$type]; } elseif(isset($this->attributes[$type])){ $this->xdebug("in getTypeDef, found attribute $type"); return $this->attributes[$type]; } elseif (ereg('_ContainedType$', $type)) { $this->xdebug("in getTypeDef, have an untyped element $type"); $typeDef['typeClass'] = 'simpleType'; $typeDef['phpType'] = 'scalar'; $typeDef['type'] = 'http://www.w3.org/2001/XMLSchema:string'; return $typeDef; } $this->xdebug("in getTypeDef, did not find $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 * @deprecated */ function serializeTypeDef($type){ //print "in sTD() for type $type
    "; if($typeDef = $this->getTypeDef($type)){ $str .= '<'.$type; if(is_array($typeDef['attrs'])){ foreach($typeDef['attrs'] as $attName => $data){ $str .= " $attName=\"{type = ".$data['type']."}\""; } } $str .= " xmlns=\"".$this->schema['targetNamespace']."\""; if(count($typeDef['elements']) > 0){ $str .= ">"; foreach($typeDef['elements'] as $element => $eData){ $str .= $this->serializeTypeDef($element); } $str .= ""; } elseif($typeDef['typeClass'] == 'element') { $str .= ">"; } else { $str .= "/>"; } return $str; } return false; } /** * returns HTML form elements that allow a user * to enter values for creating an instance of the given type. * * @param string $name name for type instance * @param string $type name of type * @return string * @access public * @deprecated */ function typeToForm($name,$type){ // get typedef if($typeDef = $this->getTypeDef($type)){ // if struct if($typeDef['phpType'] == 'struct'){ $buffer .= ''; foreach($typeDef['elements'] as $child => $childDef){ $buffer .= " "; } $buffer .= '
    $childDef[name] (type: ".$this->getLocalPart($childDef['type'])."):
    '; // if array } elseif($typeDef['phpType'] == 'array'){ $buffer .= ''; for($i=0;$i < 3; $i++){ $buffer .= " "; } $buffer .= '
    array item (type: $typeDef[arrayType]):
    '; // if scalar } else { $buffer .= ""; } } else { $buffer .= ""; } return $buffer; } /** * adds a complex type to the schema * * example: array * * addType( * 'ArrayOfstring', * 'complexType', * 'array', * '', * 'SOAP-ENC:Array', * array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'string[]'), * 'xsd:string' * ); * * example: PHP associative array ( SOAP Struct ) * * addType( * 'SOAPStruct', * 'complexType', * 'struct', * 'all', * array('myVar'=> array('name'=>'myVar','type'=>'string') * ); * * @param name * @param typeClass (complexType|simpleType|attribute) * @param phpType: currently supported are array and struct (php assoc array) * @param compositor (all|sequence|choice) * @param restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array) * @param elements = array ( name = array(name=>'',type=>'') ) * @param attrs = array( * array( * 'ref' => "http://schemas.xmlsoap.org/soap/encoding/:arrayType", * "http://schemas.xmlsoap.org/wsdl/:arrayType" => "string[]" * ) * ) * @param arrayType: namespace:name (http://www.w3.org/2001/XMLSchema:string) * @access public * @see getTypeDef */ function addComplexType($name,$typeClass='complexType',$phpType='array',$compositor='',$restrictionBase='',$elements=array(),$attrs=array(),$arrayType=''){ $this->complexTypes[$name] = array( 'name' => $name, 'typeClass' => $typeClass, 'phpType' => $phpType, 'compositor'=> $compositor, 'restrictionBase' => $restrictionBase, 'elements' => $elements, 'attrs' => $attrs, 'arrayType' => $arrayType ); $this->xdebug("addComplexType $name:"); $this->appendDebug($this->varDump($this->complexTypes[$name])); } /** * adds a simple type to the schema * * @param string $name * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array) * @param string $typeClass (should always be simpleType) * @param string $phpType (should always be scalar) * @param array $enumeration array of values * @access public * @see nusoap_xmlschema * @see getTypeDef */ function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) { $this->simpleTypes[$name] = array( 'name' => $name, 'typeClass' => $typeClass, 'phpType' => $phpType, 'type' => $restrictionBase, 'enumeration' => $enumeration ); $this->xdebug("addSimpleType $name:"); $this->appendDebug($this->varDump($this->simpleTypes[$name])); } /** * adds an element to the schema * * @param array $attrs attributes that must include name and type * @see nusoap_xmlschema * @access public */ function addElement($attrs) { if (! $this->getPrefix($attrs['type'])) { $attrs['type'] = $this->schemaTargetNamespace . ':' . $attrs['type']; } $this->elements[ $attrs['name'] ] = $attrs; $this->elements[ $attrs['name'] ]['typeClass'] = 'element'; $this->xdebug("addElement " . $attrs['name']); $this->appendDebug($this->varDump($this->elements[ $attrs['name'] ])); } } /** * Backward compatibility */ class XMLSchema extends nusoap_xmlschema { } ?> * @version $Id: nusoap.php,v 1.114 2007/11/06 15:17:46 snichol Exp $ * @access public */ class soapval extends nusoap_base { /** * The XML element name * * @var string * @access private */ var $name; /** * The XML type name (string or false) * * @var mixed * @access private */ var $type; /** * The PHP value * * @var mixed * @access private */ var $value; /** * The XML element namespace (string or false) * * @var mixed * @access private */ var $element_ns; /** * The XML type namespace (string or false) * * @var mixed * @access private */ var $type_ns; /** * The XML element attributes (array or false) * * @var mixed * @access private */ var $attributes; /** * constructor * * @param string $name optional name * @param mixed $type optional type name * @param mixed $value optional value * @param mixed $element_ns optional namespace of value * @param mixed $type_ns optional namespace of type * @param mixed $attributes associative array of attributes to add to element serialization * @access public */ function soapval($name='soapval',$type=false,$value=-1,$element_ns=false,$type_ns=false,$attributes=false) { parent::nusoap_base(); $this->name = $name; $this->type = $type; $this->value = $value; $this->element_ns = $element_ns; $this->type_ns = $type_ns; $this->attributes = $attributes; } /** * return serialized value * * @param string $use The WSDL use value (encoded|literal) * @return string XML data * @access public */ function serialize($use='encoded') { return $this->serialize_val($this->value, $this->name, $this->type, $this->element_ns, $this->type_ns, $this->attributes, $use, true); } /** * decodes a soapval object into a PHP native type * * @return mixed * @access public */ function decode(){ return $this->value; } } ?> * @author Scott Nichol * @version $Id: nusoap.php,v 1.114 2007/11/06 15:17:46 snichol Exp $ * @access public */ class soap_transport_http extends nusoap_base { var $url = ''; var $uri = ''; var $digest_uri = ''; var $scheme = ''; var $host = ''; var $port = ''; var $path = ''; var $request_method = 'POST'; var $protocol_version = '1.0'; var $encoding = ''; var $outgoing_headers = array(); var $incoming_headers = array(); var $incoming_cookies = array(); var $outgoing_payload = ''; var $incoming_payload = ''; var $response_status_line; // HTTP response status line var $useSOAPAction = true; var $persistentConnection = false; var $ch = false; // cURL handle var $ch_options = array(); // cURL custom options var $use_curl = false; // force cURL use var $proxy = null; // proxy information (associative array) var $username = ''; var $password = ''; var $authtype = ''; var $digestRequest = array(); var $certRequest = array(); // keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, certpassword (optional), verifypeer (optional), verifyhost (optional) // cainfofile: certificate authority file, e.g. '$pathToPemFiles/rootca.pem' // sslcertfile: SSL certificate file, e.g. '$pathToPemFiles/mycert.pem' // sslkeyfile: SSL key file, e.g. '$pathToPemFiles/mykey.pem' // passphrase: SSL key password/passphrase // certpassword: SSL certificate password // verifypeer: default is 1 // verifyhost: default is 1 /** * constructor * * @param string $url The URL to which to connect * @param array $curl_options User-specified cURL options * @param boolean $use_curl Whether to try to force cURL use * @access public */ function soap_transport_http($url, $curl_options = NULL, $use_curl = false){ parent::nusoap_base(); $this->debug("ctor url=$url use_curl=$use_curl curl_options:"); $this->appendDebug($this->varDump($curl_options)); $this->setURL($url); if (is_array($curl_options)) { $this->ch_options = $curl_options; } $this->use_curl = $use_curl; ereg('\$Revisio' . 'n: ([^ ]+)', $this->revision, $rev); $this->setHeader('User-Agent', $this->title.'/'.$this->version.' ('.$rev[1].')'); } /** * sets a cURL option * * @param mixed $option The cURL option (always integer?) * @param mixed $value The cURL option value * @access private */ function setCurlOption($option, $value) { $this->debug("setCurlOption option=$option, value="); $this->appendDebug($this->varDump($value)); curl_setopt($this->ch, $option, $value); } /** * sets an HTTP header * * @param string $name The name of the header * @param string $value The value of the header * @access private */ function setHeader($name, $value) { $this->outgoing_headers[$name] = $value; $this->debug("set header $name: $value"); } /** * unsets an HTTP header * * @param string $name The name of the header * @access private */ function unsetHeader($name) { if (isset($this->outgoing_headers[$name])) { $this->debug("unset header $name"); unset($this->outgoing_headers[$name]); } } /** * sets the URL to which to connect * * @param string $url The URL to which to connect * @access private */ function setURL($url) { $this->url = $url; $u = parse_url($url); foreach($u as $k => $v){ $this->debug("parsed URL $k = $v"); $this->$k = $v; } // add any GET params to path if(isset($u['query']) && $u['query'] != ''){ $this->path .= '?' . $u['query']; } // set default port if(!isset($u['port'])){ if($u['scheme'] == 'https'){ $this->port = 443; } else { $this->port = 80; } } $this->uri = $this->path; $this->digest_uri = $this->uri; // build headers if (!isset($u['port'])) { $this->setHeader('Host', $this->host); } else { $this->setHeader('Host', $this->host.':'.$this->port); } if (isset($u['user']) && $u['user'] != '') { $this->setCredentials(urldecode($u['user']), isset($u['pass']) ? urldecode($u['pass']) : ''); } } /** * gets the I/O method to use * * @return string I/O method to use (socket|curl|unknown) * @access private */ function io_method() { if ($this->use_curl || ($this->scheme == 'https') || ($this->scheme == 'http' && $this->authtype == 'ntlm') || ($this->scheme == 'http' && is_array($this->proxy) && $this->proxy['authtype'] == 'ntlm')) return 'curl'; if (($this->scheme == 'http' || $this->scheme == 'ssl') && $this->authtype != 'ntlm' && (!is_array($this->proxy) || $this->proxy['authtype'] != 'ntlm')) return 'socket'; return 'unknown'; } /** * establish an HTTP connection * * @param integer $timeout set connection timeout in seconds * @param integer $response_timeout set response timeout in seconds * @return boolean true if connected, false if not * @access private */ function connect($connection_timeout=0,$response_timeout=30){ // For PHP 4.3 with OpenSSL, change https scheme to ssl, then treat like // "regular" socket. // TODO: disabled for now because OpenSSL must be *compiled* in (not just // loaded), and until PHP5 stream_get_wrappers is not available. // if ($this->scheme == 'https') { // if (version_compare(phpversion(), '4.3.0') >= 0) { // if (extension_loaded('openssl')) { // $this->scheme = 'ssl'; // $this->debug('Using SSL over OpenSSL'); // } // } // } $this->debug("connect connection_timeout $connection_timeout, response_timeout $response_timeout, scheme $this->scheme, host $this->host, port $this->port"); if ($this->io_method() == 'socket') { if (!is_array($this->proxy)) { $host = $this->host; $port = $this->port; } else { $host = $this->proxy['host']; $port = $this->proxy['port']; } // use persistent connection if($this->persistentConnection && isset($this->fp) && is_resource($this->fp)){ if (!feof($this->fp)) { $this->debug('Re-use persistent connection'); return true; } fclose($this->fp); $this->debug('Closed persistent connection at EOF'); } // munge host if using OpenSSL if ($this->scheme == 'ssl') { $host = 'ssl://' . $host; } $this->debug('calling fsockopen with host ' . $host . ' connection_timeout ' . $connection_timeout); // open socket if($connection_timeout > 0){ $this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str, $connection_timeout); } else { $this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str); } // test pointer if(!$this->fp) { $msg = 'Couldn\'t open socket connection to server ' . $this->url; if ($this->errno) { $msg .= ', Error ('.$this->errno.'): '.$this->error_str; } else { $msg .= ' prior to connect(). This is often a problem looking up the host name.'; } $this->debug($msg); $this->setError($msg); return false; } // set response timeout $this->debug('set response timeout to ' . $response_timeout); socket_set_timeout( $this->fp, $response_timeout); $this->debug('socket connected'); return true; } else if ($this->io_method() == 'curl') { if (!extension_loaded('curl')) { // $this->setError('cURL Extension, or OpenSSL extension w/ PHP version >= 4.3 is required for HTTPS'); $this->setError('The PHP cURL Extension is required for HTTPS or NLTM. You will need to re-build or update your PHP to included cURL.'); return false; } // Avoid warnings when PHP does not have these options if (defined('CURLOPT_CONNECTIONTIMEOUT')) $CURLOPT_CONNECTIONTIMEOUT = CURLOPT_CONNECTIONTIMEOUT; else $CURLOPT_CONNECTIONTIMEOUT = 78; if (defined('CURLOPT_HTTPAUTH')) $CURLOPT_HTTPAUTH = CURLOPT_HTTPAUTH; else $CURLOPT_HTTPAUTH = 107; if (defined('CURLOPT_PROXYAUTH')) $CURLOPT_PROXYAUTH = CURLOPT_PROXYAUTH; else $CURLOPT_PROXYAUTH = 111; if (defined('CURLAUTH_BASIC')) $CURLAUTH_BASIC = CURLAUTH_BASIC; else $CURLAUTH_BASIC = 1; if (defined('CURLAUTH_DIGEST')) $CURLAUTH_DIGEST = CURLAUTH_DIGEST; else $CURLAUTH_DIGEST = 2; if (defined('CURLAUTH_NTLM')) $CURLAUTH_NTLM = CURLAUTH_NTLM; else $CURLAUTH_NTLM = 8; $this->debug('connect using cURL'); // init CURL $this->ch = curl_init(); // set url $hostURL = ($this->port != '') ? "$this->scheme://$this->host:$this->port" : "$this->scheme://$this->host"; // add path $hostURL .= $this->path; $this->setCurlOption(CURLOPT_URL, $hostURL); // follow location headers (re-directs) if (ini_get('safe_mode') || ini_get('open_basedir')) { $this->debug('safe_mode or open_basedir set, so do not set CURLOPT_FOLLOWLOCATION'); $this->debug('safe_mode = '); $this->appendDebug($this->varDump(ini_get('safe_mode'))); $this->debug('open_basedir = '); $this->appendDebug($this->varDump(ini_get('open_basedir'))); } else { $this->setCurlOption(CURLOPT_FOLLOWLOCATION, 1); } // ask for headers in the response output $this->setCurlOption(CURLOPT_HEADER, 1); // ask for the response output as the return value $this->setCurlOption(CURLOPT_RETURNTRANSFER, 1); // encode // We manage this ourselves through headers and encoding // if(function_exists('gzuncompress')){ // $this->setCurlOption(CURLOPT_ENCODING, 'deflate'); // } // persistent connection if ($this->persistentConnection) { // I believe the following comment is now bogus, having applied to // the code when it used CURLOPT_CUSTOMREQUEST to send the request. // The way we send data, we cannot use persistent connections, since // there will be some "junk" at the end of our request. //$this->setCurlOption(CURL_HTTP_VERSION_1_1, true); $this->persistentConnection = false; $this->setHeader('Connection', 'close'); } // set timeouts if ($connection_timeout != 0) { $this->setCurlOption($CURLOPT_CONNECTIONTIMEOUT, $connection_timeout); } if ($response_timeout != 0) { $this->setCurlOption(CURLOPT_TIMEOUT, $response_timeout); } if ($this->scheme == 'https') { $this->debug('set cURL SSL verify options'); // recent versions of cURL turn on peer/host checking by default, // while PHP binaries are not compiled with a default location for the // CA cert bundle, so disable peer/host checking. //$this->setCurlOption(CURLOPT_CAINFO, 'f:\php-4.3.2-win32\extensions\curl-ca-bundle.crt'); $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, 0); $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, 0); // support client certificates (thanks Tobias Boes, Doug Anarino, Eryan Ariobowo) if ($this->authtype == 'certificate') { $this->debug('set cURL certificate options'); if (isset($this->certRequest['cainfofile'])) { $this->setCurlOption(CURLOPT_CAINFO, $this->certRequest['cainfofile']); } if (isset($this->certRequest['verifypeer'])) { $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, $this->certRequest['verifypeer']); } else { $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, 1); } if (isset($this->certRequest['verifyhost'])) { $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, $this->certRequest['verifyhost']); } else { $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, 1); } if (isset($this->certRequest['sslcertfile'])) { $this->setCurlOption(CURLOPT_SSLCERT, $this->certRequest['sslcertfile']); } if (isset($this->certRequest['sslkeyfile'])) { $this->setCurlOption(CURLOPT_SSLKEY, $this->certRequest['sslkeyfile']); } if (isset($this->certRequest['passphrase'])) { $this->setCurlOption(CURLOPT_SSLKEYPASSWD, $this->certRequest['passphrase']); } if (isset($this->certRequest['certpassword'])) { $this->setCurlOption(CURLOPT_SSLCERTPASSWD, $this->certRequest['certpassword']); } } } if ($this->authtype && ($this->authtype != 'certificate')) { if ($this->username) { $this->debug('set cURL username/password'); $this->setCurlOption(CURLOPT_USERPWD, "$this->username:$this->password"); } if ($this->authtype == 'basic') { $this->debug('set cURL for Basic authentication'); $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_BASIC); } if ($this->authtype == 'digest') { $this->debug('set cURL for digest authentication'); $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_DIGEST); } if ($this->authtype == 'ntlm') { $this->debug('set cURL for NTLM authentication'); $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_NTLM); } } if (is_array($this->proxy)) { $this->debug('set cURL proxy options'); if ($this->proxy['port'] != '') { $this->setCurlOption(CURLOPT_PROXY, $this->proxy['host'].':'.$this->proxy['port']); } else { $this->setCurlOption(CURLOPT_PROXY, $this->proxy['host']); } if ($this->proxy['username'] || $this->proxy['password']) { $this->debug('set cURL proxy authentication options'); $this->setCurlOption(CURLOPT_PROXYUSERPWD, $this->proxy['username'].':'.$this->proxy['password']); if ($this->proxy['authtype'] == 'basic') { $this->setCurlOption($CURLOPT_PROXYAUTH, $CURLAUTH_BASIC); } if ($this->proxy['authtype'] == 'ntlm') { $this->setCurlOption($CURLOPT_PROXYAUTH, $CURLAUTH_NTLM); } } } $this->debug('cURL connection set up'); return true; } else { $this->setError('Unknown scheme ' . $this->scheme); $this->debug('Unknown scheme ' . $this->scheme); return false; } } /** * sends the SOAP request and gets the SOAP response via HTTP[S] * * @param string $data message data * @param integer $timeout set connection timeout in seconds * @param integer $response_timeout set response timeout in seconds * @param array $cookies cookies to send * @return string data * @access public */ function send($data, $timeout=0, $response_timeout=30, $cookies=NULL) { $this->debug('entered send() with data of length: '.strlen($data)); $this->tryagain = true; $tries = 0; while ($this->tryagain) { $this->tryagain = false; if ($tries++ < 2) { // make connnection if (!$this->connect($timeout, $response_timeout)){ return false; } // send request if (!$this->sendRequest($data, $cookies)){ return false; } // get response $respdata = $this->getResponse(); } else { $this->setError("Too many tries to get an OK response ($this->response_status_line)"); } } $this->debug('end of send()'); return $respdata; } /** * sends the SOAP request and gets the SOAP response via HTTPS using CURL * * @param string $data message data * @param integer $timeout set connection timeout in seconds * @param integer $response_timeout set response timeout in seconds * @param array $cookies cookies to send * @return string data * @access public * @deprecated */ function sendHTTPS($data, $timeout=0, $response_timeout=30, $cookies) { return $this->send($data, $timeout, $response_timeout, $cookies); } /** * if authenticating, set user credentials here * * @param string $username * @param string $password * @param string $authtype (basic|digest|certificate|ntlm) * @param array $digestRequest (keys must be nonce, nc, realm, qop) * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, certpassword (optional), verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs) * @access public */ function setCredentials($username, $password, $authtype = 'basic', $digestRequest = array(), $certRequest = array()) { $this->debug("setCredentials username=$username authtype=$authtype digestRequest="); $this->appendDebug($this->varDump($digestRequest)); $this->debug("certRequest="); $this->appendDebug($this->varDump($certRequest)); // cf. RFC 2617 if ($authtype == 'basic') { $this->setHeader('Authorization', 'Basic '.base64_encode(str_replace(':','',$username).':'.$password)); } elseif ($authtype == 'digest') { if (isset($digestRequest['nonce'])) { $digestRequest['nc'] = isset($digestRequest['nc']) ? $digestRequest['nc']++ : 1; // calculate the Digest hashes (calculate code based on digest implementation found at: http://www.rassoc.com/gregr/weblog/stories/2002/07/09/webServicesSecurityHttpDigestAuthenticationWithoutActiveDirectory.html) // A1 = unq(username-value) ":" unq(realm-value) ":" passwd $A1 = $username. ':' . (isset($digestRequest['realm']) ? $digestRequest['realm'] : '') . ':' . $password; // H(A1) = MD5(A1) $HA1 = md5($A1); // A2 = Method ":" digest-uri-value $A2 = $this->request_method . ':' . $this->digest_uri; // H(A2) $HA2 = md5($A2); // KD(secret, data) = H(concat(secret, ":", data)) // if qop == auth: // request-digest = <"> < KD ( H(A1), unq(nonce-value) // ":" nc-value // ":" unq(cnonce-value) // ":" unq(qop-value) // ":" H(A2) // ) <"> // if qop is missing, // request-digest = <"> < KD ( H(A1), unq(nonce-value) ":" H(A2) ) > <"> $unhashedDigest = ''; $nonce = isset($digestRequest['nonce']) ? $digestRequest['nonce'] : ''; $cnonce = $nonce; if ($digestRequest['qop'] != '') { $unhashedDigest = $HA1 . ':' . $nonce . ':' . sprintf("%08d", $digestRequest['nc']) . ':' . $cnonce . ':' . $digestRequest['qop'] . ':' . $HA2; } else { $unhashedDigest = $HA1 . ':' . $nonce . ':' . $HA2; } $hashedDigest = md5($unhashedDigest); $opaque = ''; if (isset($digestRequest['opaque'])) { $opaque = ', opaque="' . $digestRequest['opaque'] . '"'; } $this->setHeader('Authorization', 'Digest username="' . $username . '", realm="' . $digestRequest['realm'] . '", nonce="' . $nonce . '", uri="' . $this->digest_uri . $opaque . '", cnonce="' . $cnonce . '", nc=' . sprintf("%08x", $digestRequest['nc']) . ', qop="' . $digestRequest['qop'] . '", response="' . $hashedDigest . '"'); } } elseif ($authtype == 'certificate') { $this->certRequest = $certRequest; $this->debug('Authorization header not set for certificate'); } elseif ($authtype == 'ntlm') { // do nothing $this->debug('Authorization header not set for ntlm'); } $this->username = $username; $this->password = $password; $this->authtype = $authtype; $this->digestRequest = $digestRequest; } /** * set the soapaction value * * @param string $soapaction * @access public */ function setSOAPAction($soapaction) { $this->setHeader('SOAPAction', '"' . $soapaction . '"'); } /** * use http encoding * * @param string $enc encoding style. supported values: gzip, deflate, or both * @access public */ function setEncoding($enc='gzip, deflate') { if (function_exists('gzdeflate')) { $this->protocol_version = '1.1'; $this->setHeader('Accept-Encoding', $enc); if (!isset($this->outgoing_headers['Connection'])) { $this->setHeader('Connection', 'close'); $this->persistentConnection = false; } set_magic_quotes_runtime(0); // deprecated $this->encoding = $enc; } } /** * set proxy info here * * @param string $proxyhost use an empty string to remove proxy * @param string $proxyport * @param string $proxyusername * @param string $proxypassword * @param string $proxyauthtype (basic|ntlm) * @access public */ function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '', $proxyauthtype = 'basic') { if ($proxyhost) { $this->proxy = array( 'host' => $proxyhost, 'port' => $proxyport, 'username' => $proxyusername, 'password' => $proxypassword, 'authtype' => $proxyauthtype ); if ($proxyusername != '' && $proxypassword != '' && $proxyauthtype = 'basic') { $this->setHeader('Proxy-Authorization', ' Basic '.base64_encode($proxyusername.':'.$proxypassword)); } } else { $this->debug('remove proxy'); $proxy = null; unsetHeader('Proxy-Authorization'); } } /** * Test if the given string starts with a header that is to be skipped. * Skippable headers result from chunked transfer and proxy requests. * * @param string $data The string to check. * @returns boolean Whether a skippable header was found. * @access private */ function isSkippableCurlHeader(&$data) { $skipHeaders = array( 'HTTP/1.1 100', 'HTTP/1.0 301', 'HTTP/1.1 301', 'HTTP/1.0 302', 'HTTP/1.1 302', 'HTTP/1.0 401', 'HTTP/1.1 401', 'HTTP/1.0 200 Connection established'); foreach ($skipHeaders as $hd) { $prefix = substr($data, 0, strlen($hd)); if ($prefix == $hd) return true; } return false; } /** * decode a string that is encoded w/ "chunked' transfer encoding * as defined in RFC2068 19.4.6 * * @param string $buffer * @param string $lb * @returns string * @access public * @deprecated */ function decodeChunked($buffer, $lb){ // length := 0 $length = 0; $new = ''; // read chunk-size, chunk-extension (if any) and CRLF // get the position of the linebreak $chunkend = strpos($buffer, $lb); if ($chunkend == FALSE) { $this->debug('no linebreak found in decodeChunked'); return $new; } $temp = substr($buffer,0,$chunkend); $chunk_size = hexdec( trim($temp) ); $chunkstart = $chunkend + strlen($lb); // while (chunk-size > 0) { while ($chunk_size > 0) { $this->debug("chunkstart: $chunkstart chunk_size: $chunk_size"); $chunkend = strpos( $buffer, $lb, $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 + strlen($lb); $chunkend = strpos($buffer, $lb, $chunkstart) + strlen($lb); 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; } return $new; } /** * Writes the payload, including HTTP headers, to $this->outgoing_payload. * * @param string $data HTTP body * @param string $cookie_str data for HTTP Cookie header * @return void * @access private */ function buildPayload($data, $cookie_str = '') { // Note: for cURL connections, $this->outgoing_payload is ignored, // as is the Content-Length header, but these are still created as // debugging guides. // add content-length header $this->setHeader('Content-Length', strlen($data)); // start building outgoing payload: if ($this->proxy) { $uri = $this->url; } else { $uri = $this->uri; } $req = "$this->request_method $uri HTTP/$this->protocol_version"; $this->debug("HTTP request: $req"); $this->outgoing_payload = "$req\r\n"; // loop thru headers, serializing foreach($this->outgoing_headers as $k => $v){ $hdr = $k.': '.$v; $this->debug("HTTP header: $hdr"); $this->outgoing_payload .= "$hdr\r\n"; } // add any cookies if ($cookie_str != '') { $hdr = 'Cookie: '.$cookie_str; $this->debug("HTTP header: $hdr"); $this->outgoing_payload .= "$hdr\r\n"; } // header/body separator $this->outgoing_payload .= "\r\n"; // add data $this->outgoing_payload .= $data; } /** * sends the SOAP request via HTTP[S] * * @param string $data message data * @param array $cookies cookies to send * @return boolean true if OK, false if problem * @access private */ function sendRequest($data, $cookies = NULL) { // build cookie string $cookie_str = $this->getCookiesForRequest($cookies, (($this->scheme == 'ssl') || ($this->scheme == 'https'))); // build payload $this->buildPayload($data, $cookie_str); if ($this->io_method() == 'socket') { // send payload if(!fputs($this->fp, $this->outgoing_payload, strlen($this->outgoing_payload))) { $this->setError('couldn\'t write message data to socket'); $this->debug('couldn\'t write message data to socket'); return false; } $this->debug('wrote data to socket, length = ' . strlen($this->outgoing_payload)); return true; } else if ($this->io_method() == 'curl') { // set payload // cURL does say this should only be the verb, and in fact it // turns out that the URI and HTTP version are appended to this, which // some servers refuse to work with (so we no longer use this method!) //$this->setCurlOption(CURLOPT_CUSTOMREQUEST, $this->outgoing_payload); $curl_headers = array(); foreach($this->outgoing_headers as $k => $v){ if ($k == 'Connection' || $k == 'Content-Length' || $k == 'Host' || $k == 'Authorization' || $k == 'Proxy-Authorization') { $this->debug("Skip cURL header $k: $v"); } else { $curl_headers[] = "$k: $v"; } } if ($cookie_str != '') { $curl_headers[] = 'Cookie: ' . $cookie_str; } $this->setCurlOption(CURLOPT_HTTPHEADER, $curl_headers); $this->debug('set cURL HTTP headers'); if ($this->request_method == "POST") { $this->setCurlOption(CURLOPT_POST, 1); $this->setCurlOption(CURLOPT_POSTFIELDS, $data); $this->debug('set cURL POST data'); } else { } // insert custom user-set cURL options foreach ($this->ch_options as $key => $val) { $this->setCurlOption($key, $val); } $this->debug('set cURL payload'); return true; } } /** * gets the SOAP response via HTTP[S] * * @return string the response (also sets member variables like incoming_payload) * @access private */ function getResponse(){ $this->incoming_payload = ''; if ($this->io_method() == 'socket') { // loop until headers have been retrieved $data = ''; while (!isset($lb)){ // We might EOF during header read. if(feof($this->fp)) { $this->incoming_payload = $data; $this->debug('found no headers before EOF after length ' . strlen($data)); $this->debug("received before EOF:\n" . $data); $this->setError('server failed to send headers'); return false; } $tmp = fgets($this->fp, 256); $tmplen = strlen($tmp); $this->debug("read line of $tmplen bytes: " . trim($tmp)); if ($tmplen == 0) { $this->incoming_payload = $data; $this->debug('socket read of headers timed out after length ' . strlen($data)); $this->debug("read before timeout: " . $data); $this->setError('socket read of headers timed out'); return false; } $data .= $tmp; $pos = strpos($data,"\r\n\r\n"); if($pos > 1){ $lb = "\r\n"; } else { $pos = strpos($data,"\n\n"); if($pos > 1){ $lb = "\n"; } } // remove 100 headers if (isset($lb) && ereg('^HTTP/1.1 100',$data)) { unset($lb); $data = ''; }// } // store header data $this->incoming_payload .= $data; $this->debug('found end of headers after length ' . strlen($data)); // process headers $header_data = trim(substr($data,0,$pos)); $header_array = explode($lb,$header_data); $this->incoming_headers = array(); $this->incoming_cookies = array(); foreach($header_array as $header_line){ $arr = explode(':',$header_line, 2); if(count($arr) > 1){ $header_name = strtolower(trim($arr[0])); $this->incoming_headers[$header_name] = trim($arr[1]); if ($header_name == 'set-cookie') { // TODO: allow multiple cookies from parseCookie $cookie = $this->parseCookie(trim($arr[1])); if ($cookie) { $this->incoming_cookies[] = $cookie; $this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']); } else { $this->debug('did not find cookie in ' . trim($arr[1])); } } } else if (isset($header_name)) { // append continuation line to previous header $this->incoming_headers[$header_name] .= $lb . ' ' . $header_line; } } // loop until msg has been received if (isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked') { $content_length = 2147483647; // ignore any content-length header $chunked = true; $this->debug("want to read chunked content"); } elseif (isset($this->incoming_headers['content-length'])) { $content_length = $this->incoming_headers['content-length']; $chunked = false; $this->debug("want to read content of length $content_length"); } else { $content_length = 2147483647; $chunked = false; $this->debug("want to read content to EOF"); } $data = ''; do { if ($chunked) { $tmp = fgets($this->fp, 256); $tmplen = strlen($tmp); $this->debug("read chunk line of $tmplen bytes"); if ($tmplen == 0) { $this->incoming_payload = $data; $this->debug('socket read of chunk length timed out after length ' . strlen($data)); $this->debug("read before timeout:\n" . $data); $this->setError('socket read of chunk length timed out'); return false; } $content_length = hexdec(trim($tmp)); $this->debug("chunk length $content_length"); } $strlen = 0; while (($strlen < $content_length) && (!feof($this->fp))) { $readlen = min(8192, $content_length - $strlen); $tmp = fread($this->fp, $readlen); $tmplen = strlen($tmp); $this->debug("read buffer of $tmplen bytes"); if (($tmplen == 0) && (!feof($this->fp))) { $this->incoming_payload = $data; $this->debug('socket read of body timed out after length ' . strlen($data)); $this->debug("read before timeout:\n" . $data); $this->setError('socket read of body timed out'); return false; } $strlen += $tmplen; $data .= $tmp; } if ($chunked && ($content_length > 0)) { $tmp = fgets($this->fp, 256); $tmplen = strlen($tmp); $this->debug("read chunk terminator of $tmplen bytes"); if ($tmplen == 0) { $this->incoming_payload = $data; $this->debug('socket read of chunk terminator timed out after length ' . strlen($data)); $this->debug("read before timeout:\n" . $data); $this->setError('socket read of chunk terminator timed out'); return false; } } } while ($chunked && ($content_length > 0) && (!feof($this->fp))); if (feof($this->fp)) { $this->debug('read to EOF'); } $this->debug('read body of length ' . strlen($data)); $this->incoming_payload .= $data; $this->debug('received a total of '.strlen($this->incoming_payload).' bytes of data from server'); // close filepointer if( (isset($this->incoming_headers['connection']) && strtolower($this->incoming_headers['connection']) == 'close') || (! $this->persistentConnection) || feof($this->fp)){ fclose($this->fp); $this->fp = false; $this->debug('closed socket'); } // connection was closed unexpectedly if($this->incoming_payload == ''){ $this->setError('no response from server'); return false; } // decode transfer-encoding // if(isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked'){ // if(!$data = $this->decodeChunked($data, $lb)){ // $this->setError('Decoding of chunked data failed'); // return false; // } //print "
    \nde-chunked:\n---------------\n$data\n\n---------------\n
    "; // set decoded payload // $this->incoming_payload = $header_data.$lb.$lb.$data; // } } else if ($this->io_method() == 'curl') { // send and receive $this->debug('send and receive with cURL'); $this->incoming_payload = curl_exec($this->ch); $data = $this->incoming_payload; $cErr = curl_error($this->ch); if ($cErr != '') { $err = 'cURL ERROR: '.curl_errno($this->ch).': '.$cErr.'
    '; // TODO: there is a PHP bug that can cause this to SEGV for CURLINFO_CONTENT_TYPE foreach(curl_getinfo($this->ch) as $k => $v){ $err .= "$k: $v
    "; } $this->debug($err); $this->setError($err); curl_close($this->ch); return false; } else { //echo '
    ';
    			//var_dump(curl_getinfo($this->ch));
    			//echo '
    '; } // close curl $this->debug('No cURL error, closing cURL'); curl_close($this->ch); // try removing skippable headers $savedata = $data; while ($this->isSkippableCurlHeader($data)) { $this->debug("Found HTTP header to skip"); if ($pos = strpos($data,"\r\n\r\n")) { $data = ltrim(substr($data,$pos)); } elseif($pos = strpos($data,"\n\n") ) { $data = ltrim(substr($data,$pos)); } } if ($data == '') { // have nothing left; just remove 100 header(s) $data = $savedata; while (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 headers if ($pos = strpos($data,"\r\n\r\n")) { $lb = "\r\n"; } elseif( $pos = strpos($data,"\n\n")) { $lb = "\n"; } else { $this->debug('no proper separation of headers and document'); $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 headers foreach ($header_array as $header_line) { $arr = explode(':',$header_line,2); if(count($arr) > 1){ $header_name = strtolower(trim($arr[0])); $this->incoming_headers[$header_name] = trim($arr[1]); if ($header_name == 'set-cookie') { // TODO: allow multiple cookies from parseCookie $cookie = $this->parseCookie(trim($arr[1])); if ($cookie) { $this->incoming_cookies[] = $cookie; $this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']); } else { $this->debug('did not find cookie in ' . trim($arr[1])); } } } else if (isset($header_name)) { // append continuation line to previous header $this->incoming_headers[$header_name] .= $lb . ' ' . $header_line; } } } $this->response_status_line = $header_array[0]; $arr = explode(' ', $this->response_status_line, 3); $http_version = $arr[0]; $http_status = intval($arr[1]); $http_reason = count($arr) > 2 ? $arr[2] : ''; // see if we need to resend the request with http digest authentication if (isset($this->incoming_headers['location']) && ($http_status == 301 || $http_status == 302)) { $this->debug("Got $http_status $http_reason with Location: " . $this->incoming_headers['location']); $this->setURL($this->incoming_headers['location']); $this->tryagain = true; return false; } // see if we need to resend the request with http digest authentication if (isset($this->incoming_headers['www-authenticate']) && $http_status == 401) { $this->debug("Got 401 $http_reason with WWW-Authenticate: " . $this->incoming_headers['www-authenticate']); if (strstr($this->incoming_headers['www-authenticate'], "Digest ")) { $this->debug('Server wants digest authentication'); // remove "Digest " from our elements $digestString = str_replace('Digest ', '', $this->incoming_headers['www-authenticate']); // parse elements into array $digestElements = explode(',', $digestString); foreach ($digestElements as $val) { $tempElement = explode('=', trim($val), 2); $digestRequest[$tempElement[0]] = str_replace("\"", '', $tempElement[1]); } // should have (at least) qop, realm, nonce if (isset($digestRequest['nonce'])) { $this->setCredentials($this->username, $this->password, 'digest', $digestRequest); $this->tryagain = true; return false; } } $this->debug('HTTP authentication failed'); $this->setError('HTTP authentication failed'); return false; } if ( ($http_status >= 300 && $http_status <= 307) || ($http_status >= 400 && $http_status <= 417) || ($http_status >= 501 && $http_status <= 505) ) { $this->setError("Unsupported HTTP response status $http_status $http_reason (soapclient->response has contents of the response)"); return false; } // decode content-encoding if(isset($this->incoming_headers['content-encoding']) && $this->incoming_headers['content-encoding'] != ''){ if(strtolower($this->incoming_headers['content-encoding']) == 'deflate' || strtolower($this->incoming_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'); // IIS 5 requires gzinflate instead of gzuncompress (similar to IE 5 and gzdeflate v. gzcompress) // this means there are no Zlib headers, although there should be $this->debug('The gzinflate function exists'); $datalen = strlen($data); if ($this->incoming_headers['content-encoding'] == 'deflate') { if ($degzdata = @gzinflate($data)) { $data = $degzdata; $this->debug('The payload has been inflated to ' . strlen($data) . ' bytes'); if (strlen($data) < $datalen) { // test for the case that the payload has been compressed twice $this->debug('The inflated payload is smaller than the gzipped one; try again'); if ($degzdata = @gzinflate($data)) { $data = $degzdata; $this->debug('The payload has been inflated again to ' . strlen($data) . ' bytes'); } } } else { $this->debug('Error using gzinflate to inflate the payload'); $this->setError('Error using gzinflate to inflate the payload'); } } elseif ($this->incoming_headers['content-encoding'] == 'gzip') { if ($degzdata = @gzinflate(substr($data, 10))) { // do our best $data = $degzdata; $this->debug('The payload has been un-gzipped to ' . strlen($data) . ' bytes'); if (strlen($data) < $datalen) { // test for the case that the payload has been compressed twice $this->debug('The un-gzipped payload is smaller than the gzipped one; try again'); if ($degzdata = @gzinflate(substr($data, 10))) { $data = $degzdata; $this->debug('The payload has been un-gzipped again to ' . strlen($data) . ' bytes'); } } } else { $this->debug('Error using gzinflate to un-gzip the payload'); $this->setError('Error using gzinflate to un-gzip the payload'); } } //$timer->setMarker('finished decoding of gzip/deflated content'); //print "\nde-inflated:\n---------------\n$data\n-------------\n"; // set decoded payload $this->incoming_payload = $header_data.$lb.$lb.$data; } else { $this->debug('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.'); $this->setError('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.'); } } else { $this->debug('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']); $this->setError('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']); } } else { $this->debug('No Content-Encoding header'); } if(strlen($data) == 0){ $this->debug('no data after headers!'); $this->setError('no data present after HTTP headers'); return false; } return $data; } /** * sets the content-type for the SOAP message to be sent * * @param string $type the content type, MIME style * @param mixed $charset character set used for encoding (or false) * @access public */ function setContentType($type, $charset = false) { $this->setHeader('Content-Type', $type . ($charset ? '; charset=' . $charset : '')); } /** * specifies that an HTTP persistent connection should be used * * @return boolean whether the request was honored by this method. * @access public */ function usePersistentConnection(){ if (isset($this->outgoing_headers['Accept-Encoding'])) { return false; } $this->protocol_version = '1.1'; $this->persistentConnection = true; $this->setHeader('Connection', 'Keep-Alive'); return true; } /** * parse an incoming Cookie into it's parts * * @param string $cookie_str content of cookie * @return array with data of that cookie * @access private */ /* * TODO: allow a Set-Cookie string to be parsed into multiple cookies */ function parseCookie($cookie_str) { $cookie_str = str_replace('; ', ';', $cookie_str) . ';'; $data = split(';', $cookie_str); $value_str = $data[0]; $cookie_param = 'domain='; $start = strpos($cookie_str, $cookie_param); if ($start > 0) { $domain = substr($cookie_str, $start + strlen($cookie_param)); $domain = substr($domain, 0, strpos($domain, ';')); } else { $domain = ''; } $cookie_param = 'expires='; $start = strpos($cookie_str, $cookie_param); if ($start > 0) { $expires = substr($cookie_str, $start + strlen($cookie_param)); $expires = substr($expires, 0, strpos($expires, ';')); } else { $expires = ''; } $cookie_param = 'path='; $start = strpos($cookie_str, $cookie_param); if ( $start > 0 ) { $path = substr($cookie_str, $start + strlen($cookie_param)); $path = substr($path, 0, strpos($path, ';')); } else { $path = '/'; } $cookie_param = ';secure;'; if (strpos($cookie_str, $cookie_param) !== FALSE) { $secure = true; } else { $secure = false; } $sep_pos = strpos($value_str, '='); if ($sep_pos) { $name = substr($value_str, 0, $sep_pos); $value = substr($value_str, $sep_pos + 1); $cookie= array( 'name' => $name, 'value' => $value, 'domain' => $domain, 'path' => $path, 'expires' => $expires, 'secure' => $secure ); return $cookie; } return false; } /** * sort out cookies for the current request * * @param array $cookies array with all cookies * @param boolean $secure is the send-content secure or not? * @return string for Cookie-HTTP-Header * @access private */ function getCookiesForRequest($cookies, $secure=false) { $cookie_str = ''; if ((! is_null($cookies)) && (is_array($cookies))) { foreach ($cookies as $cookie) { if (! is_array($cookie)) { continue; } $this->debug("check cookie for validity: ".$cookie['name'].'='.$cookie['value']); if ((isset($cookie['expires'])) && (! empty($cookie['expires']))) { if (strtotime($cookie['expires']) <= time()) { $this->debug('cookie has expired'); continue; } } if ((isset($cookie['domain'])) && (! empty($cookie['domain']))) { $domain = preg_quote($cookie['domain']); if (! preg_match("'.*$domain$'i", $this->host)) { $this->debug('cookie has different domain'); continue; } } if ((isset($cookie['path'])) && (! empty($cookie['path']))) { $path = preg_quote($cookie['path']); if (! preg_match("'^$path.*'i", $this->path)) { $this->debug('cookie is for a different path'); continue; } } if ((! $secure) && (isset($cookie['secure'])) && ($cookie['secure'])) { $this->debug('cookie is secure, transport is not'); continue; } $cookie_str .= $cookie['name'] . '=' . $cookie['value'] . '; '; $this->debug('add cookie to Cookie-String: ' . $cookie['name'] . '=' . $cookie['value']); } } return $cookie_str; } } ?> * @author Scott Nichol * @version $Id: nusoap.php,v 1.114 2007/11/06 15:17:46 snichol Exp $ * @access public */ class nusoap_server extends nusoap_base { /** * HTTP headers of request * @var array * @access private */ var $headers = array(); /** * HTTP request * @var string * @access private */ var $request = ''; /** * SOAP headers from request (incomplete namespace resolution; special characters not escaped) (text) * @var string * @access public */ var $requestHeaders = ''; /** * SOAP Headers from request (parsed) * @var mixed * @access public */ var $requestHeader = NULL; /** * SOAP body request portion (incomplete namespace resolution; special characters not escaped) (text) * @var string * @access public */ var $document = ''; /** * SOAP payload for request (text) * @var string * @access public */ var $requestSOAP = ''; /** * requested method namespace URI * @var string * @access private */ var $methodURI = ''; /** * name of method requested * @var string * @access private */ var $methodname = ''; /** * method parameters from request * @var array * @access private */ var $methodparams = array(); /** * SOAP Action from request * @var string * @access private */ var $SOAPAction = ''; /** * character set encoding of incoming (request) messages * @var string * @access public */ var $xml_encoding = ''; /** * toggles whether the parser decodes element content w/ utf8_decode() * @var boolean * @access public */ var $decode_utf8 = true; /** * HTTP headers of response * @var array * @access public */ var $outgoing_headers = array(); /** * HTTP response * @var string * @access private */ var $response = ''; /** * SOAP headers for response (text or array of soapval or associative array) * @var mixed * @access public */ var $responseHeaders = ''; /** * SOAP payload for response (text) * @var string * @access private */ var $responseSOAP = ''; /** * method return value to place in response * @var mixed * @access private */ var $methodreturn = false; /** * whether $methodreturn is a string of literal XML * @var boolean * @access public */ var $methodreturnisliteralxml = false; /** * SOAP fault for response (or false) * @var mixed * @access private */ var $fault = false; /** * text indication of result (for debugging) * @var string * @access private */ var $result = 'successful'; /** * assoc array of operations => opData; operations are added by the register() * method or by parsing an external WSDL definition * @var array * @access private */ var $operations = array(); /** * wsdl instance (if one) * @var mixed * @access private */ var $wsdl = false; /** * URL for WSDL (if one) * @var mixed * @access private */ var $externalWSDLURL = false; /** * whether to append debug to response as XML comment * @var boolean * @access public */ var $debug_flag = false; /** * constructor * the optional parameter is a path to a WSDL file that you'd like to bind the server instance to. * * @param mixed $wsdl file path or URL (string), or wsdl instance (object) * @access public */ function nusoap_server($wsdl=false){ parent::nusoap_base(); // turn on debugging? global $debug; global $HTTP_SERVER_VARS; if (isset($_SERVER)) { $this->debug("_SERVER is defined:"); $this->appendDebug($this->varDump($_SERVER)); } elseif (isset($HTTP_SERVER_VARS)) { $this->debug("HTTP_SERVER_VARS is defined:"); $this->appendDebug($this->varDump($HTTP_SERVER_VARS)); } else { $this->debug("Neither _SERVER nor HTTP_SERVER_VARS is defined."); } if (isset($debug)) { $this->debug("In nusoap_server, set debug_flag=$debug based on global flag"); $this->debug_flag = $debug; } elseif (isset($_SERVER['QUERY_STRING'])) { $qs = explode('&', $_SERVER['QUERY_STRING']); foreach ($qs as $v) { if (substr($v, 0, 6) == 'debug=') { $this->debug("In nusoap_server, set debug_flag=" . substr($v, 6) . " based on query string #1"); $this->debug_flag = substr($v, 6); } } } elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) { $qs = explode('&', $HTTP_SERVER_VARS['QUERY_STRING']); foreach ($qs as $v) { if (substr($v, 0, 6) == 'debug=') { $this->debug("In nusoap_server, set debug_flag=" . substr($v, 6) . " based on query string #2"); $this->debug_flag = substr($v, 6); } } } // wsdl if($wsdl){ $this->debug("In nusoap_server, WSDL is specified"); if (is_object($wsdl) && (get_class($wsdl) == 'wsdl')) { $this->wsdl = $wsdl; $this->externalWSDLURL = $this->wsdl->wsdl; $this->debug('Use existing wsdl instance from ' . $this->externalWSDLURL); } else { $this->debug('Create wsdl from ' . $wsdl); $this->wsdl = new wsdl($wsdl); $this->externalWSDLURL = $wsdl; } $this->appendDebug($this->wsdl->getDebug()); $this->wsdl->clearDebug(); if($err = $this->wsdl->getError()){ die('WSDL ERROR: '.$err); } } } /** * processes request and returns response * * @param string $data usually is the value of $HTTP_RAW_POST_DATA * @access public */ function service($data){ global $HTTP_SERVER_VARS; if (isset($_SERVER['QUERY_STRING'])) { $qs = $_SERVER['QUERY_STRING']; } elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) { $qs = $HTTP_SERVER_VARS['QUERY_STRING']; } else { $qs = ''; } $this->debug("In service, query string=$qs"); if (ereg('wsdl', $qs) ){ $this->debug("In service, this is a request for WSDL"); if($this->externalWSDLURL){ if (strpos($this->externalWSDLURL,"://")!==false) { // assume URL header('Location: '.$this->externalWSDLURL); } else { // assume file header("Content-Type: text/xml\r\n"); $fp = fopen($this->externalWSDLURL, 'r'); fpassthru($fp); } } elseif ($this->wsdl) { header("Content-Type: text/xml; charset=ISO-8859-1\r\n"); print $this->wsdl->serialize($this->debug_flag); if ($this->debug_flag) { $this->debug('wsdl:'); $this->appendDebug($this->varDump($this->wsdl)); print $this->getDebugAsXMLComment(); } } else { header("Content-Type: text/html; charset=ISO-8859-1\r\n"); print "This service does not provide WSDL"; } } elseif ($data == '' && $this->wsdl) { $this->debug("In service, there is no data, so return Web description"); print $this->wsdl->webDescription(); } else { $this->debug("In service, invoke the request"); $this->parse_request($data); if (! $this->fault) { $this->invoke_method(); } if (! $this->fault) { $this->serialize_return(); } $this->send_response(); } } /** * parses HTTP request headers. * * The following fields are set by this function (when successful) * * headers * request * xml_encoding * SOAPAction * * @access private */ function parse_http_headers() { global $HTTP_SERVER_VARS; $this->request = ''; $this->SOAPAction = ''; if(function_exists('getallheaders')){ $this->debug("In parse_http_headers, use getallheaders"); $headers = getallheaders(); foreach($headers as $k=>$v){ $k = strtolower($k); $this->headers[$k] = $v; $this->request .= "$k: $v\r\n"; $this->debug("$k: $v"); } // get SOAPAction header if(isset($this->headers['soapaction'])){ $this->SOAPAction = str_replace('"','',$this->headers['soapaction']); } // get the character encoding of the incoming request if(isset($this->headers['content-type']) && strpos($this->headers['content-type'],'=')){ $enc = str_replace('"','',substr(strstr($this->headers["content-type"],'='),1)); if(eregi('^(ISO-8859-1|US-ASCII|UTF-8)$',$enc)){ $this->xml_encoding = strtoupper($enc); } else { $this->xml_encoding = 'US-ASCII'; } } else { // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 $this->xml_encoding = 'ISO-8859-1'; } } elseif(isset($_SERVER) && is_array($_SERVER)){ $this->debug("In parse_http_headers, use _SERVER"); foreach ($_SERVER as $k => $v) { if (substr($k, 0, 5) == 'HTTP_') { $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5)))); } else { $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k))); } if ($k == 'soapaction') { // get SOAPAction header $k = 'SOAPAction'; $v = str_replace('"', '', $v); $v = str_replace('\\', '', $v); $this->SOAPAction = $v; } else if ($k == 'content-type') { // get the character encoding of the incoming request if (strpos($v, '=')) { $enc = substr(strstr($v, '='), 1); $enc = str_replace('"', '', $enc); $enc = str_replace('\\', '', $enc); if (eregi('^(ISO-8859-1|US-ASCII|UTF-8)$', $enc)) { $this->xml_encoding = strtoupper($enc); } else { $this->xml_encoding = 'US-ASCII'; } } else { // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 $this->xml_encoding = 'ISO-8859-1'; } } $this->headers[$k] = $v; $this->request .= "$k: $v\r\n"; $this->debug("$k: $v"); } } elseif (is_array($HTTP_SERVER_VARS)) { $this->debug("In parse_http_headers, use HTTP_SERVER_VARS"); foreach ($HTTP_SERVER_VARS as $k => $v) { if (substr($k, 0, 5) == 'HTTP_') { $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5)))); $k = strtolower(substr($k, 5)); } else { $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k))); $k = strtolower($k); } if ($k == 'soapaction') { // get SOAPAction header $k = 'SOAPAction'; $v = str_replace('"', '', $v); $v = str_replace('\\', '', $v); $this->SOAPAction = $v; } else if ($k == 'content-type') { // get the character encoding of the incoming request if (strpos($v, '=')) { $enc = substr(strstr($v, '='), 1); $enc = str_replace('"', '', $enc); $enc = str_replace('\\', '', $enc); if (eregi('^(ISO-8859-1|US-ASCII|UTF-8)$', $enc)) { $this->xml_encoding = strtoupper($enc); } else { $this->xml_encoding = 'US-ASCII'; } } else { // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 $this->xml_encoding = 'ISO-8859-1'; } } $this->headers[$k] = $v; $this->request .= "$k: $v\r\n"; $this->debug("$k: $v"); } } else { $this->debug("In parse_http_headers, HTTP headers not accessible"); $this->setError("HTTP headers not accessible"); } } /** * parses a request * * The following fields are set by this function (when successful) * * headers * request * xml_encoding * SOAPAction * request * requestSOAP * methodURI * methodname * methodparams * requestHeaders * document * * This sets the fault field on error * * @param string $data XML string * @access private */ function parse_request($data='') { $this->debug('entering parse_request()'); $this->parse_http_headers(); $this->debug('got character encoding: '.$this->xml_encoding); // uncompress if necessary if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] != '') { $this->debug('got content encoding: ' . $this->headers['content-encoding']); if ($this->headers['content-encoding'] == 'deflate' || $this->headers['content-encoding'] == 'gzip') { // if decoding works, use it. else assume data wasn't gzencoded if (function_exists('gzuncompress')) { if ($this->headers['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) { $data = $degzdata; } elseif ($this->headers['content-encoding'] == 'gzip' && $degzdata = gzinflate(substr($data, 10))) { $data = $degzdata; } else { $this->fault('SOAP-ENV:Client', 'Errors occurred when trying to decode the data'); return; } } else { $this->fault('SOAP-ENV:Client', 'This Server does not support compressed data'); return; } } } $this->request .= "\r\n".$data; $data = $this->parseRequest($this->headers, $data); $this->requestSOAP = $data; $this->debug('leaving parse_request'); } /** * invokes a PHP function for the requested SOAP method * * The following fields are set by this function (when successful) * * methodreturn * * Note that the PHP function that is called may also set the following * fields to affect the response sent to the client * * responseHeaders * outgoing_headers * * This sets the fault field on error * * @access private */ function invoke_method() { $this->debug('in invoke_method, methodname=' . $this->methodname . ' methodURI=' . $this->methodURI . ' SOAPAction=' . $this->SOAPAction); if ($this->wsdl) { if ($this->opData = $this->wsdl->getOperationData($this->methodname)) { $this->debug('in invoke_method, found WSDL operation=' . $this->methodname); $this->appendDebug('opData=' . $this->varDump($this->opData)); } elseif ($this->opData = $this->wsdl->getOperationDataForSoapAction($this->SOAPAction)) { // Note: hopefully this case will only be used for doc/lit, since rpc services should have wrapper element $this->debug('in invoke_method, found WSDL soapAction=' . $this->SOAPAction . ' for operation=' . $this->opData['name']); $this->appendDebug('opData=' . $this->varDump($this->opData)); $this->methodname = $this->opData['name']; } else { $this->debug('in invoke_method, no WSDL for operation=' . $this->methodname); $this->fault('SOAP-ENV:Client', "Operation '" . $this->methodname . "' is not defined in the WSDL for this service"); return; } } else { $this->debug('in invoke_method, no WSDL to validate method'); } // if a . is present in $this->methodname, we see if there is a class in scope, // which could be referred to. We will also distinguish between two deliminators, // to allow methods to be called a the class or an instance $class = ''; $method = ''; if (strpos($this->methodname, '..') > 0) { $delim = '..'; } else if (strpos($this->methodname, '.') > 0) { $delim = '.'; } else { $delim = ''; } if (strlen($delim) > 0 && substr_count($this->methodname, $delim) == 1 && class_exists(substr($this->methodname, 0, strpos($this->methodname, $delim)))) { // get the class and method name $class = substr($this->methodname, 0, strpos($this->methodname, $delim)); $method = substr($this->methodname, strpos($this->methodname, $delim) + strlen($delim)); $this->debug("in invoke_method, class=$class method=$method delim=$delim"); } // does method exist? if ($class == '') { if (!function_exists($this->methodname)) { $this->debug("in invoke_method, function '$this->methodname' not found!"); $this->result = 'fault: method not found'; $this->fault('SOAP-ENV:Client',"method '$this->methodname' not defined in service"); return; } } else { $method_to_compare = (substr(phpversion(), 0, 2) == '4.') ? strtolower($method) : $method; if (!in_array($method_to_compare, get_class_methods($class))) { $this->debug("in invoke_method, method '$this->methodname' not found in class '$class'!"); $this->result = 'fault: method not found'; $this->fault('SOAP-ENV:Client',"method '$this->methodname' not defined in service"); return; } } // evaluate message, getting back parameters // verify that request parameters match the method's signature if(! $this->verify_method($this->methodname,$this->methodparams)){ // debug $this->debug('ERROR: request not verified against method signature'); $this->result = 'fault: request failed validation against method signature'; // return fault $this->fault('SOAP-ENV:Client',"Operation '$this->methodname' not defined in service."); return; } // if there are parameters to pass $this->debug('in invoke_method, params:'); $this->appendDebug($this->varDump($this->methodparams)); $this->debug("in invoke_method, calling '$this->methodname'"); if (!function_exists('call_user_func_array')) { if ($class == '') { $this->debug('in invoke_method, calling function using eval()'); $funcCall = "\$this->methodreturn = $this->methodname("; } else { if ($delim == '..') { $this->debug('in invoke_method, calling class method using eval()'); $funcCall = "\$this->methodreturn = ".$class."::".$method."("; } else { $this->debug('in invoke_method, calling instance method using eval()'); // generate unique instance name $instname = "\$inst_".time(); $funcCall = $instname." = new ".$class."(); "; $funcCall .= "\$this->methodreturn = ".$instname."->".$method."("; } } if ($this->methodparams) { foreach ($this->methodparams as $param) { if (is_array($param) || is_object($param)) { $this->fault('SOAP-ENV:Client', 'NuSOAP does not handle complexType parameters correctly when using eval; call_user_func_array must be available'); return; } $funcCall .= "\"$param\","; } $funcCall = substr($funcCall, 0, -1); } $funcCall .= ');'; $this->debug('in invoke_method, function call: '.$funcCall); @eval($funcCall); } else { if ($class == '') { $this->debug('in invoke_method, calling function using call_user_func_array()'); $call_arg = "$this->methodname"; // straight assignment changes $this->methodname to lower case after call_user_func_array() } elseif ($delim == '..') { $this->debug('in invoke_method, calling class method using call_user_func_array()'); $call_arg = array ($class, $method); } else { $this->debug('in invoke_method, calling instance method using call_user_func_array()'); $instance = new $class (); $call_arg = array(&$instance, $method); } if (is_array($this->methodparams)) { $this->methodreturn = call_user_func_array($call_arg, array_values($this->methodparams)); } else { $this->methodreturn = call_user_func_array($call_arg, array()); } } $this->debug('in invoke_method, methodreturn:'); $this->appendDebug($this->varDump($this->methodreturn)); $this->debug("in invoke_method, called method $this->methodname, received data of type ".gettype($this->methodreturn)); } /** * serializes the return value from a PHP function into a full SOAP Envelope * * The following fields are set by this function (when successful) * * responseSOAP * * This sets the fault field on error * * @access private */ function serialize_return() { $this->debug('Entering serialize_return methodname: ' . $this->methodname . ' methodURI: ' . $this->methodURI); // if fault if (isset($this->methodreturn) && ((get_class($this->methodreturn) == 'soap_fault') || (get_class($this->methodreturn) == 'nusoap_fault'))) { $this->debug('got a fault object from method'); $this->fault = $this->methodreturn; return; } elseif ($this->methodreturnisliteralxml) { $return_val = $this->methodreturn; // returned value(s) } else { $this->debug('got a(n) '.gettype($this->methodreturn).' from method'); $this->debug('serializing return value'); if($this->wsdl){ if (sizeof($this->opData['output']['parts']) > 1) { $this->debug('more than one output part, so use the method return unchanged'); $opParams = $this->methodreturn; } elseif (sizeof($this->opData['output']['parts']) == 1) { $this->debug('exactly one output part, so wrap the method return in a simple array'); // TODO: verify that it is not already wrapped! //foreach ($this->opData['output']['parts'] as $name => $type) { // $this->debug('wrap in element named ' . $name); //} $opParams = array($this->methodreturn); } $return_val = $this->wsdl->serializeRPCParameters($this->methodname,'output',$opParams); $this->appendDebug($this->wsdl->getDebug()); $this->wsdl->clearDebug(); if($errstr = $this->wsdl->getError()){ $this->debug('got wsdl error: '.$errstr); $this->fault('SOAP-ENV:Server', 'unable to serialize result'); return; } } else { if (isset($this->methodreturn)) { $return_val = $this->serialize_val($this->methodreturn, 'return'); } else { $return_val = ''; $this->debug('in absence of WSDL, assume void return for backward compatibility'); } } } $this->debug('return value:'); $this->appendDebug($this->varDump($return_val)); $this->debug('serializing response'); if ($this->wsdl) { $this->debug('have WSDL for serialization: style is ' . $this->opData['style']); if ($this->opData['style'] == 'rpc') { $this->debug('style is rpc for serialization: use is ' . $this->opData['output']['use']); if ($this->opData['output']['use'] == 'literal') { // http://www.ws-i.org/Profiles/BasicProfile-1.1-2004-08-24.html R2735 says rpc/literal accessor elements should not be in a namespace $payload = 'methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'methodname."Response>"; } else { $payload = 'methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'methodname."Response>"; } } else { $this->debug('style is not rpc for serialization: assume document'); $payload = $return_val; } } else { $this->debug('do not have WSDL for serialization: assume rpc/encoded'); $payload = 'methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'methodname."Response>"; } $this->result = 'successful'; if($this->wsdl){ //if($this->debug_flag){ $this->appendDebug($this->wsdl->getDebug()); // } if (isset($opData['output']['encodingStyle'])) { $encodingStyle = $opData['output']['encodingStyle']; } else { $encodingStyle = ''; } // Added: In case we use a WSDL, return a serialized env. WITH the usedNamespaces. $this->responseSOAP = $this->serializeEnvelope($payload,$this->responseHeaders,$this->wsdl->usedNamespaces,$this->opData['style'],$this->opData['output']['use'],$encodingStyle); } else { $this->responseSOAP = $this->serializeEnvelope($payload,$this->responseHeaders); } $this->debug("Leaving serialize_return"); } /** * sends an HTTP response * * The following fields are set by this function (when successful) * * outgoing_headers * response * * @access private */ function send_response() { $this->debug('Enter send_response'); if ($this->fault) { $payload = $this->fault->serialize(); $this->outgoing_headers[] = "HTTP/1.0 500 Internal Server Error"; $this->outgoing_headers[] = "Status: 500 Internal Server Error"; } else { $payload = $this->responseSOAP; // Some combinations of PHP+Web server allow the Status // to come through as a header. Since OK is the default // just do nothing. // $this->outgoing_headers[] = "HTTP/1.0 200 OK"; // $this->outgoing_headers[] = "Status: 200 OK"; } // add debug data if in debug mode if(isset($this->debug_flag) && $this->debug_flag){ $payload .= $this->getDebugAsXMLComment(); } $this->outgoing_headers[] = "Server: $this->title Server v$this->version"; ereg('\$Revisio' . 'n: ([^ ]+)', $this->revision, $rev); $this->outgoing_headers[] = "X-SOAP-Server: $this->title/$this->version (".$rev[1].")"; // Let the Web server decide about this //$this->outgoing_headers[] = "Connection: Close\r\n"; $payload = $this->getHTTPBody($payload); $type = $this->getHTTPContentType(); $charset = $this->getHTTPContentTypeCharset(); $this->outgoing_headers[] = "Content-Type: $type" . ($charset ? '; charset=' . $charset : ''); //begin code to compress payload - by John // NOTE: there is no way to know whether the Web server will also compress // this data. if (strlen($payload) > 1024 && isset($this->headers) && isset($this->headers['accept-encoding'])) { if (strstr($this->headers['accept-encoding'], 'gzip')) { if (function_exists('gzencode')) { if (isset($this->debug_flag) && $this->debug_flag) { $payload .= ""; } $this->outgoing_headers[] = "Content-Encoding: gzip"; $payload = gzencode($payload); } else { if (isset($this->debug_flag) && $this->debug_flag) { $payload .= ""; } } } elseif (strstr($this->headers['accept-encoding'], 'deflate')) { // Note: MSIE requires gzdeflate output (no Zlib header and checksum), // instead of gzcompress output, // which conflicts with HTTP 1.1 spec (http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5) if (function_exists('gzdeflate')) { if (isset($this->debug_flag) && $this->debug_flag) { $payload .= ""; } $this->outgoing_headers[] = "Content-Encoding: deflate"; $payload = gzdeflate($payload); } else { if (isset($this->debug_flag) && $this->debug_flag) { $payload .= ""; } } } } //end code $this->outgoing_headers[] = "Content-Length: ".strlen($payload); reset($this->outgoing_headers); foreach($this->outgoing_headers as $hdr){ header($hdr, false); } print $payload; $this->response = join("\r\n",$this->outgoing_headers)."\r\n\r\n".$payload; } /** * takes the value that was created by parsing the request * and compares to the method's signature, if available. * * @param string $operation The operation to be invoked * @param array $request The array of parameter values * @return boolean Whether the operation was found * @access private */ function verify_method($operation,$request){ if(isset($this->wsdl) && is_object($this->wsdl)){ if($this->wsdl->getOperationData($operation)){ return true; } } elseif(isset($this->operations[$operation])){ return true; } return false; } /** * processes SOAP message received from client * * @param array $headers The HTTP headers * @param string $data unprocessed request data from client * @return mixed value of the message, decoded into a PHP type * @access private */ function parseRequest($headers, $data) { $this->debug('Entering parseRequest() for data of length ' . strlen($data) . ' and type ' . $headers['content-type']); if (!strstr($headers['content-type'], 'text/xml')) { $this->setError('Request not of type text/xml'); return false; } if (strpos($headers['content-type'], '=')) { $enc = str_replace('"', '', substr(strstr($headers["content-type"], '='), 1)); $this->debug('Got response encoding: ' . $enc); if(eregi('^(ISO-8859-1|US-ASCII|UTF-8)$',$enc)){ $this->xml_encoding = strtoupper($enc); } else { $this->xml_encoding = 'US-ASCII'; } } else { // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 $this->xml_encoding = 'ISO-8859-1'; } $this->debug('Use encoding: ' . $this->xml_encoding . ' when creating nusoap_parser'); // parse response, get soap parser obj $parser = new nusoap_parser($data,$this->xml_encoding,'',$this->decode_utf8); // parser debug $this->debug("parser debug: \n".$parser->getDebug()); // if fault occurred during message parsing if($err = $parser->getError()){ $this->result = 'fault: error in msg parsing: '.$err; $this->fault('SOAP-ENV:Client',"error in msg parsing:\n".$err); // else successfully parsed request into soapval object } else { // get/set methodname $this->methodURI = $parser->root_struct_namespace; $this->methodname = $parser->root_struct_name; $this->debug('methodname: '.$this->methodname.' methodURI: '.$this->methodURI); $this->debug('calling parser->get_soapbody()'); $this->methodparams = $parser->get_soapbody(); // get SOAP headers $this->requestHeaders = $parser->getHeaders(); // get SOAP Header $this->requestHeader = $parser->get_soapheader(); // add document for doclit support $this->document = $parser->document; } } /** * gets the HTTP body for the current response. * * @param string $soapmsg The SOAP payload * @return string The HTTP body, which includes the SOAP payload * @access private */ function getHTTPBody($soapmsg) { return $soapmsg; } /** * gets the HTTP content type for the current response. * * Note: getHTTPBody must be called before this. * * @return string the HTTP content type for the current response. * @access private */ function getHTTPContentType() { return 'text/xml'; } /** * gets the HTTP content type charset for the current response. * returns false for non-text content types. * * Note: getHTTPBody must be called before this. * * @return string the HTTP content type charset for the current response. * @access private */ function getHTTPContentTypeCharset() { return $this->soap_defencoding; } /** * add a method to the dispatch map (this has been replaced by the register method) * * @param string $methodname * @param string $in array of input values * @param string $out array of output values * @access public * @deprecated */ function add_to_map($methodname,$in,$out){ $this->operations[$methodname] = array('name' => $methodname,'in' => $in,'out' => $out); } /** * register a service function with the server * * @param string $name the name of the PHP function, class.method or class..method * @param array $in assoc array of input values: key = param name, value = param type * @param array $out assoc array of output values: key = param name, value = param type * @param mixed $namespace the element namespace for the method or false * @param mixed $soapaction the soapaction for the method or false * @param mixed $style optional (rpc|document) or false Note: when 'document' is specified, parameter and return wrappers are created for you automatically * @param mixed $use optional (encoded|literal) or false * @param string $documentation optional Description to include in WSDL * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded) * @access public */ function register($name,$in=array(),$out=array(),$namespace=false,$soapaction=false,$style=false,$use=false,$documentation='',$encodingStyle=''){ global $HTTP_SERVER_VARS; if($this->externalWSDLURL){ die('You cannot bind to an external WSDL file, and register methods outside of it! Please choose either WSDL or no WSDL.'); } if (! $name) { die('You must specify a name when you register an operation'); } if (!is_array($in)) { die('You must provide an array for operation inputs'); } if (!is_array($out)) { die('You must provide an array for operation outputs'); } if(false == $namespace) { } if(false == $soapaction) { if (isset($_SERVER)) { $SERVER_NAME = $_SERVER['SERVER_NAME']; $SCRIPT_NAME = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']; $HTTPS = isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] : (isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off'); } elseif (isset($HTTP_SERVER_VARS)) { $SERVER_NAME = $HTTP_SERVER_VARS['SERVER_NAME']; $SCRIPT_NAME = isset($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : $HTTP_SERVER_VARS['SCRIPT_NAME']; $HTTPS = isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off'; } else { $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available"); } if ($HTTPS == '1' || $HTTPS == 'on') { $SCHEME = 'https'; } else { $SCHEME = 'http'; } $soapaction = "$SCHEME://$SERVER_NAME$SCRIPT_NAME/$name"; } if(false == $style) { $style = "rpc"; } if(false == $use) { $use = "encoded"; } if ($use == 'encoded' && $encodingStyle = '') { $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; } $this->operations[$name] = array( 'name' => $name, 'in' => $in, 'out' => $out, 'namespace' => $namespace, 'soapaction' => $soapaction, 'style' => $style); if($this->wsdl){ $this->wsdl->addOperation($name,$in,$out,$namespace,$soapaction,$style,$use,$documentation,$encodingStyle); } return true; } /** * Specify a fault to be returned to the client. * This also acts as a flag to the server that a fault has occured. * * @param string $faultcode * @param string $faultstring * @param string $faultactor * @param string $faultdetail * @access public */ function fault($faultcode,$faultstring,$faultactor='',$faultdetail=''){ if ($faultdetail == '' && $this->debug_flag) { $faultdetail = $this->getDebug(); } $this->fault = new nusoap_fault($faultcode,$faultactor,$faultstring,$faultdetail); $this->fault->soap_defencoding = $this->soap_defencoding; } /** * Sets up wsdl object. * Acts as a flag to enable internal WSDL generation * * @param string $serviceName, name of the service * @param mixed $namespace optional 'tns' service namespace or false * @param mixed $endpoint optional URL of service endpoint or false * @param string $style optional (rpc|document) WSDL style (also specified by operation) * @param string $transport optional SOAP transport * @param mixed $schemaTargetNamespace optional 'types' targetNamespace for service schema or false */ function configureWSDL($serviceName,$namespace = false,$endpoint = false,$style='rpc', $transport = 'http://schemas.xmlsoap.org/soap/http', $schemaTargetNamespace = false) { global $HTTP_SERVER_VARS; if (isset($_SERVER)) { $SERVER_NAME = $_SERVER['SERVER_NAME']; $SERVER_PORT = $_SERVER['SERVER_PORT']; $SCRIPT_NAME = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']; $HTTPS = isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] : (isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off'); } elseif (isset($HTTP_SERVER_VARS)) { $SERVER_NAME = $HTTP_SERVER_VARS['SERVER_NAME']; $SERVER_PORT = $HTTP_SERVER_VARS['SERVER_PORT']; $SCRIPT_NAME = isset($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : $HTTP_SERVER_VARS['SCRIPT_NAME']; $HTTPS = isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off'; } else { $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available"); } // If server name has port number attached then strip it (else port number gets duplicated in WSDL output) (occurred using lighttpd and FastCGI) $colon = strpos($SERVER_NAME,":"); if ($colon) { $SERVER_NAME = substr($SERVER_NAME, 0, $colon); } if ($SERVER_PORT == 80) { $SERVER_PORT = ''; } else { $SERVER_PORT = ':' . $SERVER_PORT; } if(false == $namespace) { $namespace = "http://$SERVER_NAME/soap/$serviceName"; } if(false == $endpoint) { if ($HTTPS == '1' || $HTTPS == 'on') { $SCHEME = 'https'; } else { $SCHEME = 'http'; } $endpoint = "$SCHEME://$SERVER_NAME$SERVER_PORT$SCRIPT_NAME"; } if(false == $schemaTargetNamespace) { $schemaTargetNamespace = $namespace; } $this->wsdl = new wsdl; $this->wsdl->serviceName = $serviceName; $this->wsdl->endpoint = $endpoint; $this->wsdl->namespaces['tns'] = $namespace; $this->wsdl->namespaces['soap'] = 'http://schemas.xmlsoap.org/wsdl/soap/'; $this->wsdl->namespaces['wsdl'] = 'http://schemas.xmlsoap.org/wsdl/'; if ($schemaTargetNamespace != $namespace) { $this->wsdl->namespaces['types'] = $schemaTargetNamespace; } $this->wsdl->schemas[$schemaTargetNamespace][0] = new nusoap_xmlschema('', '', $this->wsdl->namespaces); if ($style == 'document') { $this->wsdl->schemas[$schemaTargetNamespace][0]->schemaInfo['elementFormDefault'] = 'qualified'; } $this->wsdl->schemas[$schemaTargetNamespace][0]->schemaTargetNamespace = $schemaTargetNamespace; $this->wsdl->schemas[$schemaTargetNamespace][0]->imports['http://schemas.xmlsoap.org/soap/encoding/'][0] = array('location' => '', 'loaded' => true); $this->wsdl->schemas[$schemaTargetNamespace][0]->imports['http://schemas.xmlsoap.org/wsdl/'][0] = array('location' => '', 'loaded' => true); $this->wsdl->bindings[$serviceName.'Binding'] = array( 'name'=>$serviceName.'Binding', 'style'=>$style, 'transport'=>$transport, 'portType'=>$serviceName.'PortType'); $this->wsdl->ports[$serviceName.'Port'] = array( 'binding'=>$serviceName.'Binding', 'location'=>$endpoint, 'bindingType'=>'http://schemas.xmlsoap.org/wsdl/soap/'); } } /** * Backward compatibility */ class soap_server extends nusoap_server { } ?> * @author Scott Nichol * @version $Id: nusoap.php,v 1.114 2007/11/06 15:17:46 snichol Exp $ * @access public */ class wsdl extends nusoap_base { // URL or filename of the root of this WSDL var $wsdl; // define internal arrays of bindings, ports, operations, messages, etc. var $schemas = array(); var $currentSchema; var $message = array(); var $complexTypes = array(); var $messages = array(); var $currentMessage; var $currentOperation; var $portTypes = array(); var $currentPortType; var $bindings = array(); var $currentBinding; var $ports = array(); var $currentPort; var $opData = array(); var $status = ''; var $documentation = false; var $endpoint = ''; // array of wsdl docs to import var $import = array(); // parser vars var $parser; var $position = 0; var $depth = 0; var $depth_array = array(); // for getting wsdl var $proxyhost = ''; var $proxyport = ''; var $proxyusername = ''; var $proxypassword = ''; var $timeout = 0; var $response_timeout = 30; var $curl_options = array(); // User-specified cURL options var $use_curl = false; // whether to always try to use cURL // for HTTP authentication var $username = ''; // Username for HTTP authentication var $password = ''; // Password for HTTP authentication var $authtype = ''; // Type of HTTP authentication var $certRequest = array(); // Certificate for HTTP SSL authentication /** * constructor * * @param string $wsdl WSDL document URL * @param string $proxyhost * @param string $proxyport * @param string $proxyusername * @param string $proxypassword * @param integer $timeout set the connection timeout * @param integer $response_timeout set the response timeout * @param array $curl_options user-specified cURL options * @param boolean $use_curl try to use cURL * @access public */ function wsdl($wsdl = '',$proxyhost=false,$proxyport=false,$proxyusername=false,$proxypassword=false,$timeout=0,$response_timeout=30,$curl_options=null,$use_curl=false){ parent::nusoap_base(); $this->debug("ctor wsdl=$wsdl timeout=$timeout response_timeout=$response_timeout"); $this->proxyhost = $proxyhost; $this->proxyport = $proxyport; $this->proxyusername = $proxyusername; $this->proxypassword = $proxypassword; $this->timeout = $timeout; $this->response_timeout = $response_timeout; if (is_array($curl_options)) $this->curl_options = $curl_options; $this->use_curl = $use_curl; $this->fetchWSDL($wsdl); } /** * fetches the WSDL document and parses it * * @access public */ function fetchWSDL($wsdl) { $this->debug("parse and process WSDL path=$wsdl"); $this->wsdl = $wsdl; // parse wsdl file if ($this->wsdl != "") { $this->parseWSDL($this->wsdl); } // imports // TODO: handle imports more properly, grabbing them in-line and nesting them $imported_urls = array(); $imported = 1; while ($imported > 0) { $imported = 0; // Schema imports foreach ($this->schemas as $ns => $list) { foreach ($list as $xs) { $wsdlparts = parse_url($this->wsdl); // this is bogusly simple! foreach ($xs->imports as $ns2 => $list2) { for ($ii = 0; $ii < count($list2); $ii++) { if (! $list2[$ii]['loaded']) { $this->schemas[$ns]->imports[$ns2][$ii]['loaded'] = true; $url = $list2[$ii]['location']; if ($url != '') { $urlparts = parse_url($url); if (!isset($urlparts['host'])) { $url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' .$wsdlparts['port'] : '') . substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path']; } if (! in_array($url, $imported_urls)) { $this->parseWSDL($url); $imported++; $imported_urls[] = $url; } } else { $this->debug("Unexpected scenario: empty URL for unloaded import"); } } } } } } // WSDL imports $wsdlparts = parse_url($this->wsdl); // this is bogusly simple! foreach ($this->import as $ns => $list) { for ($ii = 0; $ii < count($list); $ii++) { if (! $list[$ii]['loaded']) { $this->import[$ns][$ii]['loaded'] = true; $url = $list[$ii]['location']; if ($url != '') { $urlparts = parse_url($url); if (!isset($urlparts['host'])) { $url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' . $wsdlparts['port'] : '') . substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path']; } if (! in_array($url, $imported_urls)) { $this->parseWSDL($url); $imported++; $imported_urls[] = $url; } } else { $this->debug("Unexpected scenario: empty URL for unloaded import"); } } } } } // add new data to operation data foreach($this->bindings as $binding => $bindingData) { if (isset($bindingData['operations']) && is_array($bindingData['operations'])) { foreach($bindingData['operations'] as $operation => $data) { $this->debug('post-parse data gathering for ' . $operation); $this->bindings[$binding]['operations'][$operation]['input'] = isset($this->bindings[$binding]['operations'][$operation]['input']) ? array_merge($this->bindings[$binding]['operations'][$operation]['input'], $this->portTypes[ $bindingData['portType'] ][$operation]['input']) : $this->portTypes[ $bindingData['portType'] ][$operation]['input']; $this->bindings[$binding]['operations'][$operation]['output'] = isset($this->bindings[$binding]['operations'][$operation]['output']) ? array_merge($this->bindings[$binding]['operations'][$operation]['output'], $this->portTypes[ $bindingData['portType'] ][$operation]['output']) : $this->portTypes[ $bindingData['portType'] ][$operation]['output']; if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ])){ $this->bindings[$binding]['operations'][$operation]['input']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ]; } if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ])){ $this->bindings[$binding]['operations'][$operation]['output']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ]; } // Set operation style if necessary, but do not override one already provided if (isset($bindingData['style']) && !isset($this->bindings[$binding]['operations'][$operation]['style'])) { $this->bindings[$binding]['operations'][$operation]['style'] = $bindingData['style']; } $this->bindings[$binding]['operations'][$operation]['transport'] = isset($bindingData['transport']) ? $bindingData['transport'] : ''; $this->bindings[$binding]['operations'][$operation]['documentation'] = isset($this->portTypes[ $bindingData['portType'] ][$operation]['documentation']) ? $this->portTypes[ $bindingData['portType'] ][$operation]['documentation'] : ''; $this->bindings[$binding]['operations'][$operation]['endpoint'] = isset($bindingData['endpoint']) ? $bindingData['endpoint'] : ''; } } } } /** * parses the wsdl document * * @param string $wsdl path or URL * @access private */ function parseWSDL($wsdl = '') { $this->debug("parse WSDL at path=$wsdl"); if ($wsdl == '') { $this->debug('no wsdl passed to parseWSDL()!!'); $this->setError('no wsdl passed to parseWSDL()!!'); return false; } // parse $wsdl for url format $wsdl_props = parse_url($wsdl); if (isset($wsdl_props['scheme']) && ($wsdl_props['scheme'] == 'http' || $wsdl_props['scheme'] == 'https')) { $this->debug('getting WSDL http(s) URL ' . $wsdl); // get wsdl $tr = new soap_transport_http($wsdl, $this->curl_options, $this->use_curl); $tr->request_method = 'GET'; $tr->useSOAPAction = false; if($this->proxyhost && $this->proxyport){ $tr->setProxy($this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword); } if ($this->authtype != '') { $tr->setCredentials($this->username, $this->password, $this->authtype, array(), $this->certRequest); } $tr->setEncoding('gzip, deflate'); $wsdl_string = $tr->send('', $this->timeout, $this->response_timeout); //$this->debug("WSDL request\n" . $tr->outgoing_payload); //$this->debug("WSDL response\n" . $tr->incoming_payload); $this->appendDebug($tr->getDebug()); // catch errors if($err = $tr->getError() ){ $errstr = 'HTTP ERROR: '.$err; $this->debug($errstr); $this->setError($errstr); unset($tr); return false; } unset($tr); $this->debug("got WSDL URL"); } else { // $wsdl is not http(s), so treat it as a file URL or plain file path if (isset($wsdl_props['scheme']) && ($wsdl_props['scheme'] == 'file') && isset($wsdl_props['path'])) { $path = isset($wsdl_props['host']) ? ($wsdl_props['host'] . ':' . $wsdl_props['path']) : $wsdl_props['path']; } else { $path = $wsdl; } $this->debug('getting WSDL file ' . $path); if ($fp = @fopen($path, 'r')) { $wsdl_string = ''; while ($data = fread($fp, 32768)) { $wsdl_string .= $data; } fclose($fp); } else { $errstr = "Bad path to WSDL file $path"; $this->debug($errstr); $this->setError($errstr); return false; } } $this->debug('Parse WSDL'); // end new code added // Create an XML parser. $this->parser = xml_parser_create(); // Set the options for parsing the XML data. // xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1); 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. xml_set_element_handler($this->parser, 'start_element', 'end_element'); xml_set_character_data_handler($this->parser, 'character_data'); // Parse the XML file. if (!xml_parse($this->parser, $wsdl_string, true)) { // Display an error message. $errstr = sprintf( 'XML error parsing WSDL from %s on line %d: %s', $wsdl, xml_get_current_line_number($this->parser), xml_error_string(xml_get_error_code($this->parser)) ); $this->debug($errstr); $this->debug("XML payload:\n" . $wsdl_string); $this->setError($errstr); return false; } // free the parser xml_parser_free($this->parser); $this->debug('Parsing WSDL done'); // catch wsdl parse errors if($this->getError()){ return false; } return true; } /** * start-element handler * * @param string $parser XML parser object * @param string $name element name * @param string $attrs associative array of attributes * @access private */ function start_element($parser, $name, $attrs) { if ($this->status == 'schema') { $this->currentSchema->schemaStartElement($parser, $name, $attrs); $this->appendDebug($this->currentSchema->getDebug()); $this->currentSchema->clearDebug(); } elseif (ereg('schema$', $name)) { $this->debug('Parsing WSDL schema'); // $this->debug("startElement for $name ($attrs[name]). status = $this->status (".$this->getLocalPart($name).")"); $this->status = 'schema'; $this->currentSchema = new nusoap_xmlschema('', '', $this->namespaces); $this->currentSchema->schemaStartElement($parser, $name, $attrs); $this->appendDebug($this->currentSchema->getDebug()); $this->currentSchema->clearDebug(); } else { // 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; $this->message[$pos] = array('cdata' => ''); // process attributes if (count($attrs) > 0) { // register namespace declarations foreach($attrs as $k => $v) { if (ereg("^xmlns", $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' || $v == 'http://www.w3.org/2000/10/XMLSchema') { $this->XMLSchemaVersion = $v; $this->namespaces['xsi'] = $v . '-instance'; } } } // expand each attribute prefix to its namespace foreach($attrs as $k => $v) { $k = strpos($k, ':') ? $this->expandQname($k) : $k; if ($k != 'location' && $k != 'soapAction' && $k != 'namespace') { $v = strpos($v, ':') ? $this->expandQname($v) : $v; } $eAttrs[$k] = $v; } $attrs = $eAttrs; } else { $attrs = array(); } // get element prefix, namespace and name if (ereg(':', $name)) { // get ns prefix $prefix = substr($name, 0, strpos($name, ':')); // get ns $namespace = isset($this->namespaces[$prefix]) ? $this->namespaces[$prefix] : ''; // get unqualified name $name = substr(strstr($name, ':'), 1); } // process attributes, expanding any prefixes to namespaces // find status, register data switch ($this->status) { case 'message': if ($name == 'part') { if (isset($attrs['type'])) { $this->debug("msg " . $this->currentMessage . ": found part (with type) $attrs[name]: " . implode(',', $attrs)); $this->messages[$this->currentMessage][$attrs['name']] = $attrs['type']; } if (isset($attrs['element'])) { $this->debug("msg " . $this->currentMessage . ": found part (with element) $attrs[name]: " . implode(',', $attrs)); $this->messages[$this->currentMessage][$attrs['name']] = $attrs['element'] . '^'; } } break; case 'portType': switch ($name) { case 'operation': $this->currentPortOperation = $attrs['name']; $this->debug("portType $this->currentPortType operation: $this->currentPortOperation"); if (isset($attrs['parameterOrder'])) { $this->portTypes[$this->currentPortType][$attrs['name']]['parameterOrder'] = $attrs['parameterOrder']; } break; case 'documentation': $this->documentation = true; break; // merge input/output data default: $m = isset($attrs['message']) ? $this->getLocalPart($attrs['message']) : ''; $this->portTypes[$this->currentPortType][$this->currentPortOperation][$name]['message'] = $m; break; } break; case 'binding': switch ($name) { case 'binding': // get ns prefix if (isset($attrs['style'])) { $this->bindings[$this->currentBinding]['prefix'] = $prefix; } $this->bindings[$this->currentBinding] = array_merge($this->bindings[$this->currentBinding], $attrs); break; case 'header': $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus]['headers'][] = $attrs; break; case 'operation': if (isset($attrs['soapAction'])) { $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['soapAction'] = $attrs['soapAction']; } if (isset($attrs['style'])) { $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['style'] = $attrs['style']; } if (isset($attrs['name'])) { $this->currentOperation = $attrs['name']; $this->debug("current binding operation: $this->currentOperation"); $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['name'] = $attrs['name']; $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['binding'] = $this->currentBinding; $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['endpoint'] = isset($this->bindings[$this->currentBinding]['endpoint']) ? $this->bindings[$this->currentBinding]['endpoint'] : ''; } break; case 'input': $this->opStatus = 'input'; break; case 'output': $this->opStatus = 'output'; break; case 'body': if (isset($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus])) { $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = array_merge($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus], $attrs); } else { $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = $attrs; } break; } break; case 'service': switch ($name) { case 'port': $this->currentPort = $attrs['name']; $this->debug('current port: ' . $this->currentPort); $this->ports[$this->currentPort]['binding'] = $this->getLocalPart($attrs['binding']); break; case 'address': $this->ports[$this->currentPort]['location'] = $attrs['location']; $this->ports[$this->currentPort]['bindingType'] = $namespace; $this->bindings[ $this->ports[$this->currentPort]['binding'] ]['bindingType'] = $namespace; $this->bindings[ $this->ports[$this->currentPort]['binding'] ]['endpoint'] = $attrs['location']; break; } break; } // set status switch ($name) { case 'import': if (isset($attrs['location'])) { $this->import[$attrs['namespace']][] = array('location' => $attrs['location'], 'loaded' => false); $this->debug('parsing import ' . $attrs['namespace']. ' - ' . $attrs['location'] . ' (' . count($this->import[$attrs['namespace']]).')'); } else { $this->import[$attrs['namespace']][] = array('location' => '', 'loaded' => true); if (! $this->getPrefixFromNamespace($attrs['namespace'])) { $this->namespaces['ns'.(count($this->namespaces)+1)] = $attrs['namespace']; } $this->debug('parsing import ' . $attrs['namespace']. ' - [no location] (' . count($this->import[$attrs['namespace']]).')'); } break; //wait for schema //case 'types': // $this->status = 'schema'; // break; case 'message': $this->status = 'message'; $this->messages[$attrs['name']] = array(); $this->currentMessage = $attrs['name']; break; case 'portType': $this->status = 'portType'; $this->portTypes[$attrs['name']] = array(); $this->currentPortType = $attrs['name']; break; case "binding": if (isset($attrs['name'])) { // get binding name if (strpos($attrs['name'], ':')) { $this->currentBinding = $this->getLocalPart($attrs['name']); } else { $this->currentBinding = $attrs['name']; } $this->status = 'binding'; $this->bindings[$this->currentBinding]['portType'] = $this->getLocalPart($attrs['type']); $this->debug("current binding: $this->currentBinding of portType: " . $attrs['type']); } break; case 'service': $this->serviceName = $attrs['name']; $this->status = 'service'; $this->debug('current service: ' . $this->serviceName); break; case 'definitions': foreach ($attrs as $name => $value) { $this->wsdl_info[$name] = $value; } break; } } } /** * end-element handler * * @param string $parser XML parser object * @param string $name element name * @access private */ function end_element($parser, $name){ // unset schema status if (/*ereg('types$', $name) ||*/ ereg('schema$', $name)) { $this->status = ""; $this->appendDebug($this->currentSchema->getDebug()); $this->currentSchema->clearDebug(); $this->schemas[$this->currentSchema->schemaTargetNamespace][] = $this->currentSchema; $this->debug('Parsing WSDL schema done'); } if ($this->status == 'schema') { $this->currentSchema->schemaEndElement($parser, $name); } else { // bring depth down a notch $this->depth--; } // end documentation if ($this->documentation) { //TODO: track the node to which documentation should be assigned; it can be a part, message, etc. //$this->portTypes[$this->currentPortType][$this->currentPortOperation]['documentation'] = $this->documentation; $this->documentation = false; } } /** * element content handler * * @param string $parser XML parser object * @param string $data element content * @access private */ function character_data($parser, $data) { $pos = isset($this->depth_array[$this->depth]) ? $this->depth_array[$this->depth] : 0; if (isset($this->message[$pos]['cdata'])) { $this->message[$pos]['cdata'] .= $data; } if ($this->documentation) { $this->documentation .= $data; } } /** * if authenticating, set user credentials here * * @param string $username * @param string $password * @param string $authtype (basic|digest|certificate|ntlm) * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, certpassword (optional), verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs) * @access public */ function setCredentials($username, $password, $authtype = 'basic', $certRequest = array()) { $this->debug("setCredentials username=$username authtype=$authtype certRequest="); $this->appendDebug($this->varDump($certRequest)); $this->username = $username; $this->password = $password; $this->authtype = $authtype; $this->certRequest = $certRequest; } function getBindingData($binding) { if (is_array($this->bindings[$binding])) { return $this->bindings[$binding]; } } /** * returns an assoc array of operation names => operation data * * @param string $bindingType eg: soap, smtp, dime (only soap and soap12 are currently supported) * @return array * @access public */ function getOperations($bindingType = 'soap') { $ops = array(); if ($bindingType == 'soap') { $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/'; } elseif ($bindingType == 'soap12') { $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap12/'; } // loop thru ports foreach($this->ports as $port => $portData) { // binding type of port matches parameter if ($portData['bindingType'] == $bindingType) { //$this->debug("getOperations for port $port"); //$this->debug("port data: " . $this->varDump($portData)); //$this->debug("bindings: " . $this->varDump($this->bindings[ $portData['binding'] ])); // merge bindings if (isset($this->bindings[ $portData['binding'] ]['operations'])) { $ops = array_merge ($ops, $this->bindings[ $portData['binding'] ]['operations']); } } } return $ops; } /** * returns an associative array of data necessary for calling an operation * * @param string $operation name of operation * @param string $bindingType type of binding eg: soap, soap12 * @return array * @access public */ function getOperationData($operation, $bindingType = 'soap') { if ($bindingType == 'soap') { $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/'; } elseif ($bindingType == 'soap12') { $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap12/'; } // loop thru ports foreach($this->ports as $port => $portData) { // binding type of port matches parameter if ($portData['bindingType'] == $bindingType) { // get binding //foreach($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) { foreach(array_keys($this->bindings[ $portData['binding'] ]['operations']) as $bOperation) { // note that we could/should also check the namespace here if ($operation == $bOperation) { $opData = $this->bindings[ $portData['binding'] ]['operations'][$operation]; return $opData; } } } } } /** * returns an associative array of data necessary for calling an operation * * @param string $soapAction soapAction for operation * @param string $bindingType type of binding eg: soap, soap12 * @return array * @access public */ function getOperationDataForSoapAction($soapAction, $bindingType = 'soap') { if ($bindingType == 'soap') { $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/'; } elseif ($bindingType == 'soap12') { $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap12/'; } // loop thru ports foreach($this->ports as $port => $portData) { // binding type of port matches parameter if ($portData['bindingType'] == $bindingType) { // loop through operations for the binding foreach ($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) { if ($opData['soapAction'] == $soapAction) { return $opData; } } } } } /** * 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 $type the type * @param string $ns namespace (not prefix) of the type * @return mixed * @access public * @see nusoap_xmlschema */ function getTypeDef($type, $ns) { $this->debug("in getTypeDef: type=$type, ns=$ns"); if ((! $ns) && isset($this->namespaces['tns'])) { $ns = $this->namespaces['tns']; $this->debug("in getTypeDef: type namespace forced to $ns"); } if (!isset($this->schemas[$ns])) { foreach ($this->schemas as $ns0 => $schema0) { if (strcasecmp($ns, $ns0) == 0) { $this->debug("in getTypeDef: replacing schema namespace $ns with $ns0"); $ns = $ns0; break; } } } if (isset($this->schemas[$ns])) { $this->debug("in getTypeDef: have schema for namespace $ns"); for ($i = 0; $i < count($this->schemas[$ns]); $i++) { $xs = &$this->schemas[$ns][$i]; $t = $xs->getTypeDef($type); //$this->appendDebug($xs->getDebug()); //$xs->clearDebug(); if ($t) { if (!isset($t['phpType'])) { // get info for type to tack onto the element $uqType = substr($t['type'], strrpos($t['type'], ':') + 1); $ns = substr($t['type'], 0, strrpos($t['type'], ':')); $etype = $this->getTypeDef($uqType, $ns); if ($etype) { $this->debug("found type for [element] $type:"); $this->debug($this->varDump($etype)); if (isset($etype['phpType'])) { $t['phpType'] = $etype['phpType']; } if (isset($etype['elements'])) { $t['elements'] = $etype['elements']; } if (isset($etype['attrs'])) { $t['attrs'] = $etype['attrs']; } } } return $t; } } } else { $this->debug("in getTypeDef: do not have schema for namespace $ns"); } return false; } /** * prints html description of services * * @access private */ function webDescription(){ global $HTTP_SERVER_VARS; if (isset($_SERVER)) { $PHP_SELF = $_SERVER['PHP_SELF']; } elseif (isset($HTTP_SERVER_VARS)) { $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF']; } else { $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available"); } $b = ' NuSOAP: '.$this->serviceName.'


    '.$this->serviceName.'
    '; return $b; } /** * serialize the parsed wsdl * * @param mixed $debug whether to put debug=1 in endpoint URL * @return string serialization of WSDL * @access public */ function serialize($debug = 0) { $xml = ''; $xml .= "\nnamespaces as $k => $v) { $xml .= " xmlns:$k=\"$v\""; } // 10.9.02 - add poulter fix for wsdl and tns declarations if (isset($this->namespaces['wsdl'])) { $xml .= " xmlns=\"" . $this->namespaces['wsdl'] . "\""; } if (isset($this->namespaces['tns'])) { $xml .= " targetNamespace=\"" . $this->namespaces['tns'] . "\""; } $xml .= '>'; // imports if (sizeof($this->import) > 0) { foreach($this->import as $ns => $list) { foreach ($list as $ii) { if ($ii['location'] != '') { $xml .= ''; } else { $xml .= ''; } } } } // types if (count($this->schemas)>=1) { $xml .= "\n\n"; foreach ($this->schemas as $ns => $list) { foreach ($list as $xs) { $xml .= $xs->serializeSchema(); } } $xml .= ''; } // messages if (count($this->messages) >= 1) { foreach($this->messages as $msgName => $msgParts) { $xml .= "\n'; if(is_array($msgParts)){ foreach($msgParts as $partName => $partType) { // print 'serializing '.$partType.', sv: '.$this->XMLSchemaVersion.'
    '; if (strpos($partType, ':')) { $typePrefix = $this->getPrefixFromNamespace($this->getPrefix($partType)); } elseif (isset($this->typemap[$this->namespaces['xsd']][$partType])) { // print 'checking typemap: '.$this->XMLSchemaVersion.'
    '; $typePrefix = 'xsd'; } else { foreach($this->typemap as $ns => $types) { if (isset($types[$partType])) { $typePrefix = $this->getPrefixFromNamespace($ns); } } if (!isset($typePrefix)) { die("$partType has no namespace!"); } } $ns = $this->getNamespaceFromPrefix($typePrefix); $localPart = $this->getLocalPart($partType); $typeDef = $this->getTypeDef($localPart, $ns); if ($typeDef['typeClass'] == 'element') { $elementortype = 'element'; if (substr($localPart, -1) == '^') { $localPart = substr($localPart, 0, -1); } } else { $elementortype = 'type'; } $xml .= "\n" . ' '; } } $xml .= '
    '; } } // bindings & porttypes if (count($this->bindings) >= 1) { $binding_xml = ''; $portType_xml = ''; foreach($this->bindings as $bindingName => $attrs) { $binding_xml .= "\n'; $binding_xml .= "\n" . ' '; $portType_xml .= "\n'; foreach($attrs['operations'] as $opName => $opParts) { $binding_xml .= "\n" . ' '; $binding_xml .= "\n" . ' '; if (isset($opParts['input']['encodingStyle']) && $opParts['input']['encodingStyle'] != '') { $enc_style = ' encodingStyle="' . $opParts['input']['encodingStyle'] . '"'; } else { $enc_style = ''; } $binding_xml .= "\n" . ' '; if (isset($opParts['output']['encodingStyle']) && $opParts['output']['encodingStyle'] != '') { $enc_style = ' encodingStyle="' . $opParts['output']['encodingStyle'] . '"'; } else { $enc_style = ''; } $binding_xml .= "\n" . ' '; $binding_xml .= "\n" . ' '; $portType_xml .= "\n" . ' ' . htmlspecialchars($opParts['documentation']) . ''; } $portType_xml .= "\n" . ' '; $portType_xml .= "\n" . ' '; $portType_xml .= "\n" . ' '; } $portType_xml .= "\n" . ''; $binding_xml .= "\n" . ''; } $xml .= $portType_xml . $binding_xml; } // services $xml .= "\nserviceName . '">'; if (count($this->ports) >= 1) { foreach($this->ports as $pName => $attrs) { $xml .= "\n" . ' '; $xml .= "\n" . ' '; $xml .= "\n" . ' '; } } $xml .= "\n" . ''; return $xml . "\n"; } /** * determine whether a set of parameters are unwrapped * when they are expect to be wrapped, Microsoft-style. * * @param string $type the type (element name) of the wrapper * @param array $parameters the parameter values for the SOAP call * @return boolean whether they parameters are unwrapped (and should be wrapped) * @access private */ function parametersMatchWrapped($type, &$parameters) { $this->debug("in parametersMatchWrapped type=$type, parameters="); $this->appendDebug($this->varDump($parameters)); // split type into namespace:unqualified-type if (strpos($type, ':')) { $uqType = substr($type, strrpos($type, ':') + 1); $ns = substr($type, 0, strrpos($type, ':')); $this->debug("in parametersMatchWrapped: got a prefixed type: $uqType, $ns"); if ($this->getNamespaceFromPrefix($ns)) { $ns = $this->getNamespaceFromPrefix($ns); $this->debug("in parametersMatchWrapped: expanded prefixed type: $uqType, $ns"); } } else { // TODO: should the type be compared to types in XSD, and the namespace // set to XSD if the type matches? $this->debug("in parametersMatchWrapped: No namespace for type $type"); $ns = ''; $uqType = $type; } // get the type information if (!$typeDef = $this->getTypeDef($uqType, $ns)) { $this->debug("in parametersMatchWrapped: $type ($uqType) is not a supported type."); return false; } $this->debug("in parametersMatchWrapped: found typeDef="); $this->appendDebug($this->varDump($typeDef)); if (substr($uqType, -1) == '^') { $uqType = substr($uqType, 0, -1); } $phpType = $typeDef['phpType']; $arrayType = (isset($typeDef['arrayType']) ? $typeDef['arrayType'] : ''); $this->debug("in parametersMatchWrapped: uqType: $uqType, ns: $ns, phptype: $phpType, arrayType: $arrayType"); // we expect a complexType or element of complexType if ($phpType != 'struct') { $this->debug("in parametersMatchWrapped: not a struct"); return false; } // see whether the parameter names match the elements if (isset($typeDef['elements']) && is_array($typeDef['elements'])) { $elements = 0; $matches = 0; $change = false; if ($this->isArraySimpleOrStruct($parameters) == 'arraySimple' && count($parameters) == count($typeDef['elements'])) { $this->debug("in parametersMatchWrapped: (wrapped return value kludge) correct number of elements in simple array, so change array and wrap"); $change = true; } foreach ($typeDef['elements'] as $name => $attrs) { if ($change) { $this->debug("in parametersMatchWrapped: change parameter $element to name $name"); $parameters[$name] = $parameters[$elements]; unset($parameters[$elements]); $matches++; } elseif (isset($parameters[$name])) { $this->debug("in parametersMatchWrapped: have parameter named $name"); $matches++; } else { $this->debug("in parametersMatchWrapped: do not have parameter named $name"); } $elements++; } $this->debug("in parametersMatchWrapped: $matches parameter names match $elements wrapped parameter names"); if ($matches == 0) { return false; } return true; } // since there are no elements for the type, if the user passed no // parameters, the parameters match wrapped. $this->debug("in parametersMatchWrapped: no elements type $ns:$uqType"); return count($parameters) == 0; } /** * serialize PHP values according to a WSDL message definition * contrary to the method name, this is not limited to RPC * * TODO * - multi-ref serialization * - validate PHP values against type definitions, return errors if invalid * * @param string $operation operation name * @param string $direction (input|output) * @param mixed $parameters parameter value(s) * @param string $bindingType (soap|soap12) * @return mixed parameters serialized as XML or false on error (e.g. operation not found) * @access public */ function serializeRPCParameters($operation, $direction, $parameters, $bindingType = 'soap') { $this->debug("in serializeRPCParameters: operation=$operation, direction=$direction, XMLSchemaVersion=$this->XMLSchemaVersion, bindingType=$bindingType"); $this->appendDebug('parameters=' . $this->varDump($parameters)); if ($direction != 'input' && $direction != 'output') { $this->debug('The value of the \$direction argument needs to be either "input" or "output"'); $this->setError('The value of the \$direction argument needs to be either "input" or "output"'); return false; } if (!$opData = $this->getOperationData($operation, $bindingType)) { $this->debug('Unable to retrieve WSDL data for operation: ' . $operation . ' bindingType: ' . $bindingType); $this->setError('Unable to retrieve WSDL data for operation: ' . $operation . ' bindingType: ' . $bindingType); return false; } $this->debug('in serializeRPCParameters: opData:'); $this->appendDebug($this->varDump($opData)); // Get encoding style for output and set to current $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; if(($direction == 'input') && isset($opData['output']['encodingStyle']) && ($opData['output']['encodingStyle'] != $encodingStyle)) { $encodingStyle = $opData['output']['encodingStyle']; $enc_style = $encodingStyle; } // set input params $xml = ''; if (isset($opData[$direction]['parts']) && sizeof($opData[$direction]['parts']) > 0) { $parts = &$opData[$direction]['parts']; $part_count = sizeof($parts); $style = $opData['style']; $use = $opData[$direction]['use']; $this->debug("have $part_count part(s) to serialize using $style/$use"); if (is_array($parameters)) { $parametersArrayType = $this->isArraySimpleOrStruct($parameters); $parameter_count = count($parameters); $this->debug("have $parameter_count parameter(s) provided as $parametersArrayType to serialize"); // check for Microsoft-style wrapped parameters if ($style == 'document' && $use == 'literal' && $part_count == 1 && isset($parts['parameters'])) { $this->debug('check whether the caller has wrapped the parameters'); if ((($parametersArrayType == 'arrayStruct' || $parameter_count == 0) && !isset($parameters['parameters'])) || ($direction == 'output' && $parametersArrayType == 'arraySimple' && $parameter_count == 1)) { $this->debug('check whether caller\'s parameters match the wrapped ones'); if ($this->parametersMatchWrapped($parts['parameters'], $parameters)) { $this->debug('wrap the parameters for the caller'); $parameters = array('parameters' => $parameters); $parameter_count = 1; } } } foreach ($parts as $name => $type) { $this->debug("serializing part $name of type $type"); // Track encoding style if (isset($opData[$direction]['encodingStyle']) && $encodingStyle != $opData[$direction]['encodingStyle']) { $encodingStyle = $opData[$direction]['encodingStyle']; $enc_style = $encodingStyle; } else { $enc_style = false; } // NOTE: add error handling here // if serializeType returns false, then catch global error and fault if ($parametersArrayType == 'arraySimple') { $p = array_shift($parameters); $this->debug('calling serializeType w/indexed param'); $xml .= $this->serializeType($name, $type, $p, $use, $enc_style); } elseif (isset($parameters[$name])) { $this->debug('calling serializeType w/named param'); $xml .= $this->serializeType($name, $type, $parameters[$name], $use, $enc_style); } else { // TODO: only send nillable $this->debug('calling serializeType w/null param'); $xml .= $this->serializeType($name, $type, null, $use, $enc_style); } } } else { $this->debug('no parameters passed.'); } } $this->debug("serializeRPCParameters returning: $xml"); return $xml; } /** * serialize a PHP value according to a WSDL message definition * * TODO * - multi-ref serialization * - validate PHP values against type definitions, return errors if invalid * * @param string $operation operation name * @param string $direction (input|output) * @param mixed $parameters parameter value(s) * @return mixed parameters serialized as XML or false on error (e.g. operation not found) * @access public * @deprecated */ function serializeParameters($operation, $direction, $parameters) { $this->debug("in serializeParameters: operation=$operation, direction=$direction, XMLSchemaVersion=$this->XMLSchemaVersion"); $this->appendDebug('parameters=' . $this->varDump($parameters)); if ($direction != 'input' && $direction != 'output') { $this->debug('The value of the \$direction argument needs to be either "input" or "output"'); $this->setError('The value of the \$direction argument needs to be either "input" or "output"'); return false; } if (!$opData = $this->getOperationData($operation)) { $this->debug('Unable to retrieve WSDL data for operation: ' . $operation); $this->setError('Unable to retrieve WSDL data for operation: ' . $operation); return false; } $this->debug('opData:'); $this->appendDebug($this->varDump($opData)); // Get encoding style for output and set to current $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; if(($direction == 'input') && isset($opData['output']['encodingStyle']) && ($opData['output']['encodingStyle'] != $encodingStyle)) { $encodingStyle = $opData['output']['encodingStyle']; $enc_style = $encodingStyle; } // set input params $xml = ''; if (isset($opData[$direction]['parts']) && sizeof($opData[$direction]['parts']) > 0) { $use = $opData[$direction]['use']; $this->debug("use=$use"); $this->debug('got ' . count($opData[$direction]['parts']) . ' part(s)'); if (is_array($parameters)) { $parametersArrayType = $this->isArraySimpleOrStruct($parameters); $this->debug('have ' . $parametersArrayType . ' parameters'); foreach($opData[$direction]['parts'] as $name => $type) { $this->debug('serializing part "'.$name.'" of type "'.$type.'"'); // Track encoding style if(isset($opData[$direction]['encodingStyle']) && $encodingStyle != $opData[$direction]['encodingStyle']) { $encodingStyle = $opData[$direction]['encodingStyle']; $enc_style = $encodingStyle; } else { $enc_style = false; } // NOTE: add error handling here // if serializeType returns false, then catch global error and fault if ($parametersArrayType == 'arraySimple') { $p = array_shift($parameters); $this->debug('calling serializeType w/indexed param'); $xml .= $this->serializeType($name, $type, $p, $use, $enc_style); } elseif (isset($parameters[$name])) { $this->debug('calling serializeType w/named param'); $xml .= $this->serializeType($name, $type, $parameters[$name], $use, $enc_style); } else { // TODO: only send nillable $this->debug('calling serializeType w/null param'); $xml .= $this->serializeType($name, $type, null, $use, $enc_style); } } } else { $this->debug('no parameters passed.'); } } $this->debug("serializeParameters returning: $xml"); return $xml; } /** * serializes a PHP value according a given type definition * * @param string $name name of value (part or element) * @param string $type XML schema type of value (type or element) * @param mixed $value a native PHP value (parameter value) * @param string $use use for part (encoded|literal) * @param string $encodingStyle SOAP encoding style for the value (if different than the enclosing style) * @param boolean $unqualified a kludge for what should be XML namespace form handling * @return string value serialized as an XML string * @access private */ function serializeType($name, $type, $value, $use='encoded', $encodingStyle=false, $unqualified=false) { $this->debug("in serializeType: name=$name, type=$type, use=$use, encodingStyle=$encodingStyle, unqualified=" . ($unqualified ? "unqualified" : "qualified")); $this->appendDebug("value=" . $this->varDump($value)); if($use == 'encoded' && $encodingStyle) { $encodingStyle = ' SOAP-ENV:encodingStyle="' . $encodingStyle . '"'; } // if a soapval has been supplied, let its type override the WSDL if (is_object($value) && get_class($value) == 'soapval') { if ($value->type_ns) { $type = $value->type_ns . ':' . $value->type; $forceType = true; $this->debug("in serializeType: soapval overrides type to $type"); } elseif ($value->type) { $type = $value->type; $forceType = true; $this->debug("in serializeType: soapval overrides type to $type"); } else { $forceType = false; $this->debug("in serializeType: soapval does not override type"); } $attrs = $value->attributes; $value = $value->value; $this->debug("in serializeType: soapval overrides value to $value"); if ($attrs) { if (!is_array($value)) { $value['!'] = $value; } foreach ($attrs as $n => $v) { $value['!' . $n] = $v; } $this->debug("in serializeType: soapval provides attributes"); } } else { $forceType = false; } $xml = ''; if (strpos($type, ':')) { $uqType = substr($type, strrpos($type, ':') + 1); $ns = substr($type, 0, strrpos($type, ':')); $this->debug("in serializeType: got a prefixed type: $uqType, $ns"); if ($this->getNamespaceFromPrefix($ns)) { $ns = $this->getNamespaceFromPrefix($ns); $this->debug("in serializeType: expanded prefixed type: $uqType, $ns"); } if($ns == $this->XMLSchemaVersion || $ns == 'http://schemas.xmlsoap.org/soap/encoding/'){ $this->debug('in serializeType: type namespace indicates XML Schema or SOAP Encoding type'); if ($unqualified && $use == 'literal') { $elementNS = " xmlns=\"\""; } else { $elementNS = ''; } if (is_null($value)) { if ($use == 'literal') { // TODO: depends on minOccurs $xml = "<$name$elementNS/>"; } else { // TODO: depends on nillable, which should be checked before calling this method $xml = "<$name$elementNS xsi:nil=\"true\" xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"/>"; } $this->debug("in serializeType: returning: $xml"); return $xml; } if ($uqType == 'Array') { // JBoss/Axis does this sometimes return $this->serialize_val($value, $name, false, false, false, false, $use); } if ($uqType == 'boolean') { if ((is_string($value) && $value == 'false') || (! $value)) { $value = 'false'; } else { $value = 'true'; } } if ($uqType == 'string' && gettype($value) == 'string') { $value = $this->expandEntities($value); } if (($uqType == 'long' || $uqType == 'unsignedLong') && gettype($value) == 'double') { $value = sprintf("%.0lf", $value); } // it's a scalar // TODO: what about null/nil values? // check type isn't a custom type extending xmlschema namespace if (!$this->getTypeDef($uqType, $ns)) { if ($use == 'literal') { if ($forceType) { $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">$value"; } else { $xml = "<$name$elementNS>$value"; } } else { $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value"; } $this->debug("in serializeType: returning: $xml"); return $xml; } $this->debug('custom type extends XML Schema or SOAP Encoding namespace (yuck)'); } else if ($ns == 'http://xml.apache.org/xml-soap') { $this->debug('in serializeType: appears to be Apache SOAP type'); if ($uqType == 'Map') { $tt_prefix = $this->getPrefixFromNamespace('http://xml.apache.org/xml-soap'); if (! $tt_prefix) { $this->debug('in serializeType: Add namespace for Apache SOAP type'); $tt_prefix = 'ns' . rand(1000, 9999); $this->namespaces[$tt_prefix] = 'http://xml.apache.org/xml-soap'; // force this to be added to usedNamespaces $tt_prefix = $this->getPrefixFromNamespace('http://xml.apache.org/xml-soap'); } $contents = ''; foreach($value as $k => $v) { $this->debug("serializing map element: key $k, value $v"); $contents .= ''; $contents .= $this->serialize_val($k,'key',false,false,false,false,$use); $contents .= $this->serialize_val($v,'value',false,false,false,false,$use); $contents .= ''; } if ($use == 'literal') { if ($forceType) { $xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\">$contents"; } else { $xml = "<$name>$contents"; } } else { $xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\"$encodingStyle>$contents"; } $this->debug("in serializeType: returning: $xml"); return $xml; } $this->debug('in serializeType: Apache SOAP type, but only support Map'); } } else { // TODO: should the type be compared to types in XSD, and the namespace // set to XSD if the type matches? $this->debug("in serializeType: No namespace for type $type"); $ns = ''; $uqType = $type; } if(!$typeDef = $this->getTypeDef($uqType, $ns)){ $this->setError("$type ($uqType) is not a supported type."); $this->debug("in serializeType: $type ($uqType) is not a supported type."); return false; } else { $this->debug("in serializeType: found typeDef"); $this->appendDebug('typeDef=' . $this->varDump($typeDef)); if (substr($uqType, -1) == '^') { $uqType = substr($uqType, 0, -1); } } $phpType = $typeDef['phpType']; $this->debug("in serializeType: uqType: $uqType, ns: $ns, phptype: $phpType, arrayType: " . (isset($typeDef['arrayType']) ? $typeDef['arrayType'] : '') ); // if php type == struct, map value to the element names if ($phpType == 'struct') { if (isset($typeDef['typeClass']) && $typeDef['typeClass'] == 'element') { $elementName = $uqType; if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) { $elementNS = " xmlns=\"$ns\""; } else { $elementNS = " xmlns=\"\""; } } else { $elementName = $name; if ($unqualified) { $elementNS = " xmlns=\"\""; } else { $elementNS = ''; } } if (is_null($value)) { if ($use == 'literal') { // TODO: depends on minOccurs $xml = "<$elementName$elementNS/>"; } else { $xml = "<$elementName$elementNS xsi:nil=\"true\" xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"/>"; } $this->debug("in serializeType: returning: $xml"); return $xml; } if (is_object($value)) { $value = get_object_vars($value); } if (is_array($value)) { $elementAttrs = $this->serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType); if ($use == 'literal') { if ($forceType) { $xml = "<$elementName$elementNS$elementAttrs xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">"; } else { $xml = "<$elementName$elementNS$elementAttrs>"; } } else { $xml = "<$elementName$elementNS$elementAttrs xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>"; } $xml .= $this->serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use, $encodingStyle); $xml .= ""; } else { $this->debug("in serializeType: phpType is struct, but value is not an array"); $this->setError("phpType is struct, but value is not an array: see debug output for details"); $xml = ''; } } elseif ($phpType == 'array') { if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) { $elementNS = " xmlns=\"$ns\""; } else { if ($unqualified) { $elementNS = " xmlns=\"\""; } else { $elementNS = ''; } } if (is_null($value)) { if ($use == 'literal') { // TODO: depends on minOccurs $xml = "<$name$elementNS/>"; } else { $xml = "<$name$elementNS xsi:nil=\"true\" xsi:type=\"" . $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') . ":Array\" " . $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') . ':arrayType="' . $this->getPrefixFromNamespace($this->getPrefix($typeDef['arrayType'])) . ':' . $this->getLocalPart($typeDef['arrayType'])."[0]\"/>"; } $this->debug("in serializeType: returning: $xml"); return $xml; } if (isset($typeDef['multidimensional'])) { $nv = array(); foreach($value as $v) { $cols = ',' . sizeof($v); $nv = array_merge($nv, $v); } $value = $nv; } else { $cols = ''; } if (is_array($value) && sizeof($value) >= 1) { $rows = sizeof($value); $contents = ''; foreach($value as $k => $v) { $this->debug("serializing array element: $k, $v of type: $typeDef[arrayType]"); //if (strpos($typeDef['arrayType'], ':') ) { if (!in_array($typeDef['arrayType'],$this->typemap['http://www.w3.org/2001/XMLSchema'])) { $contents .= $this->serializeType('item', $typeDef['arrayType'], $v, $use); } else { $contents .= $this->serialize_val($v, 'item', $typeDef['arrayType'], null, $this->XMLSchemaVersion, false, $use); } } } else { $rows = 0; $contents = null; } // TODO: for now, an empty value will be serialized as a zero element // array. Revisit this when coding the handling of null/nil values. if ($use == 'literal') { $xml = "<$name$elementNS>" .$contents .""; } else { $xml = "<$name$elementNS xsi:type=\"".$this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/').':Array" '. $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') .':arrayType="' .$this->getPrefixFromNamespace($this->getPrefix($typeDef['arrayType'])) .":".$this->getLocalPart($typeDef['arrayType'])."[$rows$cols]\">" .$contents .""; } } elseif ($phpType == 'scalar') { if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) { $elementNS = " xmlns=\"$ns\""; } else { if ($unqualified) { $elementNS = " xmlns=\"\""; } else { $elementNS = ''; } } if ($use == 'literal') { if ($forceType) { $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">$value"; } else { $xml = "<$name$elementNS>$value"; } } else { $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value"; } } $this->debug("in serializeType: returning: $xml"); return $xml; } /** * serializes the attributes for a complexType * * @param array $typeDef our internal representation of an XML schema type (or element) * @param mixed $value a native PHP value (parameter value) * @param string $ns the namespace of the type * @param string $uqType the local part of the type * @return string value serialized as an XML string * @access private */ function serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType) { $xml = ''; if (isset($typeDef['attrs']) && is_array($typeDef['attrs'])) { $this->debug("serialize attributes for XML Schema type $ns:$uqType"); if (is_array($value)) { $xvalue = $value; } elseif (is_object($value)) { $xvalue = get_object_vars($value); } else { $this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType"); $xvalue = array(); } foreach ($typeDef['attrs'] as $aName => $attrs) { if (isset($xvalue['!' . $aName])) { $xname = '!' . $aName; $this->debug("value provided for attribute $aName with key $xname"); } elseif (isset($xvalue[$aName])) { $xname = $aName; $this->debug("value provided for attribute $aName with key $xname"); } elseif (isset($attrs['default'])) { $xname = '!' . $aName; $xvalue[$xname] = $attrs['default']; $this->debug('use default value of ' . $xvalue[$aName] . ' for attribute ' . $aName); } else { $xname = ''; $this->debug("no value provided for attribute $aName"); } if ($xname) { $xml .= " $aName=\"" . $this->expandEntities($xvalue[$xname]) . "\""; } } } else { $this->debug("no attributes to serialize for XML Schema type $ns:$uqType"); } if (isset($typeDef['extensionBase'])) { $ns = $this->getPrefix($typeDef['extensionBase']); $uqType = $this->getLocalPart($typeDef['extensionBase']); if ($this->getNamespaceFromPrefix($ns)) { $ns = $this->getNamespaceFromPrefix($ns); } if ($typeDef = $this->getTypeDef($uqType, $ns)) { $this->debug("serialize attributes for extension base $ns:$uqType"); $xml .= $this->serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType); } else { $this->debug("extension base $ns:$uqType is not a supported type"); } } return $xml; } /** * serializes the elements for a complexType * * @param array $typeDef our internal representation of an XML schema type (or element) * @param mixed $value a native PHP value (parameter value) * @param string $ns the namespace of the type * @param string $uqType the local part of the type * @param string $use use for part (encoded|literal) * @param string $encodingStyle SOAP encoding style for the value (if different than the enclosing style) * @return string value serialized as an XML string * @access private */ function serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use='encoded', $encodingStyle=false) { $xml = ''; if (isset($typeDef['elements']) && is_array($typeDef['elements'])) { $this->debug("in serializeComplexTypeElements, serialize elements for XML Schema type $ns:$uqType"); if (is_array($value)) { $xvalue = $value; } elseif (is_object($value)) { $xvalue = get_object_vars($value); } else { $this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType"); $xvalue = array(); } // toggle whether all elements are present - ideally should validate against schema if (count($typeDef['elements']) != count($xvalue)){ $optionals = true; } foreach ($typeDef['elements'] as $eName => $attrs) { if (!isset($xvalue[$eName])) { if (isset($attrs['default'])) { $xvalue[$eName] = $attrs['default']; $this->debug('use default value of ' . $xvalue[$eName] . ' for element ' . $eName); } } // if user took advantage of a minOccurs=0, then only serialize named parameters if (isset($optionals) && (!isset($xvalue[$eName])) && ( (!isset($attrs['nillable'])) || $attrs['nillable'] != 'true') ){ if (isset($attrs['minOccurs']) && $attrs['minOccurs'] <> '0') { $this->debug("apparent error: no value provided for element $eName with minOccurs=" . $attrs['minOccurs']); } // do nothing $this->debug("no value provided for complexType element $eName and element is not nillable, so serialize nothing"); } else { // get value if (isset($xvalue[$eName])) { $v = $xvalue[$eName]; } else { $v = null; } if (isset($attrs['form'])) { $unqualified = ($attrs['form'] == 'unqualified'); } else { $unqualified = false; } if (isset($attrs['maxOccurs']) && ($attrs['maxOccurs'] == 'unbounded' || $attrs['maxOccurs'] > 1) && isset($v) && is_array($v) && $this->isArraySimpleOrStruct($v) == 'arraySimple') { $vv = $v; foreach ($vv as $k => $v) { if (isset($attrs['type']) || isset($attrs['ref'])) { // serialize schema-defined type $xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified); } else { // serialize generic type (can this ever really happen?) $this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use"); $xml .= $this->serialize_val($v, $eName, false, false, false, false, $use); } } } else { if (isset($attrs['type']) || isset($attrs['ref'])) { // serialize schema-defined type $xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified); } else { // serialize generic type (can this ever really happen?) $this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use"); $xml .= $this->serialize_val($v, $eName, false, false, false, false, $use); } } } } } else { $this->debug("no elements to serialize for XML Schema type $ns:$uqType"); } if (isset($typeDef['extensionBase'])) { $ns = $this->getPrefix($typeDef['extensionBase']); $uqType = $this->getLocalPart($typeDef['extensionBase']); if ($this->getNamespaceFromPrefix($ns)) { $ns = $this->getNamespaceFromPrefix($ns); } if ($typeDef = $this->getTypeDef($uqType, $ns)) { $this->debug("serialize elements for extension base $ns:$uqType"); $xml .= $this->serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use, $encodingStyle); } else { $this->debug("extension base $ns:$uqType is not a supported type"); } } return $xml; } /** * adds an XML Schema complex type to the WSDL types * * @param string $name * @param string $typeClass (complexType|simpleType|attribute) * @param string $phpType currently supported are array and struct (php assoc array) * @param string $compositor (all|sequence|choice) * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array) * @param array $elements e.g. array ( name => array(name=>'',type=>'') ) * @param array $attrs e.g. array(array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'xsd:string[]')) * @param string $arrayType as namespace:name (xsd:string) * @see nusoap_xmlschema * @access public */ function addComplexType($name,$typeClass='complexType',$phpType='array',$compositor='',$restrictionBase='',$elements=array(),$attrs=array(),$arrayType='') { if (count($elements) > 0) { $eElements = array(); foreach($elements as $n => $e){ // expand each element $ee = array(); foreach ($e as $k => $v) { $k = strpos($k,':') ? $this->expandQname($k) : $k; $v = strpos($v,':') ? $this->expandQname($v) : $v; $ee[$k] = $v; } $eElements[$n] = $ee; } $elements = $eElements; } if (count($attrs) > 0) { foreach($attrs as $n => $a){ // expand each attribute foreach ($a as $k => $v) { $k = strpos($k,':') ? $this->expandQname($k) : $k; $v = strpos($v,':') ? $this->expandQname($v) : $v; $aa[$k] = $v; } $eAttrs[$n] = $aa; } $attrs = $eAttrs; } $restrictionBase = strpos($restrictionBase,':') ? $this->expandQname($restrictionBase) : $restrictionBase; $arrayType = strpos($arrayType,':') ? $this->expandQname($arrayType) : $arrayType; $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns']; $this->schemas[$typens][0]->addComplexType($name,$typeClass,$phpType,$compositor,$restrictionBase,$elements,$attrs,$arrayType); } /** * adds an XML Schema simple type to the WSDL types * * @param string $name * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array) * @param string $typeClass (should always be simpleType) * @param string $phpType (should always be scalar) * @param array $enumeration array of values * @see nusoap_xmlschema * @access public */ function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) { $restrictionBase = strpos($restrictionBase,':') ? $this->expandQname($restrictionBase) : $restrictionBase; $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns']; $this->schemas[$typens][0]->addSimpleType($name, $restrictionBase, $typeClass, $phpType, $enumeration); } /** * adds an element to the WSDL types * * @param array $attrs attributes that must include name and type * @see nusoap_xmlschema * @access public */ function addElement($attrs) { $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns']; $this->schemas[$typens][0]->addElement($attrs); } /** * register an operation with the server * * @param string $name operation (method) name * @param array $in assoc array of input values: key = param name, value = param type * @param array $out assoc array of output values: key = param name, value = param type * @param string $namespace optional The namespace for the operation * @param string $soapaction optional The soapaction for the operation * @param string $style (rpc|document) optional The style for the operation Note: when 'document' is specified, parameter and return wrappers are created for you automatically * @param string $use (encoded|literal) optional The use for the parameters (cannot mix right now) * @param string $documentation optional The description to include in the WSDL * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded) * @access public */ function addOperation($name, $in = false, $out = false, $namespace = false, $soapaction = false, $style = 'rpc', $use = 'encoded', $documentation = '', $encodingStyle = ''){ if ($use == 'encoded' && $encodingStyle == '') { $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; } if ($style == 'document') { $elements = array(); foreach ($in as $n => $t) { $elements[$n] = array('name' => $n, 'type' => $t); } $this->addComplexType($name . 'RequestType', 'complexType', 'struct', 'all', '', $elements); $this->addElement(array('name' => $name, 'type' => $name . 'RequestType')); $in = array('parameters' => 'tns:' . $name . '^'); $elements = array(); foreach ($out as $n => $t) { $elements[$n] = array('name' => $n, 'type' => $t); } $this->addComplexType($name . 'ResponseType', 'complexType', 'struct', 'all', '', $elements); $this->addElement(array('name' => $name . 'Response', 'type' => $name . 'ResponseType', 'form' => 'qualified')); $out = array('parameters' => 'tns:' . $name . 'Response' . '^'); } // get binding $this->bindings[ $this->serviceName . 'Binding' ]['operations'][$name] = array( 'name' => $name, 'binding' => $this->serviceName . 'Binding', 'endpoint' => $this->endpoint, 'soapAction' => $soapaction, 'style' => $style, 'input' => array( 'use' => $use, 'namespace' => $namespace, 'encodingStyle' => $encodingStyle, 'message' => $name . 'Request', 'parts' => $in), 'output' => array( 'use' => $use, 'namespace' => $namespace, 'encodingStyle' => $encodingStyle, 'message' => $name . 'Response', 'parts' => $out), 'namespace' => $namespace, 'transport' => 'http://schemas.xmlsoap.org/soap/http', 'documentation' => $documentation); // add portTypes // add messages if($in) { foreach($in as $pName => $pType) { if(strpos($pType,':')) { $pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType); } $this->messages[$name.'Request'][$pName] = $pType; } } else { $this->messages[$name.'Request']= '0'; } if($out) { foreach($out as $pName => $pType) { if(strpos($pType,':')) { $pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType); } $this->messages[$name.'Response'][$pName] = $pType; } } else { $this->messages[$name.'Response']= '0'; } return true; } } ?> * @author Scott Nichol * @version $Id: nusoap.php,v 1.114 2007/11/06 15:17:46 snichol Exp $ * @access public */ class nusoap_parser extends nusoap_base { var $xml = ''; var $xml_encoding = ''; var $method = ''; var $root_struct = ''; var $root_struct_name = ''; var $root_struct_namespace = ''; var $root_header = ''; var $document = ''; // incoming SOAP body (text) // determines where in the message we are (envelope,header,body,method) var $status = ''; var $position = 0; var $depth = 0; var $default_namespace = ''; var $namespaces = array(); var $message = array(); var $parent = ''; var $fault = false; var $fault_code = ''; var $fault_str = ''; var $fault_detail = ''; var $depth_array = array(); var $debug_flag = true; var $soapresponse = NULL; // parsed SOAP Body var $soapheader = NULL; // parsed SOAP Header var $responseHeaders = ''; // incoming SOAP headers (text) var $body_position = 0; // for multiref parsing: // array of id => pos var $ids = array(); // array of id => hrefs => pos var $multirefs = array(); // toggle for auto-decoding element content var $decode_utf8 = true; /** * constructor that actually does the parsing * * @param string $xml SOAP message * @param string $encoding character encoding scheme of message * @param string $method method for which XML is parsed (unused?) * @param string $decode_utf8 whether to decode UTF-8 to ISO-8859-1 * @access public */ function nusoap_parser($xml,$encoding='UTF-8',$method='',$decode_utf8=true){ parent::nusoap_base(); $this->xml = $xml; $this->xml_encoding = $encoding; $this->method = $method; $this->decode_utf8 = $decode_utf8; // Check whether content has been read. if(!empty($xml)){ // Check XML encoding $pos_xml = strpos($xml, '', $pos_xml + 2) - $pos_xml + 1); if (preg_match("/encoding=[\"']([^\"']*)[\"']/", $xml_decl, $res)) { $xml_encoding = $res[1]; if (strtoupper($xml_encoding) != $encoding) { $err = "Charset from HTTP Content-Type '" . $encoding . "' does not match encoding from XML declaration '" . $xml_encoding . "'"; $this->debug($err); if ($encoding != 'ISO-8859-1' || strtoupper($xml_encoding) != 'UTF-8') { $this->setError($err); return; } // when HTTP says ISO-8859-1 (the default) and XML says UTF-8 (the typical), assume the other endpoint is just sloppy and proceed } else { $this->debug('Charset from HTTP Content-Type matches encoding from XML declaration'); } } else { $this->debug('No encoding specified in XML declaration'); } } else { $this->debug('No XML declaration'); } $this->debug('Entering nusoap_parser(), length='.strlen($xml).', encoding='.$encoding); // Create an XML parser - why not xml_parser_create_ns? $this->parser = xml_parser_create($this->xml_encoding); // Set the options for parsing the XML data. //xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1); xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, $this->xml_encoding); // Set the object for the parser. xml_set_object($this->parser, $this); // Set the element handlers for the parser. xml_set_element_handler($this->parser, 'start_element','end_element'); xml_set_character_data_handler($this->parser,'character_data'); // Parse the XML file. if(!xml_parse($this->parser,$xml,true)){ // Display an error message. $err = sprintf('XML error parsing SOAP payload on line %d: %s', xml_get_current_line_number($this->parser), xml_error_string(xml_get_error_code($this->parser))); $this->debug($err); $this->debug("XML payload:\n" . $xml); $this->setError($err); } else { $this->debug('parsed successfully, found root struct: '.$this->root_struct.' of name '.$this->root_struct_name); // get final value $this->soapresponse = $this->message[$this->root_struct]['result']; // get header value if($this->root_header != '' && isset($this->message[$this->root_header]['result'])){ $this->soapheader = $this->message[$this->root_header]['result']; } // resolve hrefs/ids if(sizeof($this->multirefs) > 0){ foreach($this->multirefs as $id => $hrefs){ $this->debug('resolving multirefs for id: '.$id); $idVal = $this->buildVal($this->ids[$id]); if (is_array($idVal) && isset($idVal['!id'])) { unset($idVal['!id']); } foreach($hrefs as $refPos => $ref){ $this->debug('resolving href at pos '.$refPos); $this->multirefs[$id][$refPos] = $idVal; } } } } xml_parser_free($this->parser); } else { $this->debug('xml was empty, didn\'t parse!'); $this->setError('xml was empty, didn\'t parse!'); } } /** * start-element handler * * @param resource $parser XML parser object * @param string $name element name * @param array $attrs associative array of attributes * @access private */ function start_element($parser, $name, $attrs) { // position in a total number of elements, starting from 0 // update class level pos $pos = $this->position++; // and set mine $this->message[$pos] = array('pos' => $pos,'children'=>'','cdata'=>''); // depth = how many levels removed from root? // set mine as current global depth and increment global depth value $this->message[$pos]['depth'] = $this->depth++; // else add self as child to whoever the current parent is if($pos != 0){ $this->message[$this->parent]['children'] .= '|'.$pos; } // set my parent $this->message[$pos]['parent'] = $this->parent; // set self as current parent $this->parent = $pos; // set self as current value for this depth $this->depth_array[$this->depth] = $pos; // get element prefix if(strpos($name,':')){ // get ns prefix $prefix = substr($name,0,strpos($name,':')); // get unqualified name $name = substr(strstr($name,':'),1); } // set status if($name == 'Envelope'){ $this->status = 'envelope'; } elseif($name == 'Header' && $this->status = 'envelope'){ $this->root_header = $pos; $this->status = 'header'; } elseif($name == 'Body' && $this->status = 'envelope'){ $this->status = 'body'; $this->body_position = $pos; // set method } elseif($this->status == 'body' && $pos == ($this->body_position+1)){ $this->status = 'method'; $this->root_struct_name = $name; $this->root_struct = $pos; $this->message[$pos]['type'] = 'struct'; $this->debug("found root struct $this->root_struct_name, pos $this->root_struct"); } // set my status $this->message[$pos]['status'] = $this->status; // set name $this->message[$pos]['name'] = htmlspecialchars($name); // set attrs $this->message[$pos]['attrs'] = $attrs; // loop through atts, logging ns and type declarations $attstr = ''; foreach($attrs as $key => $value){ $key_prefix = $this->getPrefix($key); $key_localpart = $this->getLocalPart($key); // if ns declarations, add to class level array of valid namespaces if($key_prefix == 'xmlns'){ if(ereg('^http://www.w3.org/[0-9]{4}/XMLSchema$',$value)){ $this->XMLSchemaVersion = $value; $this->namespaces['xsd'] = $this->XMLSchemaVersion; $this->namespaces['xsi'] = $this->XMLSchemaVersion.'-instance'; } $this->namespaces[$key_localpart] = $value; // set method namespace if($name == $this->root_struct_name){ $this->methodNamespace = $value; } // if it's a type declaration, set type } elseif($key_localpart == 'type'){ if (isset($this->message[$pos]['type']) && $this->message[$pos]['type'] == 'array') { // do nothing: already processed arrayType } else { $value_prefix = $this->getPrefix($value); $value_localpart = $this->getLocalPart($value); $this->message[$pos]['type'] = $value_localpart; $this->message[$pos]['typePrefix'] = $value_prefix; if(isset($this->namespaces[$value_prefix])){ $this->message[$pos]['type_namespace'] = $this->namespaces[$value_prefix]; } else if(isset($attrs['xmlns:'.$value_prefix])) { $this->message[$pos]['type_namespace'] = $attrs['xmlns:'.$value_prefix]; } // should do something here with the namespace of specified type? } } elseif($key_localpart == 'arrayType'){ $this->message[$pos]['type'] = 'array'; /* do arrayType ereg here [1] arrayTypeValue ::= atype asize [2] atype ::= QName rank* [3] rank ::= '[' (',')* ']' [4] asize ::= '[' length~ ']' [5] length ::= nextDimension* Digit+ [6] nextDimension ::= Digit+ ',' */ $expr = '([A-Za-z0-9_]+):([A-Za-z]+[A-Za-z0-9_]+)\[([0-9]+),?([0-9]*)\]'; if(ereg($expr,$value,$regs)){ $this->message[$pos]['typePrefix'] = $regs[1]; $this->message[$pos]['arrayTypePrefix'] = $regs[1]; if (isset($this->namespaces[$regs[1]])) { $this->message[$pos]['arrayTypeNamespace'] = $this->namespaces[$regs[1]]; } else if (isset($attrs['xmlns:'.$regs[1]])) { $this->message[$pos]['arrayTypeNamespace'] = $attrs['xmlns:'.$regs[1]]; } $this->message[$pos]['arrayType'] = $regs[2]; $this->message[$pos]['arraySize'] = $regs[3]; $this->message[$pos]['arrayCols'] = $regs[4]; } // specifies nil value (or not) } elseif ($key_localpart == 'nil'){ $this->message[$pos]['nil'] = ($value == 'true' || $value == '1'); // some other attribute } elseif ($key != 'href' && $key != 'xmlns' && $key_localpart != 'encodingStyle' && $key_localpart != 'root') { $this->message[$pos]['xattrs']['!' . $key] = $value; } if ($key == 'xmlns') { $this->default_namespace = $value; } // log id if($key == 'id'){ $this->ids[$value] = $pos; } // root if($key_localpart == 'root' && $value == 1){ $this->status = 'method'; $this->root_struct_name = $name; $this->root_struct = $pos; $this->debug("found root struct $this->root_struct_name, pos $pos"); } // for doclit $attstr .= " $key=\"$value\""; } // get namespace - must be done after namespace atts are processed if(isset($prefix)){ $this->message[$pos]['namespace'] = $this->namespaces[$prefix]; $this->default_namespace = $this->namespaces[$prefix]; } else { $this->message[$pos]['namespace'] = $this->default_namespace; } if($this->status == 'header'){ if ($this->root_header != $pos) { $this->responseHeaders .= "<" . (isset($prefix) ? $prefix . ':' : '') . "$name$attstr>"; } } elseif($this->root_struct_name != ''){ $this->document .= "<" . (isset($prefix) ? $prefix . ':' : '') . "$name$attstr>"; } } /** * end-element handler * * @param resource $parser XML parser object * @param string $name element name * @access private */ function end_element($parser, $name) { // position of current element is equal to the last value left in depth_array for my depth $pos = $this->depth_array[$this->depth--]; // get element prefix if(strpos($name,':')){ // get ns prefix $prefix = substr($name,0,strpos($name,':')); // get unqualified name $name = substr(strstr($name,':'),1); } // build to native type if(isset($this->body_position) && $pos > $this->body_position){ // deal w/ multirefs if(isset($this->message[$pos]['attrs']['href'])){ // get id $id = substr($this->message[$pos]['attrs']['href'],1); // add placeholder to href array $this->multirefs[$id][$pos] = 'placeholder'; // add set a reference to it as the result value $this->message[$pos]['result'] =& $this->multirefs[$id][$pos]; // build complexType values } elseif($this->message[$pos]['children'] != ''){ // if result has already been generated (struct/array) if(!isset($this->message[$pos]['result'])){ $this->message[$pos]['result'] = $this->buildVal($pos); } // build complexType values of attributes and possibly simpleContent } elseif (isset($this->message[$pos]['xattrs'])) { if (isset($this->message[$pos]['nil']) && $this->message[$pos]['nil']) { $this->message[$pos]['xattrs']['!'] = null; } elseif (isset($this->message[$pos]['cdata']) && trim($this->message[$pos]['cdata']) != '') { if (isset($this->message[$pos]['type'])) { $this->message[$pos]['xattrs']['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : ''); } else { $parent = $this->message[$pos]['parent']; if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) { $this->message[$pos]['xattrs']['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : ''); } else { $this->message[$pos]['xattrs']['!'] = $this->message[$pos]['cdata']; } } } $this->message[$pos]['result'] = $this->message[$pos]['xattrs']; // set value of simpleType (or nil complexType) } else { //$this->debug('adding data for scalar value '.$this->message[$pos]['name'].' of value '.$this->message[$pos]['cdata']); if (isset($this->message[$pos]['nil']) && $this->message[$pos]['nil']) { $this->message[$pos]['xattrs']['!'] = null; } elseif (isset($this->message[$pos]['type'])) { $this->message[$pos]['result'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : ''); } else { $parent = $this->message[$pos]['parent']; if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) { $this->message[$pos]['result'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : ''); } else { $this->message[$pos]['result'] = $this->message[$pos]['cdata']; } } /* add value to parent's result, if parent is struct/array $parent = $this->message[$pos]['parent']; if($this->message[$parent]['type'] != 'map'){ if(strtolower($this->message[$parent]['type']) == 'array'){ $this->message[$parent]['result'][] = $this->message[$pos]['result']; } else { $this->message[$parent]['result'][$this->message[$pos]['name']] = $this->message[$pos]['result']; } } */ } } // for doclit if($this->status == 'header'){ if ($this->root_header != $pos) { $this->responseHeaders .= ""; } } elseif($pos >= $this->root_struct){ $this->document .= ""; } // switch status if($pos == $this->root_struct){ $this->status = 'body'; $this->root_struct_namespace = $this->message[$pos]['namespace']; } elseif($name == 'Body'){ $this->status = 'envelope'; } elseif($name == 'Header'){ $this->status = 'envelope'; } elseif($name == 'Envelope'){ // } // set parent back to my parent $this->parent = $this->message[$pos]['parent']; } /** * element content handler * * @param resource $parser XML parser object * @param string $data element content * @access private */ function character_data($parser, $data){ $pos = $this->depth_array[$this->depth]; if ($this->xml_encoding=='UTF-8'){ // TODO: add an option to disable this for folks who want // raw UTF-8 that, e.g., might not map to iso-8859-1 // TODO: this can also be handled with xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "ISO-8859-1"); if($this->decode_utf8){ $data = utf8_decode($data); } } $this->message[$pos]['cdata'] .= $data; // for doclit if($this->status == 'header'){ $this->responseHeaders .= $data; } else { $this->document .= $data; } } /** * get the parsed message (SOAP Body) * * @return mixed * @access public * @deprecated use get_soapbody instead */ function get_response(){ return $this->soapresponse; } /** * get the parsed SOAP Body (NULL if there was none) * * @return mixed * @access public */ function get_soapbody(){ return $this->soapresponse; } /** * get the parsed SOAP Header (NULL if there was none) * * @return mixed * @access public */ function get_soapheader(){ return $this->soapheader; } /** * get the unparsed SOAP Header * * @return string XML or empty if no Header * @access public */ function getHeaders(){ return $this->responseHeaders; } /** * decodes simple types into PHP variables * * @param string $value value to decode * @param string $type XML type to decode * @param string $typens XML type namespace to decode * @return mixed PHP value * @access private */ function decodeSimple($value, $type, $typens) { // TODO: use the namespace! if ((!isset($type)) || $type == 'string' || $type == 'long' || $type == 'unsignedLong') { return (string) $value; } if ($type == 'int' || $type == 'integer' || $type == 'short' || $type == 'byte') { return (int) $value; } if ($type == 'float' || $type == 'double' || $type == 'decimal') { return (double) $value; } if ($type == 'boolean') { if (strtolower($value) == 'false' || strtolower($value) == 'f') { return false; } return (boolean) $value; } if ($type == 'base64' || $type == 'base64Binary') { $this->debug('Decode base64 value'); return base64_decode($value); } // obscure numeric types if ($type == 'nonPositiveInteger' || $type == 'negativeInteger' || $type == 'nonNegativeInteger' || $type == 'positiveInteger' || $type == 'unsignedInt' || $type == 'unsignedShort' || $type == 'unsignedByte') { return (int) $value; } // bogus: parser treats array with no elements as a simple type if ($type == 'array') { return array(); } // everything else return (string) $value; } /** * builds response structures for compound values (arrays/structs) * and scalars * * @param integer $pos position in node tree * @return mixed PHP value * @access private */ function buildVal($pos){ if(!isset($this->message[$pos]['type'])){ $this->message[$pos]['type'] = ''; } $this->debug('in buildVal() for '.$this->message[$pos]['name']."(pos $pos) of type ".$this->message[$pos]['type']); // if there are children... if($this->message[$pos]['children'] != ''){ $this->debug('in buildVal, there are children'); $children = explode('|',$this->message[$pos]['children']); array_shift($children); // knock off empty // md array if(isset($this->message[$pos]['arrayCols']) && $this->message[$pos]['arrayCols'] != ''){ $r=0; // rowcount $c=0; // colcount foreach($children as $child_pos){ $this->debug("in buildVal, got an MD array element: $r, $c"); $params[$r][] = $this->message[$child_pos]['result']; $c++; if($c == $this->message[$pos]['arrayCols']){ $c = 0; $r++; } } // array } elseif($this->message[$pos]['type'] == 'array' || $this->message[$pos]['type'] == 'Array'){ $this->debug('in buildVal, adding array '.$this->message[$pos]['name']); foreach($children as $child_pos){ $params[] = &$this->message[$child_pos]['result']; } // apache Map type: java hashtable } elseif($this->message[$pos]['type'] == 'Map' && $this->message[$pos]['type_namespace'] == 'http://xml.apache.org/xml-soap'){ $this->debug('in buildVal, Java Map '.$this->message[$pos]['name']); foreach($children as $child_pos){ $kv = explode("|",$this->message[$child_pos]['children']); $params[$this->message[$kv[1]]['result']] = &$this->message[$kv[2]]['result']; } // generic compound type //} elseif($this->message[$pos]['type'] == 'SOAPStruct' || $this->message[$pos]['type'] == 'struct') { } else { // Apache Vector type: treat as an array $this->debug('in buildVal, adding Java Vector or generic compound type '.$this->message[$pos]['name']); if ($this->message[$pos]['type'] == 'Vector' && $this->message[$pos]['type_namespace'] == 'http://xml.apache.org/xml-soap') { $notstruct = 1; } else { $notstruct = 0; } // foreach($children as $child_pos){ if($notstruct){ $params[] = &$this->message[$child_pos]['result']; } else { if (isset($params[$this->message[$child_pos]['name']])) { // de-serialize repeated element name into an array if ((!is_array($params[$this->message[$child_pos]['name']])) || (!isset($params[$this->message[$child_pos]['name']][0]))) { $params[$this->message[$child_pos]['name']] = array($params[$this->message[$child_pos]['name']]); } $params[$this->message[$child_pos]['name']][] = &$this->message[$child_pos]['result']; } else { $params[$this->message[$child_pos]['name']] = &$this->message[$child_pos]['result']; } } } } if (isset($this->message[$pos]['xattrs'])) { $this->debug('in buildVal, handling attributes'); foreach ($this->message[$pos]['xattrs'] as $n => $v) { $params[$n] = $v; } } // handle simpleContent if (isset($this->message[$pos]['cdata']) && trim($this->message[$pos]['cdata']) != '') { $this->debug('in buildVal, handling simpleContent'); if (isset($this->message[$pos]['type'])) { $params['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : ''); } else { $parent = $this->message[$pos]['parent']; if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) { $params['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : ''); } else { $params['!'] = $this->message[$pos]['cdata']; } } } $ret = is_array($params) ? $params : array(); $this->debug('in buildVal, return:'); $this->appendDebug($this->varDump($ret)); return $ret; } else { $this->debug('in buildVal, no children, building scalar'); $cdata = isset($this->message[$pos]['cdata']) ? $this->message[$pos]['cdata'] : ''; if (isset($this->message[$pos]['type'])) { $ret = $this->decodeSimple($cdata, $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : ''); $this->debug("in buildVal, return: $ret"); return $ret; } $parent = $this->message[$pos]['parent']; if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) { $ret = $this->decodeSimple($cdata, $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : ''); $this->debug("in buildVal, return: $ret"); return $ret; } $ret = $this->message[$pos]['cdata']; $this->debug("in buildVal, return: $ret"); return $ret; } } } /** * Backward compatibility */ class soap_parser extends nusoap_parser { } ?>call( string methodname [ ,array parameters] ); * * // bye bye client * unset($soapclient); * * @author Dietrich Ayala * @author Scott Nichol * @version $Id: nusoap.php,v 1.114 2007/11/06 15:17:46 snichol Exp $ * @access public */ class nusoap_client extends nusoap_base { var $username = ''; // Username for HTTP authentication var $password = ''; // Password for HTTP authentication var $authtype = ''; // Type of HTTP authentication var $certRequest = array(); // Certificate for HTTP SSL authentication var $requestHeaders = false; // SOAP headers in request (text) var $responseHeaders = ''; // SOAP headers from response (incomplete namespace resolution) (text) var $responseHeader = NULL; // SOAP Header from response (parsed) var $document = ''; // SOAP body response portion (incomplete namespace resolution) (text) var $endpoint; var $forceEndpoint = ''; // overrides WSDL endpoint var $proxyhost = ''; var $proxyport = ''; var $proxyusername = ''; var $proxypassword = ''; var $xml_encoding = ''; // character set encoding of incoming (response) messages var $http_encoding = false; var $timeout = 0; // HTTP connection timeout var $response_timeout = 30; // HTTP response timeout var $endpointType = ''; // soap|wsdl, empty for WSDL initialization error var $persistentConnection = false; var $defaultRpcParams = false; // This is no longer used var $request = ''; // HTTP request var $response = ''; // HTTP response var $responseData = ''; // SOAP payload of response var $cookies = array(); // Cookies from response or for request var $decode_utf8 = true; // toggles whether the parser decodes element content w/ utf8_decode() var $operations = array(); // WSDL operations, empty for WSDL initialization error var $curl_options = array(); // User-specified cURL options var $bindingType = ''; // WSDL operation binding type var $use_curl = false; // whether to always try to use cURL /* * fault related variables */ /** * @var fault * @access public */ var $fault; /** * @var faultcode * @access public */ var $faultcode; /** * @var faultstring * @access public */ var $faultstring; /** * @var faultdetail * @access public */ var $faultdetail; /** * constructor * * @param mixed $endpoint SOAP server or WSDL URL (string), or wsdl instance (object) * @param bool $wsdl optional, set to true if using WSDL * @param int $portName optional portName in WSDL document * @param string $proxyhost * @param string $proxyport * @param string $proxyusername * @param string $proxypassword * @param integer $timeout set the connection timeout * @param integer $response_timeout set the response timeout * @access public */ function nusoap_client($endpoint,$wsdl = false,$proxyhost = false,$proxyport = false,$proxyusername = false, $proxypassword = false, $timeout = 0, $response_timeout = 30){ parent::nusoap_base(); $this->endpoint = $endpoint; $this->proxyhost = $proxyhost; $this->proxyport = $proxyport; $this->proxyusername = $proxyusername; $this->proxypassword = $proxypassword; $this->timeout = $timeout; $this->response_timeout = $response_timeout; $this->debug("ctor wsdl=$wsdl timeout=$timeout response_timeout=$response_timeout"); $this->appendDebug('endpoint=' . $this->varDump($endpoint)); // make values if($wsdl){ if (is_object($endpoint) && (get_class($endpoint) == 'wsdl')) { $this->wsdl = $endpoint; $this->endpoint = $this->wsdl->wsdl; $this->wsdlFile = $this->endpoint; $this->debug('existing wsdl instance created from ' . $this->endpoint); $this->checkWSDL(); } else { $this->wsdlFile = $this->endpoint; $this->wsdl = null; $this->debug('will use lazy evaluation of wsdl from ' . $this->endpoint); } $this->endpointType = 'wsdl'; } else { $this->debug("instantiate SOAP with endpoint at $endpoint"); $this->endpointType = 'soap'; } } /** * calls method, returns PHP native type * * @param string $operation SOAP server URL or path * @param mixed $params An array, associative or simple, of the parameters * for the method call, or a string that is the XML * for the call. For rpc style, this call will * wrap the XML in a tag named after the method, as * well as the SOAP Envelope and Body. For document * style, this will only wrap with the Envelope and Body. * IMPORTANT: when using an array with document style, * in which case there * is really one parameter, the root of the fragment * used in the call, which encloses what programmers * normally think of parameters. A parameter array * *must* include the wrapper. * @param string $namespace optional method namespace (WSDL can override) * @param string $soapAction optional SOAPAction value (WSDL can override) * @param mixed $headers optional string of XML with SOAP header content, or array of soapval objects for SOAP headers, or associative array * @param boolean $rpcParams optional (no longer used) * @param string $style optional (rpc|document) the style to use when serializing parameters (WSDL can override) * @param string $use optional (encoded|literal) the use when serializing parameters (WSDL can override) * @return mixed response from SOAP call * @access public */ function call($operation,$params=array(),$namespace='http://tempuri.org',$soapAction='',$headers=false,$rpcParams=null,$style='rpc',$use='encoded'){ $this->operation = $operation; $this->fault = false; $this->setError(''); $this->request = ''; $this->response = ''; $this->responseData = ''; $this->faultstring = ''; $this->faultcode = ''; $this->opData = array(); $this->debug("call: operation=$operation, namespace=$namespace, soapAction=$soapAction, rpcParams=$rpcParams, style=$style, use=$use, endpointType=$this->endpointType"); $this->appendDebug('params=' . $this->varDump($params)); $this->appendDebug('headers=' . $this->varDump($headers)); if ($headers) { $this->requestHeaders = $headers; } if ($this->endpointType == 'wsdl' && is_null($this->wsdl)) { $this->loadWSDL(); if ($this->getError()) return false; } // serialize parameters if($this->endpointType == 'wsdl' && $opData = $this->getOperationData($operation)){ // use WSDL for operation $this->opData = $opData; $this->debug("found operation"); $this->appendDebug('opData=' . $this->varDump($opData)); if (isset($opData['soapAction'])) { $soapAction = $opData['soapAction']; } if (! $this->forceEndpoint) { $this->endpoint = $opData['endpoint']; } else { $this->endpoint = $this->forceEndpoint; } $namespace = isset($opData['input']['namespace']) ? $opData['input']['namespace'] : $namespace; $style = $opData['style']; $use = $opData['input']['use']; // add ns to ns array if($namespace != '' && !isset($this->wsdl->namespaces[$namespace])){ $nsPrefix = 'ns' . rand(1000, 9999); $this->wsdl->namespaces[$nsPrefix] = $namespace; } $nsPrefix = $this->wsdl->getPrefixFromNamespace($namespace); // serialize payload if (is_string($params)) { $this->debug("serializing param string for WSDL operation $operation"); $payload = $params; } elseif (is_array($params)) { $this->debug("serializing param array for WSDL operation $operation"); $payload = $this->wsdl->serializeRPCParameters($operation,'input',$params,$this->bindingType); } else { $this->debug('params must be array or string'); $this->setError('params must be array or string'); return false; } $usedNamespaces = $this->wsdl->usedNamespaces; if (isset($opData['input']['encodingStyle'])) { $encodingStyle = $opData['input']['encodingStyle']; } else { $encodingStyle = ''; } $this->appendDebug($this->wsdl->getDebug()); $this->wsdl->clearDebug(); if ($errstr = $this->wsdl->getError()) { $this->debug('got wsdl error: '.$errstr); $this->setError('wsdl error: '.$errstr); return false; } } elseif($this->endpointType == 'wsdl') { // operation not in WSDL $this->appendDebug($this->wsdl->getDebug()); $this->wsdl->clearDebug(); $this->setError( 'operation '.$operation.' not present.'); $this->debug("operation '$operation' not present."); return false; } else { // no WSDL //$this->namespaces['ns1'] = $namespace; $nsPrefix = 'ns' . rand(1000, 9999); // serialize $payload = ''; if (is_string($params)) { $this->debug("serializing param string for operation $operation"); $payload = $params; } elseif (is_array($params)) { $this->debug("serializing param array for operation $operation"); foreach($params as $k => $v){ $payload .= $this->serialize_val($v,$k,false,false,false,false,$use); } } else { $this->debug('params must be array or string'); $this->setError('params must be array or string'); return false; } $usedNamespaces = array(); if ($use == 'encoded') { $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; } else { $encodingStyle = ''; } } // wrap RPC calls with method element if ($style == 'rpc') { if ($use == 'literal') { $this->debug("wrapping RPC request with literal method element"); if ($namespace) { // http://www.ws-i.org/Profiles/BasicProfile-1.1-2004-08-24.html R2735 says rpc/literal accessor elements should not be in a namespace $payload = "<$nsPrefix:$operation xmlns:$nsPrefix=\"$namespace\">" . $payload . ""; } else { $payload = "<$operation>" . $payload . ""; } } else { $this->debug("wrapping RPC request with encoded method element"); if ($namespace) { $payload = "<$nsPrefix:$operation xmlns:$nsPrefix=\"$namespace\">" . $payload . ""; } else { $payload = "<$operation>" . $payload . ""; } } } // serialize envelope $soapmsg = $this->serializeEnvelope($payload,$this->requestHeaders,$usedNamespaces,$style,$use,$encodingStyle); $this->debug("endpoint=$this->endpoint, soapAction=$soapAction, namespace=$namespace, style=$style, use=$use, encodingStyle=$encodingStyle"); $this->debug('SOAP message length=' . strlen($soapmsg) . ' contents (max 1000 bytes)=' . substr($soapmsg, 0, 1000)); // send $return = $this->send($this->getHTTPBody($soapmsg),$soapAction,$this->timeout,$this->response_timeout); if($errstr = $this->getError()){ $this->debug('Error: '.$errstr); return false; } else { $this->return = $return; $this->debug('sent message successfully and got a(n) '.gettype($return)); $this->appendDebug('return=' . $this->varDump($return)); // fault? if(is_array($return) && isset($return['faultcode'])){ $this->debug('got fault'); $this->setError($return['faultcode'].': '.$return['faultstring']); $this->fault = true; foreach($return as $k => $v){ $this->$k = $v; $this->debug("$k = $v
    "); } return $return; } elseif ($style == 'document') { // NOTE: if the response is defined to have multiple parts (i.e. unwrapped), // we are only going to return the first part here...sorry about that return $return; } else { // array of return values if(is_array($return)){ // multiple 'out' parameters, which we return wrapped up // in the array if(sizeof($return) > 1){ return $return; } // single 'out' parameter (normally the return value) $return = array_shift($return); $this->debug('return shifted value: '); $this->appendDebug($this->varDump($return)); return $return; // nothing returned (ie, echoVoid) } else { return ""; } } } } /** * check WSDL passed as an instance or pulled from an endpoint * * @access private */ function checkWSDL() { $this->appendDebug($this->wsdl->getDebug()); $this->wsdl->clearDebug(); $this->debug('checkWSDL'); // catch errors if ($errstr = $this->wsdl->getError()) { $this->debug('got wsdl error: '.$errstr); $this->setError('wsdl error: '.$errstr); } elseif ($this->operations = $this->wsdl->getOperations('soap')) { $this->bindingType = 'soap'; $this->debug('got '.count($this->operations).' operations from wsdl '.$this->wsdlFile.' for binding type '.$this->bindingType); } elseif ($this->operations = $this->wsdl->getOperations('soap12')) { $this->bindingType = 'soap12'; $this->debug('got '.count($this->operations).' operations from wsdl '.$this->wsdlFile.' for binding type '.$this->bindingType); $this->debug('**************** WARNING: SOAP 1.2 BINDING *****************'); } else { $this->debug('getOperations returned false'); $this->setError('no operations defined in the WSDL document!'); } } /** * instantiate wsdl object and parse wsdl file * * @access public */ function loadWSDL() { $this->debug('instantiating wsdl class with doc: '.$this->wsdlFile); $this->wsdl = new wsdl('',$this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword,$this->timeout,$this->response_timeout,$this->curl_options,$this->use_curl); $this->wsdl->setCredentials($this->username, $this->password, $this->authtype, $this->certRequest); $this->wsdl->fetchWSDL($this->wsdlFile); $this->checkWSDL(); } /** * get available data pertaining to an operation * * @param string $operation operation name * @return array array of data pertaining to the operation * @access public */ function getOperationData($operation){ if ($this->endpointType == 'wsdl' && is_null($this->wsdl)) { $this->loadWSDL(); if ($this->getError()) return false; } if(isset($this->operations[$operation])){ return $this->operations[$operation]; } $this->debug("No data for operation: $operation"); } /** * send the SOAP message * * Note: if the operation has multiple return values * the return value of this method will be an array * of those values. * * @param string $msg a SOAPx4 soapmsg object * @param string $soapaction SOAPAction value * @param integer $timeout set connection timeout in seconds * @param integer $response_timeout set response timeout in seconds * @return mixed native PHP types. * @access private */ function send($msg, $soapaction = '', $timeout=0, $response_timeout=30) { $this->checkCookies(); // detect transport switch(true){ // http(s) case ereg('^http',$this->endpoint): $this->debug('transporting via HTTP'); if($this->persistentConnection == true && is_object($this->persistentConnection)){ $http =& $this->persistentConnection; } else { $http = new soap_transport_http($this->endpoint, $this->curl_options, $this->use_curl); if ($this->persistentConnection) { $http->usePersistentConnection(); } } $http->setContentType($this->getHTTPContentType(), $this->getHTTPContentTypeCharset()); $http->setSOAPAction($soapaction); if($this->proxyhost && $this->proxyport){ $http->setProxy($this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword); } if($this->authtype != '') { $http->setCredentials($this->username, $this->password, $this->authtype, array(), $this->certRequest); } if($this->http_encoding != ''){ $http->setEncoding($this->http_encoding); } $this->debug('sending message, length='.strlen($msg)); if(ereg('^http:',$this->endpoint)){ //if(strpos($this->endpoint,'http:')){ $this->responseData = $http->send($msg,$timeout,$response_timeout,$this->cookies); } elseif(ereg('^https',$this->endpoint)){ //} elseif(strpos($this->endpoint,'https:')){ //if(phpversion() == '4.3.0-dev'){ //$response = $http->send($msg,$timeout,$response_timeout); //$this->request = $http->outgoing_payload; //$this->response = $http->incoming_payload; //} else $this->responseData = $http->sendHTTPS($msg,$timeout,$response_timeout,$this->cookies); } else { $this->setError('no http/s in endpoint url'); } $this->request = $http->outgoing_payload; $this->response = $http->incoming_payload; $this->appendDebug($http->getDebug()); $this->UpdateCookies($http->incoming_cookies); // save transport object if using persistent connections if ($this->persistentConnection) { $http->clearDebug(); if (!is_object($this->persistentConnection)) { $this->persistentConnection = $http; } } if($err = $http->getError()){ $this->setError('HTTP Error: '.$err); return false; } elseif($this->getError()){ return false; } else { $this->debug('got response, length='. strlen($this->responseData).' type='.$http->incoming_headers['content-type']); return $this->parseResponse($http->incoming_headers, $this->responseData); } break; default: $this->setError('no transport found, or selected transport is not yet supported!'); return false; break; } } /** * processes SOAP message returned from server * * @param array $headers The HTTP headers * @param string $data unprocessed response data from server * @return mixed value of the message, decoded into a PHP type * @access private */ function parseResponse($headers, $data) { $this->debug('Entering parseResponse() for data of length ' . strlen($data) . ' headers:'); $this->appendDebug($this->varDump($headers)); if (!strstr($headers['content-type'], 'text/xml')) { $this->setError('Response not of type text/xml: ' . $headers['content-type']); return false; } if (strpos($headers['content-type'], '=')) { $enc = str_replace('"', '', substr(strstr($headers["content-type"], '='), 1)); $this->debug('Got response encoding: ' . $enc); if(eregi('^(ISO-8859-1|US-ASCII|UTF-8)$',$enc)){ $this->xml_encoding = strtoupper($enc); } else { $this->xml_encoding = 'US-ASCII'; } } else { // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 $this->xml_encoding = 'ISO-8859-1'; } $this->debug('Use encoding: ' . $this->xml_encoding . ' when creating nusoap_parser'); $parser = new nusoap_parser($data,$this->xml_encoding,$this->operation,$this->decode_utf8); // add parser debug data to our debug $this->appendDebug($parser->getDebug()); // if parse errors if($errstr = $parser->getError()){ $this->setError( $errstr); // destroy the parser object unset($parser); return false; } else { // get SOAP headers $this->responseHeaders = $parser->getHeaders(); // get SOAP headers $this->responseHeader = $parser->get_soapheader(); // get decoded message $return = $parser->get_soapbody(); // add document for doclit support $this->document = $parser->document; // destroy the parser object unset($parser); // return decode message return $return; } } /** * sets user-specified cURL options * * @param mixed $option The cURL option (always integer?) * @param mixed $value The cURL option value * @access public */ function setCurlOption($option, $value) { $this->debug("setCurlOption option=$option, value="); $this->appendDebug($this->varDump($value)); $this->curl_options[$option] = $value; } /** * sets the SOAP endpoint, which can override WSDL * * @param string $endpoint The endpoint URL to use, or empty string or false to prevent override * @access public */ function setEndpoint($endpoint) { $this->debug("setEndpoint(\"$endpoint\")"); $this->forceEndpoint = $endpoint; } /** * set the SOAP headers * * @param mixed $headers String of XML with SOAP header content, or array of soapval objects for SOAP headers * @access public */ function setHeaders($headers){ $this->debug("setHeaders headers="); $this->appendDebug($this->varDump($headers)); $this->requestHeaders = $headers; } /** * get the SOAP response headers (namespace resolution incomplete) * * @return string * @access public */ function getHeaders(){ return $this->responseHeaders; } /** * get the SOAP response Header (parsed) * * @return mixed * @access public */ function getHeader(){ return $this->responseHeader; } /** * set proxy info here * * @param string $proxyhost * @param string $proxyport * @param string $proxyusername * @param string $proxypassword * @access public */ function setHTTPProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '') { $this->proxyhost = $proxyhost; $this->proxyport = $proxyport; $this->proxyusername = $proxyusername; $this->proxypassword = $proxypassword; } /** * if authenticating, set user credentials here * * @param string $username * @param string $password * @param string $authtype (basic|digest|certificate|ntlm) * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs) * @access public */ function setCredentials($username, $password, $authtype = 'basic', $certRequest = array()) { $this->debug("setCredentials username=$username authtype=$authtype certRequest="); $this->appendDebug($this->varDump($certRequest)); $this->username = $username; $this->password = $password; $this->authtype = $authtype; $this->certRequest = $certRequest; } /** * use HTTP encoding * * @param string $enc HTTP encoding * @access public */ function setHTTPEncoding($enc='gzip, deflate'){ $this->debug("setHTTPEncoding(\"$enc\")"); $this->http_encoding = $enc; } /** * Set whether to try to use cURL connections if possible * * @param boolean $use Whether to try to use cURL * @access public */ function setUseCURL($use) { $this->debug("setUseCURL($use)"); $this->use_curl = $use; } /** * use HTTP persistent connections if possible * * @access public */ function useHTTPPersistentConnection(){ $this->debug("useHTTPPersistentConnection"); $this->persistentConnection = true; } /** * gets the default RPC parameter setting. * If true, default is that call params are like RPC even for document style. * Each call() can override this value. * * This is no longer used. * * @return boolean * @access public * @deprecated */ function getDefaultRpcParams() { return $this->defaultRpcParams; } /** * sets the default RPC parameter setting. * If true, default is that call params are like RPC even for document style * Each call() can override this value. * * This is no longer used. * * @param boolean $rpcParams * @access public * @deprecated */ function setDefaultRpcParams($rpcParams) { $this->defaultRpcParams = $rpcParams; } /** * dynamically creates an instance of a proxy class, * allowing user to directly call methods from wsdl * * @return object soap_proxy object * @access public */ function getProxy() { $r = rand(); $evalStr = $this->_getProxyClassCode($r); //$this->debug("proxy class: $evalStr"); if ($this->getError()) { $this->debug("Error from _getProxyClassCode, so return NULL"); return null; } // eval the class eval($evalStr); // instantiate proxy object eval("\$proxy = new nusoap_proxy_$r('');"); // transfer current wsdl data to the proxy thereby avoiding parsing the wsdl twice $proxy->endpointType = 'wsdl'; $proxy->wsdlFile = $this->wsdlFile; $proxy->wsdl = $this->wsdl; $proxy->operations = $this->operations; $proxy->defaultRpcParams = $this->defaultRpcParams; // transfer other state $proxy->soap_defencoding = $this->soap_defencoding; $proxy->username = $this->username; $proxy->password = $this->password; $proxy->authtype = $this->authtype; $proxy->certRequest = $this->certRequest; $proxy->requestHeaders = $this->requestHeaders; $proxy->endpoint = $this->endpoint; $proxy->forceEndpoint = $this->forceEndpoint; $proxy->proxyhost = $this->proxyhost; $proxy->proxyport = $this->proxyport; $proxy->proxyusername = $this->proxyusername; $proxy->proxypassword = $this->proxypassword; $proxy->http_encoding = $this->http_encoding; $proxy->timeout = $this->timeout; $proxy->response_timeout = $this->response_timeout; $proxy->persistentConnection = &$this->persistentConnection; $proxy->decode_utf8 = $this->decode_utf8; $proxy->curl_options = $this->curl_options; $proxy->bindingType = $this->bindingType; $proxy->use_curl = $this->use_curl; return $proxy; } /** * dynamically creates proxy class code * * @return string PHP/NuSOAP code for the proxy class * @access private */ function _getProxyClassCode($r) { $this->debug("in getProxy endpointType=$this->endpointType"); $this->appendDebug("wsdl=" . $this->varDump($this->wsdl)); if ($this->endpointType != 'wsdl') { $evalStr = 'A proxy can only be created for a WSDL client'; $this->setError($evalStr); $evalStr = "echo \"$evalStr\";"; return $evalStr; } if ($this->endpointType == 'wsdl' && is_null($this->wsdl)) { $this->loadWSDL(); if ($this->getError()) { return "echo \"" . $this->getError() . "\";"; } } $evalStr = ''; foreach ($this->operations as $operation => $opData) { if ($operation != '') { // create param string and param comment string if (sizeof($opData['input']['parts']) > 0) { $paramStr = ''; $paramArrayStr = ''; $paramCommentStr = ''; foreach ($opData['input']['parts'] as $name => $type) { $paramStr .= "\$$name, "; $paramArrayStr .= "'$name' => \$$name, "; $paramCommentStr .= "$type \$$name, "; } $paramStr = substr($paramStr, 0, strlen($paramStr)-2); $paramArrayStr = substr($paramArrayStr, 0, strlen($paramArrayStr)-2); $paramCommentStr = substr($paramCommentStr, 0, strlen($paramCommentStr)-2); } else { $paramStr = ''; $paramArrayStr = ''; $paramCommentStr = 'void'; } $opData['namespace'] = !isset($opData['namespace']) ? 'http://testuri.com' : $opData['namespace']; $evalStr .= "// $paramCommentStr function " . str_replace('.', '__', $operation) . "($paramStr) { \$params = array($paramArrayStr); return \$this->call('$operation', \$params, '".$opData['namespace']."', '".(isset($opData['soapAction']) ? $opData['soapAction'] : '')."'); } "; unset($paramStr); unset($paramCommentStr); } } $evalStr = 'class nusoap_proxy_'.$r.' extends nusoap_client { '.$evalStr.' }'; return $evalStr; } /** * dynamically creates proxy class code * * @return string PHP/NuSOAP code for the proxy class * @access public */ function getProxyClassCode() { $r = rand(); return $this->_getProxyClassCode($r); } /** * gets the HTTP body for the current request. * * @param string $soapmsg The SOAP payload * @return string The HTTP body, which includes the SOAP payload * @access private */ function getHTTPBody($soapmsg) { return $soapmsg; } /** * gets the HTTP content type for the current request. * * Note: getHTTPBody must be called before this. * * @return string the HTTP content type for the current request. * @access private */ function getHTTPContentType() { return 'text/xml'; } /** * gets the HTTP content type charset for the current request. * returns false for non-text content types. * * Note: getHTTPBody must be called before this. * * @return string the HTTP content type charset for the current request. * @access private */ function getHTTPContentTypeCharset() { return $this->soap_defencoding; } /* * whether or not parser should decode utf8 element content * * @return always returns true * @access public */ function decodeUTF8($bool){ $this->decode_utf8 = $bool; return true; } /** * adds a new Cookie into $this->cookies array * * @param string $name Cookie Name * @param string $value Cookie Value * @return boolean if cookie-set was successful returns true, else false * @access public */ function setCookie($name, $value) { if (strlen($name) == 0) { return false; } $this->cookies[] = array('name' => $name, 'value' => $value); return true; } /** * gets all Cookies * * @return array with all internal cookies * @access public */ function getCookies() { return $this->cookies; } /** * checks all Cookies and delete those which are expired * * @return boolean always return true * @access private */ function checkCookies() { if (sizeof($this->cookies) == 0) { return true; } $this->debug('checkCookie: check ' . sizeof($this->cookies) . ' cookies'); $curr_cookies = $this->cookies; $this->cookies = array(); foreach ($curr_cookies as $cookie) { if (! is_array($cookie)) { $this->debug('Remove cookie that is not an array'); continue; } if ((isset($cookie['expires'])) && (! empty($cookie['expires']))) { if (strtotime($cookie['expires']) > time()) { $this->cookies[] = $cookie; } else { $this->debug('Remove expired cookie ' . $cookie['name']); } } else { $this->cookies[] = $cookie; } } $this->debug('checkCookie: '.sizeof($this->cookies).' cookies left in array'); return true; } /** * updates the current cookies with a new set * * @param array $cookies new cookies with which to update current ones * @return boolean always return true * @access private */ function UpdateCookies($cookies) { if (sizeof($this->cookies) == 0) { // no existing cookies: take whatever is new if (sizeof($cookies) > 0) { $this->debug('Setting new cookie(s)'); $this->cookies = $cookies; } return true; } if (sizeof($cookies) == 0) { // no new cookies: keep what we've got return true; } // merge foreach ($cookies as $newCookie) { if (!is_array($newCookie)) { continue; } if ((!isset($newCookie['name'])) || (!isset($newCookie['value']))) { continue; } $newName = $newCookie['name']; $found = false; for ($i = 0; $i < count($this->cookies); $i++) { $cookie = $this->cookies[$i]; if (!is_array($cookie)) { continue; } if (!isset($cookie['name'])) { continue; } if ($newName != $cookie['name']) { continue; } $newDomain = isset($newCookie['domain']) ? $newCookie['domain'] : 'NODOMAIN'; $domain = isset($cookie['domain']) ? $cookie['domain'] : 'NODOMAIN'; if ($newDomain != $domain) { continue; } $newPath = isset($newCookie['path']) ? $newCookie['path'] : 'NOPATH'; $path = isset($cookie['path']) ? $cookie['path'] : 'NOPATH'; if ($newPath != $path) { continue; } $this->cookies[$i] = $newCookie; $found = true; $this->debug('Update cookie ' . $newName . '=' . $newCookie['value']); break; } if (! $found) { $this->debug('Add cookie ' . $newName . '=' . $newCookie['value']); $this->cookies[] = $newCookie; } } return true; } } if (!extension_loaded('soap')) { /** * For backwards compatiblity, define soapclient unless the PHP SOAP extension is loaded. */ class soapclient extends nusoap_client { } } ?> administrator/components/com_virtuemart/classes/nusoap/nusoapmime.php100644 0 0 36277 11263442237 24205 0ustar 0 0 * @author Thanks to Guillaume and Henning Reich for posting great attachment code to the mail list * @version $Id: nusoapmime.php,v 1.12 2007/04/17 16:34:03 snichol Exp $ * @access public */ class nusoap_client_mime extends nusoap_client { /** * @var array Each array element in the return is an associative array with keys * data, filename, contenttype, cid * @access private */ var $requestAttachments = array(); /** * @var array Each array element in the return is an associative array with keys * data, filename, contenttype, cid * @access private */ var $responseAttachments; /** * @var string * @access private */ var $mimeContentType; /** * adds a MIME attachment to the current request. * * If the $data parameter contains an empty string, this method will read * the contents of the file named by the $filename parameter. * * If the $cid parameter is false, this method will generate the cid. * * @param string $data The data of the attachment * @param string $filename The filename of the attachment (default is empty string) * @param string $contenttype The MIME Content-Type of the attachment (default is application/octet-stream) * @param string $cid The content-id (cid) of the attachment (default is false) * @return string The content-id (cid) of the attachment * @access public */ function addAttachment($data, $filename = '', $contenttype = 'application/octet-stream', $cid = false) { if (! $cid) { $cid = md5(uniqid(time())); } $info['data'] = $data; $info['filename'] = $filename; $info['contenttype'] = $contenttype; $info['cid'] = $cid; $this->requestAttachments[] = $info; return $cid; } /** * clears the MIME attachments for the current request. * * @access public */ function clearAttachments() { $this->requestAttachments = array(); } /** * gets the MIME attachments from the current response. * * Each array element in the return is an associative array with keys * data, filename, contenttype, cid. These keys correspond to the parameters * for addAttachment. * * @return array The attachments. * @access public */ function getAttachments() { return $this->responseAttachments; } /** * gets the HTTP body for the current request. * * @param string $soapmsg The SOAP payload * @return string The HTTP body, which includes the SOAP payload * @access private */ function getHTTPBody($soapmsg) { if (count($this->requestAttachments) > 0) { $params['content_type'] = 'multipart/related; type="text/xml"'; $mimeMessage = new Mail_mimePart('', $params); unset($params); $params['content_type'] = 'text/xml'; $params['encoding'] = '8bit'; $params['charset'] = $this->soap_defencoding; $mimeMessage->addSubpart($soapmsg, $params); foreach ($this->requestAttachments as $att) { unset($params); $params['content_type'] = $att['contenttype']; $params['encoding'] = 'base64'; $params['disposition'] = 'attachment'; $params['dfilename'] = $att['filename']; $params['cid'] = $att['cid']; if ($att['data'] == '' && $att['filename'] <> '') { if ($fd = fopen($att['filename'], 'rb')) { $data = fread($fd, filesize($att['filename'])); fclose($fd); } else { $data = ''; } $mimeMessage->addSubpart($data, $params); } else { $mimeMessage->addSubpart($att['data'], $params); } } $output = $mimeMessage->encode(); $mimeHeaders = $output['headers']; foreach ($mimeHeaders as $k => $v) { $this->debug("MIME header $k: $v"); if (strtolower($k) == 'content-type') { // PHP header() seems to strip leading whitespace starting // the second line, so force everything to one line $this->mimeContentType = str_replace("\r\n", " ", $v); } } return $output['body']; } return parent::getHTTPBody($soapmsg); } /** * gets the HTTP content type for the current request. * * Note: getHTTPBody must be called before this. * * @return string the HTTP content type for the current request. * @access private */ function getHTTPContentType() { if (count($this->requestAttachments) > 0) { return $this->mimeContentType; } return parent::getHTTPContentType(); } /** * gets the HTTP content type charset for the current request. * returns false for non-text content types. * * Note: getHTTPBody must be called before this. * * @return string the HTTP content type charset for the current request. * @access private */ function getHTTPContentTypeCharset() { if (count($this->requestAttachments) > 0) { return false; } return parent::getHTTPContentTypeCharset(); } /** * processes SOAP message returned from server * * @param array $headers The HTTP headers * @param string $data unprocessed response data from server * @return mixed value of the message, decoded into a PHP type * @access private */ function parseResponse($headers, $data) { $this->debug('Entering parseResponse() for payload of length ' . strlen($data) . ' and type of ' . $headers['content-type']); $this->responseAttachments = array(); if (strstr($headers['content-type'], 'multipart/related')) { $this->debug('Decode multipart/related'); $input = ''; foreach ($headers as $k => $v) { $input .= "$k: $v\r\n"; } $params['input'] = $input . "\r\n" . $data; $params['include_bodies'] = true; $params['decode_bodies'] = true; $params['decode_headers'] = true; $structure = Mail_mimeDecode::decode($params); foreach ($structure->parts as $part) { if (!isset($part->disposition) && (strstr($part->headers['content-type'], 'text/xml'))) { $this->debug('Have root part of type ' . $part->headers['content-type']); $root = $part->body; $return = parent::parseResponse($part->headers, $part->body); } else { $this->debug('Have an attachment of type ' . $part->headers['content-type']); $info['data'] = $part->body; $info['filename'] = isset($part->d_parameters['filename']) ? $part->d_parameters['filename'] : ''; $info['contenttype'] = $part->headers['content-type']; $info['cid'] = $part->headers['content-id']; $this->responseAttachments[] = $info; } } if (isset($return)) { $this->responseData = $root; return $return; } $this->setError('No root part found in multipart/related content'); return ''; } $this->debug('Not multipart/related'); return parent::parseResponse($headers, $data); } } /* * For backwards compatiblity, define soapclientmime unless the PHP SOAP extension is loaded. */ if (!extension_loaded('soap')) { class soapclientmime extends nusoap_client_mime { } } /** * nusoap_server_mime server supporting MIME attachments defined at * http://www.w3.org/TR/SOAP-attachments. It depends on the PEAR Mail_MIME library. * * @author Scott Nichol * @author Thanks to Guillaume and Henning Reich for posting great attachment code to the mail list * @version $Id: nusoapmime.php,v 1.12 2007/04/17 16:34:03 snichol Exp $ * @access public */ class nusoap_server_mime extends nusoap_server { /** * @var array Each array element in the return is an associative array with keys * data, filename, contenttype, cid * @access private */ var $requestAttachments = array(); /** * @var array Each array element in the return is an associative array with keys * data, filename, contenttype, cid * @access private */ var $responseAttachments; /** * @var string * @access private */ var $mimeContentType; /** * adds a MIME attachment to the current response. * * If the $data parameter contains an empty string, this method will read * the contents of the file named by the $filename parameter. * * If the $cid parameter is false, this method will generate the cid. * * @param string $data The data of the attachment * @param string $filename The filename of the attachment (default is empty string) * @param string $contenttype The MIME Content-Type of the attachment (default is application/octet-stream) * @param string $cid The content-id (cid) of the attachment (default is false) * @return string The content-id (cid) of the attachment * @access public */ function addAttachment($data, $filename = '', $contenttype = 'application/octet-stream', $cid = false) { if (! $cid) { $cid = md5(uniqid(time())); } $info['data'] = $data; $info['filename'] = $filename; $info['contenttype'] = $contenttype; $info['cid'] = $cid; $this->responseAttachments[] = $info; return $cid; } /** * clears the MIME attachments for the current response. * * @access public */ function clearAttachments() { $this->responseAttachments = array(); } /** * gets the MIME attachments from the current request. * * Each array element in the return is an associative array with keys * data, filename, contenttype, cid. These keys correspond to the parameters * for addAttachment. * * @return array The attachments. * @access public */ function getAttachments() { return $this->requestAttachments; } /** * gets the HTTP body for the current response. * * @param string $soapmsg The SOAP payload * @return string The HTTP body, which includes the SOAP payload * @access private */ function getHTTPBody($soapmsg) { if (count($this->responseAttachments) > 0) { $params['content_type'] = 'multipart/related; type="text/xml"'; $mimeMessage = new Mail_mimePart('', $params); unset($params); $params['content_type'] = 'text/xml'; $params['encoding'] = '8bit'; $params['charset'] = $this->soap_defencoding; $mimeMessage->addSubpart($soapmsg, $params); foreach ($this->responseAttachments as $att) { unset($params); $params['content_type'] = $att['contenttype']; $params['encoding'] = 'base64'; $params['disposition'] = 'attachment'; $params['dfilename'] = $att['filename']; $params['cid'] = $att['cid']; if ($att['data'] == '' && $att['filename'] <> '') { if ($fd = fopen($att['filename'], 'rb')) { $data = fread($fd, filesize($att['filename'])); fclose($fd); } else { $data = ''; } $mimeMessage->addSubpart($data, $params); } else { $mimeMessage->addSubpart($att['data'], $params); } } $output = $mimeMessage->encode(); $mimeHeaders = $output['headers']; foreach ($mimeHeaders as $k => $v) { $this->debug("MIME header $k: $v"); if (strtolower($k) == 'content-type') { // PHP header() seems to strip leading whitespace starting // the second line, so force everything to one line $this->mimeContentType = str_replace("\r\n", " ", $v); } } return $output['body']; } return parent::getHTTPBody($soapmsg); } /** * gets the HTTP content type for the current response. * * Note: getHTTPBody must be called before this. * * @return string the HTTP content type for the current response. * @access private */ function getHTTPContentType() { if (count($this->responseAttachments) > 0) { return $this->mimeContentType; } return parent::getHTTPContentType(); } /** * gets the HTTP content type charset for the current response. * returns false for non-text content types. * * Note: getHTTPBody must be called before this. * * @return string the HTTP content type charset for the current response. * @access private */ function getHTTPContentTypeCharset() { if (count($this->responseAttachments) > 0) { return false; } return parent::getHTTPContentTypeCharset(); } /** * processes SOAP message received from client * * @param array $headers The HTTP headers * @param string $data unprocessed request data from client * @return mixed value of the message, decoded into a PHP type * @access private */ function parseRequest($headers, $data) { $this->debug('Entering parseRequest() for payload of length ' . strlen($data) . ' and type of ' . $headers['content-type']); $this->requestAttachments = array(); if (strstr($headers['content-type'], 'multipart/related')) { $this->debug('Decode multipart/related'); $input = ''; foreach ($headers as $k => $v) { $input .= "$k: $v\r\n"; } $params['input'] = $input . "\r\n" . $data; $params['include_bodies'] = true; $params['decode_bodies'] = true; $params['decode_headers'] = true; $structure = Mail_mimeDecode::decode($params); foreach ($structure->parts as $part) { if (!isset($part->disposition) && (strstr($part->headers['content-type'], 'text/xml'))) { $this->debug('Have root part of type ' . $part->headers['content-type']); $return = parent::parseRequest($part->headers, $part->body); } else { $this->debug('Have an attachment of type ' . $part->headers['content-type']); $info['data'] = $part->body; $info['filename'] = isset($part->d_parameters['filename']) ? $part->d_parameters['filename'] : ''; $info['contenttype'] = $part->headers['content-type']; $info['cid'] = $part->headers['content-id']; $this->requestAttachments[] = $info; } } if (isset($return)) { return $return; } $this->setError('No root part found in multipart/related content'); return; } $this->debug('Not multipart/related'); return parent::parseRequest($headers, $data); } } /* * For backwards compatiblity */ class nusoapservermime extends nusoap_server_mime { } ?> administrator/components/com_virtuemart/classes/pageNavigation.class.php100644 0 0 23332 11063532564 24550 0ustar 0 0 total = intval( $total ); $this->limitstart = max( $limitstart, 0 ); $this->limit = max( $limit, 1 ); if ($this->limit > $this->total) { $this->limitstart = 0; } if (($this->limit-1)*$this->limitstart > $this->total) { $this->limitstart -= $this->limitstart % $this->limit; } } /** * Writes the html limit # input box * Modified by shumisha to handle SEF URLs 2008-06-28 */ function writeLimitBox ( $link = '') { echo $this->getLimitBox( $link); } /** * Modified by shumisha to handle SEF URLs 2008-06-28 * @return string The html for the limit # input box */ function getLimitBox ( $link = '') { $limits = array(); if (!empty($link) && strpos( 'limitstart=', $link) === false) { // insert limitstart in url if missing // shumisha $link .= '&limitstart='.$this->limitstart; } for ($i=5; $i <= 30; $i+=5) { if (empty( $link)) { $limits[$i] = $i; } else { $limits[vmRoute($link.'&limit='.$i)] = $i; } } if (empty( $link)) { $limits[50] = 50; } else { $limits[vmRoute($link.'&limit=50')] = 50; } // build the html select list if (empty( $link)) { $html = ps_html::selectList( 'limit', $this->limit, $limits, 1, '', 'onchange="this.form.submit();"' ); } else { $current = vmRoute($link.'&limit='.$this->limit); $html = ps_html::selectList( 'limit', $current, $limits, 1, '', 'onchange="location.href=this.value"' ); } $html .= "\nlimitstart\" />"; return $html; } function writePagesCounter() { echo $this->getPagesCounter(); } /** * @return string The html for the pages counter, eg, Results 1-10 of x */ function getPagesCounter() { $html = ''; $from_result = $this->limitstart+1; if ($this->limitstart + $this->limit < $this->total) { $to_result = $this->limitstart + $this->limit; } else { $to_result = $this->total; } if ($this->total > 0) { $html .= $GLOBALS['VM_LANG']->_('PN_RESULTS')." $from_result - $to_result ".$GLOBALS['VM_LANG']->_('PN_OF')." $this->total"; } else { //$html .= "\nNo records found."; } return $html; } /** * Writes the html for the pages counter, eg, Results 1-10 of x */ function writePagesLinks($link='') { echo $this->getPagesLinks($link); } /** * @return string The html links for pages, eg, previous, next, 1 2 3 ... x */ function getPagesLinks($link='') { global $VM_LANG; $displayed_pages = 10; $total_pages = ceil( $this->total / $this->limit ); $this_page = ceil( ($this->limitstart+1) / $this->limit ); $start_loop = (floor(($this_page-1)/$displayed_pages))*$displayed_pages+1; if ($start_loop + $displayed_pages - 1 < $total_pages) { $stop_loop = $start_loop + $displayed_pages - 1; } else { $stop_loop = $total_pages; } $html = '"; return $html; } function getListFooter() { $html = ''; if( $this->total > $this->limit || $this->limitstart > 0) { $html .= ''; } $html .= ''; $html .= ''; $html .= ''; $html .= '
    '; $html .= $this->getPagesLinks(); $html .= '
    '.$GLOBALS['VM_LANG']->_('PN_DISPLAY_NR').'' .$this->getLimitBox() . '' . $this->getPagesCounter() . '
    '; return $html; } /** * @param int The row index * @return int */ function rowNumber( $i ) { return $i + 1 + $this->limitstart; } /** * @param int The row index * @param string The task to fire * @param string The alt text for the icon * @return string */ function orderUpIcon( $i, $condition=true, $task='orderup', $alt='', $page, $func ) { global $mosConfig_live_site, $VM_LANG; if( $alt == '') { $alt = $VM_LANG->_('CMN_ORDER_UP'); } if (($i > 0 || ($i+$this->limitstart > 0)) && $condition) { return ' '.$alt.' '; } else { return ' '; } } /** * @param int The row index * @param int The number of items in the list * @param string The task to fire * @param string The alt text for the icon * @return string */ function orderDownIcon( $i, $n, $condition=true, $task='orderdown', $alt='', $page, $func ) { global $mosConfig_live_site, $VM_LANG; if( $alt == '') { $alt = $VM_LANG->_('CMN_ORDER_DOWN'); } if (($i < $n-1 || $i+$this->limitstart < $this->total-1) && $condition) { return ' '.$alt.' '; } else { return ' '; } } } ?> administrator/components/com_virtuemart/classes/parameters.class.php100644 0 0 37543 10732276304 23767 0ustar 0 0 _params = $this->parse( $text ); $this->_raw = $text; $this->_path = $path; $this->_type = $type; } /** * Returns the params array * @return object */ function toObject() { return $this->_params; } /** * Returns a named array of the parameters * @return object */ function toArray() { return mosObjectToArray( $this->_params ); } /** * @param string The name of the param * @param string The value of the parameter * @return string The set value */ function set( $key, $value='' ) { $this->_params->$key = $value; return $value; } /** * Sets a default value if not alreay assigned * @param string The name of the param * @param string The value of the parameter * @return string The set value */ function def( $key, $value='' ) { return $this->set( $key, $this->get( $key, $value ) ); } /** * @param string The name of the param * @param mixed The default value if not found * @return string */ function get( $key, $default='' ) { if (isset( $this->_params->$key )) { return $this->_params->$key === '' ? $default : $this->_params->$key; } else { return $default; } } /** * Parse an .ini string, based on phpDocumentor phpDocumentor_parse_ini_file function * @param mixed The ini string or array of lines * @param boolean add an associative index for each section [in brackets] * @return object */ function parse( $txt, $process_sections = false, $asArray = false ) { if (is_string( $txt )) { $lines = explode( "\n", $txt ); } else if (is_array( $txt )) { $lines = $txt; } else { $lines = array(); } $obj = $asArray ? array() : new stdClass(); $sec_name = ''; $unparsed = 0; if (!$lines) { return $obj; } foreach ($lines as $line) { // ignore comments if ($line && $line[0] == ';') { continue; } $line = trim( $line ); if ($line == '') { continue; } if ($line && $line[0] == '[' && $line[strlen($line) - 1] == ']') { $sec_name = substr( $line, 1, strlen($line) - 2 ); if ($process_sections) { if ($asArray) { $obj[$sec_name] = array(); } else { $obj->$sec_name = new stdClass(); } } } else { if ($pos = strpos( $line, '=' )) { $property = trim( substr( $line, 0, $pos ) ); if (substr($property, 0, 1) == '"' && substr($property, -1) == '"') { $property = stripcslashes(substr($property,1,count($property) - 2)); } $value = trim( substr( $line, $pos + 1 ) ); if ($value == 'false') { $value = false; } if ($value == 'true') { $value = true; } if (substr( $value, 0, 1 ) == '"' && substr( $value, -1 ) == '"') { $value = stripcslashes( substr( $value, 1, count( $value ) - 2 ) ); } if ($process_sections) { $value = str_replace( '\n', "\n", $value ); if ($sec_name != '') { if ($asArray) { $obj[$sec_name][$property] = $value; } else { $obj->$sec_name->$property = $value; } } else { if ($asArray) { $obj[$property] = $value; } else { $obj->$property = $value; } } } else { $value = str_replace( '\n', "\n", $value ); if ($asArray) { $obj[$property] = $value; } else { $obj->$property = $value; } } } else { if ($line && trim($line[0]) == ';') { continue; } if ($process_sections) { $property = '__invalid' . $unparsed++ . '__'; if ($process_sections) { if ($sec_name != '') { if ($asArray) { $obj[$sec_name][$property] = trim($line); } else { $obj->$sec_name->$property = trim($line); } } else { if ($asArray) { $obj[$property] = trim($line); } else { $obj->$property = trim($line); } } } else { if ($asArray) { $obj[$property] = trim($line); } else { $obj->$property = trim($line); } } } } } } return $obj; } /** * @param string The name of the control, or the default text area if a setup file is not found * @return string HTML */ function render( $name='params' ) { global $mosConfig_absolute_path; if ($this->_path) { if (!is_object( $this->_xmlElem )) { require_once( $mosConfig_absolute_path . '/includes/domit/xml_domit_lite_include.php' ); $xmlDoc = new DOMIT_Lite_Document(); $xmlDoc->resolveErrors( true ); if ($xmlDoc->loadXML( $this->_path, false, true )) { $root =& $xmlDoc->documentElement; $tagName = $root->getTagName(); $isParamsFile = ($tagName == 'mosinstall' || $tagName == 'mosparams'); if ($isParamsFile && $root->getAttribute( 'type' ) == $this->_type) { if ($params = &$root->getElementsByPath( 'params', 1 )) { $this->_xmlElem =& $params; } } } } } if (is_object( $this->_xmlElem )) { $html = array(); $html[] = ''; $element =& $this->_xmlElem; if ($description = $element->getAttribute( 'description' )) { // add the params description to the display $html[] = ''; } //$params = mosParseParams( $row->params ); $this->_methods = get_class_methods( get_class( $this ) ); foreach ($element->childNodes as $param) { $result = $this->renderParam( $param, $name ); $html[] = ''; $html[] = ''; $html[] = ''; $html[] = ''; } $html[] = '
    ' . $description . '
    ' . $result[0] . '' . $result[1] . '
    '; if (count( $element->childNodes ) < 1) { $html[] = "" . _NO_PARAMS . ""; } return implode( "\n", $html ); } else { return ""; } } /** * @param object A param tag node * @param string The control name * @return array Any array of the label, the form element and the tooltip */ function renderParam( &$param, $control_name='params' ) { $result = array(); $name = $param->getAttribute( 'name' ); $label = $param->getAttribute( 'label' ); $value = $this->get( $name, $param->getAttribute( 'default' ) ); $description = $param->getAttribute( 'description' ); $result[0] = $label ? $label : $name; if ($result[0] == '@spacer') { $result[0] = ' '; } else { $result[0] = vmToolTip( addslashes( $description ), addslashes( $result[0] ), '', '', $result[0], '#', 0 ); } $type = $param->getAttribute( 'type' ); if (in_array( '_form_' . $type, $this->_methods )) { $result[1] = call_user_func( array( &$this, '_form_' . $type ), $name, $value, $param, $control_name ); } else { $result[1] = _HANDLER . ' = ' . $type; } if ( $description ) { $result[2] = vmToolTip( $description, $result[0] ); $result[2] = ''; } else { $result[2] = ''; } return $result; } /** * @param string The name of the form element * @param string The value of the element * @param object The xml element for the parameter * @param string The control name * @return string The html for the element */ function _form_text( $name, $value, &$node, $control_name ) { $size = $node->getAttribute( 'size' ); return ''; } /** * @param string The name of the form element * @param string The value of the element * @param object The xml element for the parameter * @param string The control name * @return string The html for the element */ function _form_list( $name, $value, &$node, $control_name ) { $size = $node->getAttribute( 'size' ); $options = array(); foreach ($node->childNodes as $option) { $val = $option->getAttribute( 'value' ); $text = $option->gettext(); $options[$val] = $text; } return ps_html::selectList( $control_name .'['. $name .']', $value, $options ); } /** * @param string The name of the form element * @param string The value of the element * @param object The xml element for the parameter * @param string The control name * @return string The html for the element */ function _form_radio( $name, $value, &$node, $control_name ) { $options = array(); foreach ($node->childNodes as $option) { $val = $option->getAttribute( 'value' ); $text = $option->gettext(); $options[$val] = $text; } return ps_html::radioList( $control_name .'['. $name .']', $value, $options ); } /** * @param string The name of the form element * @param string The value of the element * @param object The xml element for the parameter * @param string The control name * @return string The html for the element */ function _form_mos_section( $name, $value, &$node, $control_name ) { global $database; $query = "SELECT id, title" . "\n FROM #__sections" . "\n WHERE published = 1" . "\n AND scope = 'content'" . "\n ORDER BY title" ; $database->setQuery( $query ); $options = $database->loadObjectList(); array_unshift( $options, mosHTML::makeOption( '0', '- Select Section -', 'id', 'title' ) ); return mosHTML::selectList( $options, ''. $control_name .'['. $name .']', 'class="inputbox"', 'id', 'title', $value ); } /** * @param string The name of the form element * @param string The value of the element * @param object The xml element for the parameter * @param string The control name * @return string The html for the element */ function _form_mos_category( $name, $value, &$node, $control_name ) { global $database; $scope = $node->getAttribute( 'scope' ); if( !isset($scope) ) { $scope = 'content'; } if( $scope== 'content' ) { // This might get a conflict with the dynamic translation - TODO: search for better solution $query = "SELECT c.id, CONCAT_WS( '/',s.title, c.title ) AS title" . "\n FROM #__categories AS c" . "\n LEFT JOIN #__sections AS s ON s.id=c.section" . "\n WHERE c.published = 1" . "\n AND s.scope = " . $database->Quote( $scope ) . "\n ORDER BY c.title" ; } else { $query = "SELECT c.id, c.title" . "\n FROM #__categories AS c" . "\n WHERE c.published = 1" . "\n AND c.section = " . $database->Quote( $scope ) . "\n ORDER BY c.title" ; } $database->setQuery( $query ); $options = $database->loadObjectList(); array_unshift( $options, mosHTML::makeOption( '0', '- Select Category -', 'id', 'title' ) ); return mosHTML::selectList( $options, ''. $control_name .'['. $name .']', 'class="inputbox"', 'id', 'title', $value ); } /** * @param string The name of the form element * @param string The value of the element * @param object The xml element for the parameter * @param string The control name * @return string The html for the element */ function _form_mos_menu( $name, $value, &$node, $control_name ) { global $database; $menuTypes = mosAdminMenus::menutypes(); foreach($menuTypes as $menutype ) { $options[] = mosHTML::makeOption( $menutype, $menutype ); } array_unshift( $options, mosHTML::makeOption( '', '- Select Menu -' ) ); return mosHTML::selectList( $options, ''. $control_name .'['. $name .']', 'class="inputbox"', 'value', 'text', $value ); } /** * @param string The name of the form element * @param string The value of the element * @param object The xml element for the parameter * @param string The control name * @return string The html for the element */ function _form_filelist( $name, $value, &$node, $control_name ) { global $mosConfig_absolute_path; // path to images directory $path = $mosConfig_absolute_path . $node->getAttribute( 'directory' ); $filter = $node->getAttribute( 'filter' ); $files = vmReadDirectory( $path, $filter ); $options = array(); foreach ($files as $file) { $options[] = mosHTML::makeOption( $file, $file ); } if ( !$node->getAttribute( 'hide_none' ) ) { array_unshift( $options, mosHTML::makeOption( '-1', '- '. 'Do Not Use' .' -' ) ); } if ( !$node->getAttribute( 'hide_default' ) ) { array_unshift( $options, mosHTML::makeOption( '', '- '. 'Use Default' .' -' ) ); } return mosHTML::selectList( $options, ''. $control_name .'['. $name .']', 'class="inputbox"', 'value', 'text', $value, "param$name" ); } /** * @param string The name of the form element * @param string The value of the element * @param object The xml element for the parameter * @param string The control name * @return string The html for the element */ function _form_imagelist( $name, $value, &$node, $control_name ) { $node->setAttribute( 'filter', '\.png$|\.gif$|\.jpg$|\.bmp$|\.ico$' ); return $this->_form_filelist( $name, $value, $node, $control_name ); } /** * @param string The name of the form element * @param string The value of the element * @param object The xml element for the parameter * @param string The control name * @return string The html for the element */ function _form_textarea( $name, $value, &$node, $control_name ) { $rows = $node->getAttribute( 'rows' ); $cols = $node->getAttribute( 'cols' ); // convert
    tags so they are not visible when editing $value = str_replace( '
    ', "\n", $value ); return ''; } /** * @param string The name of the form element * @param string The value of the element * @param object The xml element for the parameter * @param string The control name * @return string The html for the element */ function _form_spacer( $name, $value, &$node, $control_name ) { if ( $value ) { return $value; } else { return '
    '; } } /** * special handling for textarea param */ function textareaHandling( &$txt ) { $total = count( $txt ); for( $i=0; $i < $total; $i++ ) { if ( strstr( $txt[$i], "\n" ) ) { $txt[$i] = str_replace( "\n", '
    ', $txt[$i] ); } } $txt = implode( "\n", $txt ); return $txt; } } /** * @param string * @return string */ function vmParseParams( $txt ) { return vmParameters::parse( $txt ); }administrator/components/com_virtuemart/classes/payment/index.html100644 0 0 0 10547254314 23334 0ustar 0 0 administrator/components/com_virtuemart/classes/payment/payflow_pro.cfg.php100644 0 0 601 10732276304 25215 0ustar 0 0 administrator/components/com_virtuemart/classes/payment/payflow_pro.php100644 0 0 100402 11263443355 24541 0ustar 0 0 classname.".cfg.php"); ?>
    _('PHPSHOP_ADMIN_CFG_ENABLE_PFP_TESTMODE') ?> _('PHPSHOP_ADMIN_CFG_ENABLE_PFP_TESTMODE_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_PFP_PARTNER') ?> _('PHPSHOP_ADMIN_CFG_PFP_PARTNET_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_PFP_VENDOR') ?> _('PHPSHOP_ADMIN_CFG_PFP_VENDOR_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_PFP_USER') ?> _('PHPSHOP_ADMIN_CFG_PFP_USER_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_PFP_PASSWORD') ?> " >  
    _('PHPSHOP_PAYMENT_CVV2') ?> _('PHPSHOP_PAYMENT_CVV2_TOOLTIP') ?>

    _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_SUCC') ?> _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_SUCC_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_FAIL') ?> _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_FAIL_EXPLAIN') ?>
    classname.".cfg.php" ); } /** * Returns the "is_readable" status of the configuration file * @param void * @returns boolean True when the configuration file is writeable, false when not */ function configfile_readable() { return is_readable( CLASSPATH."payment/".$this->classname.".cfg.php" ); } /** * Writes the configuration file for this payment method * @param array An array of objects * @returns boolean True when writing was successful */ function write_configuration( &$d ) { $my_config_array = array("PFP_TEST_REQUEST" => $d['PFP_TEST_REQUEST'], "PFP_PARTNER" => $d['PFP_PARTNER'], "PFP_VENDOR" => $d['PFP_VENDOR'], "PFP_USER" => $d['PFP_USER'], "PFP_CHECK_CARD_CODE" => $d['PFP_CHECK_CARD_CODE'], "PFP_VERIFIED_STATUS" => $d['PFP_VERIFIED_STATUS'], "PFP_INVALID_STATUS" => $d['PFP_INVALID_STATUS'] ); $config = " $value ) { $config .= "define ('$key', '$value');\n"; } $config .= "?>"; if ($fp = fopen(CLASSPATH ."payment/".$this->classname.".cfg.php", "w")) { fputs($fp, $config, strlen($config)); fclose ($fp); return true; } else { return false; } } /** * process transaction with Payflow Pro * Authorizes the amount for the customer account * * @param string $order_number * @param float $order_total * @param array $d * @return boolean */ function process_payment($order_number, $order_total, &$d) { global $vendor_mail, $vendor_currency, $VM_LANG, $vmLogger; $database = new ps_DB; $ps_vendor_id = $_SESSION["ps_vendor_id"]; $auth = $_SESSION['auth']; $ps_checkout = new ps_checkout; // Get the Configuration File for authorize.net require_once(CLASSPATH ."payment/".$this->classname.".cfg.php"); // connector class require_once(CLASSPATH ."connectionTools.class.php"); // Get the Password securely from the database $database->query( "SELECT ".VM_DECRYPT_FUNCTION."(payment_passkey,'".ENCODE_KEY."') as passkey FROM #__{vm}_payment_method WHERE payment_class='".$this->classname."' AND shopper_group_id='".$auth['shopper_group_id']."'" ); $transaction = $database->record[0]; if( empty($transaction->passkey)) { $vmLogger->err( $VM_LANG->_('PHPSHOP_PAYMENT_ERROR',false).'. Technical Note: The required passwird is empty! The payment method settings must be reviewed.' ); return false; } // Get user billing information $dbbt = new ps_DB; $qt = "SELECT * FROM #__{vm}_user_info WHERE user_id=".$auth["user_id"]." AND address_type='BT'"; $dbbt->query($qt); $dbbt->next_record(); $user_info_id = $dbbt->f("user_info_id"); if( $user_info_id != $d["ship_to_info_id"]) { // Get user billing information $dbst = new ps_DB; $qt = "SELECT * FROM #__{vm}_user_info WHERE user_info_id='".$d["ship_to_info_id"]."' AND address_type='ST'"; $dbst->query($qt); $dbst->next_record(); } else { $dbst = $dbbt; } $tempstr = $_SESSION['ccdata']['order_payment_number'] . $order_total . date('YmdGis'); $request_id = md5($tempstr); //Authnet vars to send $formdata = array ( 'PARTNER' => PFP_PARTNER, 'VENDOR' => PFP_VENDOR, 'USER' => PFP_USER, 'PWD' => $transaction->passkey, 'TEST' => PFP_TEST_REQUEST, // Transaction Data 'AMT' => $order_total, // amount 'TRXTYPE' => 'A', // transaction type: Delayed Capture 'TENDER' => 'C', // payment method (C = Credit Card) 'CURRENCY' => $vendor_currency, // Customer Name and Billing Address 'NAME' => strtoupper(substr($dbbt->f("first_name"), 0, 15).substr($dbbt->f("last_name"), 0, 15)), 'STREET' => substr($dbbt->f("address_1"), 0, 30), 'CITY' => substr($dbbt->f("city"), 0, 40), 'STATE' => substr($dbbt->f("state"), 0, 40), 'ZIP' => substr($dbbt->f("zip"), 0, 9 ), // Invoice Information 'CUSTREF' => substr($order_number, 0, 12), // Account Data 'ACCT' => $_SESSION['ccdata']['order_payment_number'], 'CVV2' => $_SESSION['ccdata']['credit_card_code'], 'EXPDATE' => ($_SESSION['ccdata']['order_payment_expire_month']) . substr($_SESSION['ccdata']['order_payment_expire_year'], 2 ) ); //build the post string $poststring = ''; foreach($formdata AS $key => $val){ $poststring .= urlencode($key) . "=" . urlencode($val) . "&"; } // strip off trailing ampersand $poststring = substr($poststring, 0, -1); if(PFP_TEST_REQUEST=='TRUE') { $host = 'pilot-payflowpro.verisign.com'; } else { $host = 'payflowpro.verisign.com'; } $headers[] = "X-VPS-Timeout: 30"; $headers[] = "X-VPS-VIT-OS-Name: ".PHP_OS; // Name of your OS $headers[] = "X-VPS-VIT-OS-Version: ".PHP_OS; // OS Version $headers[] = "X-VPS-VIT-Client-Type: PHP/cURL"; // What you are using $headers[] = "X-VPS-VIT-Client-Version: 0.01"; // For your info $headers[] = "X-VPS-VIT-Client-Architecture: x86"; // For your info $headers[] = "X-VPS-VIT-Client-Certification-Id: ".PFP_CLIENT_CERTIFICATION_ID; // get this from Todd @ payflowintegrator@paypal.com $headers[] = "X-VPS-VIT-Integration-Product: ".phpversion()."::cURL"; // For your info, would populate with application name $headers[] = "X-VPS-VIT-Integration-Version: 0.01"; // Application version $headers[] = "X-VPS-Request-ID: " . $request_id; $result = vmConnector::handleCommunication( "https://$host:443/transaction/", $poststring, $headers ); if( !$result ) { $vmLogger->err('The transaction could not be completed.' ); return false; } $result = strstr($result, 'RESULT'); $valArray = explode('&', $result); foreach($valArray as $val) { $valArray2 = explode('=', $val); $pfpro[$valArray2[0]] = $valArray2[1]; } $vmLogger->debug('Beginning to analyse the response from '.$host); $RESULT_CODE = vmGet( $pfpro, 'RESULT' ); $TRANSACTION_ID = vmGet( $pfpro, 'PNREF' ); $RESPMSG = vmGet( $pfpro, 'RESPMSG', '' ); $CVV2MATCH = vmGet( $pfpro, 'CVV2MATCH', '' ); $success = false; switch($RESULT_CODE) { case '0': // Approved - Success! $success = true; $d["order_payment_log"] = $VM_LANG->_('PHPSHOP_PAYMENT_TRANSACTION_SUCCESS').": "; $d["order_payment_log"] .= $RESPMSG; $vmLogger->debug( $d['order_payment_log']); break; default: $d["order_payment_log"] = payflow_pro::getResponseMsg( $RESULT_CODE ); if( !empty( $d["order_payment_log"] )) { $vmLogger->err( $d["order_payment_log"] ); } else { $vmLogger->err( 'An unknown Error occured while processing your Payment Request.'); } break; } // Catch Transaction ID $d["order_payment_trans_id"] = $TRANSACTION_ID; return $success; } /** * Process a previous transaction with Payflow Pro and Capture the Payment * * @param array $d * @return boolean */ function capture_payment( &$d ) { global $vendor_mail, $vendor_currency, $VM_LANG, $vmLogger; $database = new ps_DB(); require_once(CLASSPATH ."connectionTools.class.php"); if( empty($d['order_number'])) { $vmLogger->err("Error: No Order Number provided."); return false; } /*** Get the Configuration File for authorize.net ***/ require_once(CLASSPATH ."payment/".$this->classname.".cfg.php"); // Get the Account Password securely from the database $database->query( "SELECT ".VM_DECRYPT_FUNCTION."(payment_passkey,'".ENCODE_KEY."') as passkey FROM #__{vm}_payment_method WHERE payment_class='".$this->classname."'" ); $transaction = $database->record[0]; if( empty($transaction->passkey)) { $vmLogger->err($VM_LANG->_('PHPSHOP_PAYMENT_ERROR'),false); return false; } $db = new ps_DB; $q = "SELECT * FROM #__{vm}_orders, #__{vm}_order_payment WHERE "; $q .= "order_number='".$d['order_number']."' "; $q .= "AND #__{vm}_orders.order_id=#__{vm}_order_payment.order_id"; $db->query( $q ); if( !$db->next_record() ) { $vmLogger->err("Error: Order not found."); return false; } $expire_date = date( "my", $db->f("order_payment_expire") ); $cvv2_code = $db->f("order_payment_code"); // DECODE Account Number $dbaccount = new ps_DB; $q = "SELECT ".VM_DECRYPT_FUNCTION."(order_payment_number,'".ENCODE_KEY."') AS account_number from #__{vm}_order_payment WHERE order_id='".$db->f("order_id")."'"; $dbaccount->query($q); $dbaccount->next_record(); // Get user billing information $dbbt = new ps_DB; $qt = "SELECT * FROM #__{vm}_user_info WHERE user_id='".$db->f("user_id")."'"; $dbbt->query($qt); $dbbt->next_record(); $user_info_id = $dbbt->f("user_info_id"); if( $user_info_id != $db->f("user_info_id")) { // Get user's alternative shipping information $dbst = new ps_DB; $qt = "SELECT * FROM #__{vm}_user_info WHERE user_info_id='".$db->f("user_info_id")."' AND address_type='ST'"; $dbst->query($qt); $dbst->next_record(); } else { $dbst = $dbbt; } $tempstr = $dbaccount->f('account_number') . $db->f('order_total') . date('YmdGis'); $request_id = md5($tempstr); //Authnet vars to send $formdata = array ( 'PARTNER' => PFP_PARTNER, 'VENDOR' => PFP_VENDOR, 'USER' => PFP_USER, 'PWD' => $transaction->passkey, 'TEST' => PFP_TEST_REQUEST, // Transaction Data 'AMT' => $db->f('order_total'), // amount 'TRXTYPE' => 'D', // transaction type: Delayed Capture 'TENDER' => 'C', // payment method (C = Credit Card) 'CURRENCY' => $vendor_currency, // Customer Name and Billing Address 'NAME' => strtoupper(substr($dbbt->f("first_name"), 0, 15).substr($dbbt->f("last_name"), 0, 15)), 'STREET' => substr($dbbt->f("address_1"), 0, 30), 'CITY' => substr($dbbt->f("city"), 0, 40), 'STATE' => substr($dbbt->f("state"), 0, 40), 'ZIP' => substr($dbbt->f("zip"), 0, 9 ), // Invoice Information 'CUSTREF' => substr($db->f('order_number'), 0, 12), // Account Data 'ORIGID' => $db->f('order_payment_trans_id'), 'ACCT' => $dbaccount->f('account_number'), 'CVV2' => $cvv2_code, 'EXPDATE' => $expire_date ); //build the post string $poststring = ''; foreach($formdata AS $key => $val){ $poststring .= urlencode($key) . "=" . urlencode($val) . "&"; } // strip off trailing ampersand $poststring = substr($poststring, 0, -1); if(PFP_TEST_REQUEST=='TRUE') { $host = 'pilot-payflowpro.verisign.com'; } else { $host = 'payflowpro.verisign.com'; } $headers[] = "X-VPS-Timeout: 30"; $headers[] = "X-VPS-VIT-OS-Name: ".PHP_OS; // Name of your OS $headers[] = "X-VPS-VIT-OS-Version: ".PHP_OS; // OS Version $headers[] = "X-VPS-VIT-Client-Type: PHP/cURL"; // What you are using $headers[] = "X-VPS-VIT-Client-Version: 0.01"; // For your info $headers[] = "X-VPS-VIT-Client-Architecture: x86"; // For your info $headers[] = "X-VPS-VIT-Client-Certification-Id: ".PFP_CLIENT_CERTIFICATION_ID; // get this from Todd @ payflowintegrator@paypal.com $headers[] = "X-VPS-VIT-Integration-Product: ".phpversion()."::cURL"; // For your info, would populate with application name $headers[] = "X-VPS-VIT-Integration-Version: 0.01"; // Application version $headers[] = "X-VPS-Request-ID: " . $request_id; $result = vmConnector::handleCommunication( "https://$host:443/transaction", $poststring, $headers ); if( !$result ) { $vmLogger->err('The transaction could not be completed.' ); return false; } $result = strstr($result, 'RESULT'); $valArray = explode('&', $result); foreach($valArray as $val) { $valArray2 = explode('=', $val); $pfpro[$valArray2[0]] = $valArray2[1]; } $vmLogger->debug('Beginning to analyse the response from '.$host); $RESULT_CODE = vmGet( $pfpro, 'RESULT' ); $TRANSACTION_ID = vmGet( $pfpro, 'PNREF' ); $RESPMSG = vmGet( $pfpro, 'RESPMSG', '' ); $CVV2MATCH = vmGet( $pfpro, 'CVV2MATCH', '' ); $success = false; switch($RESULT_CODE) { case '0': // Approved - Success! $success = true; $d["order_payment_log"] = $VM_LANG->_('PHPSHOP_PAYMENT_TRANSACTION_SUCCESS').": "; $d["order_payment_log"] .= $RESPMSG; $q = "UPDATE #__{vm}_order_payment SET "; $q .="order_payment_log='".$d["order_payment_log"]."',"; $q .="order_payment_trans_id='".$TRANSACTION_ID."' "; $q .="WHERE order_id='".$db->f("order_id")."' "; $db->query( $q ); $vmLogger->debug( $d['order_payment_log']); break; default: $d["order_payment_log"] = payflow_pro::getResponseMsg( $RESULT_CODE ); if( !empty( $d["order_payment_log"] )) { $vmLogger->err( $d["order_payment_log"] ); } else { $vmLogger->err( 'An unknown Error occured while capturing the Payment.'); } break; } return $success; } /** * Voids a previous transaction with Payflow Pro * * @param array $d * @return boolean */ function void_authorization( &$d ) { global $vendor_mail, $vendor_currency, $VM_LANG, $vmLogger; $database = new ps_DB(); require_once(CLASSPATH ."connectionTools.class.php"); if( empty($d['order_number'])) { $vmLogger->err("Error: No Order Number provided."); return false; } /*** Get the Configuration File for authorize.net ***/ require_once(CLASSPATH ."payment/".$this->classname.".cfg.php"); // Get the Account Password securely from the database $database->query( "SELECT ".VM_DECRYPT_FUNCTION."(payment_passkey,'".ENCODE_KEY."') as passkey FROM #__{vm}_payment_method WHERE payment_class='".$this->classname."'" ); $transaction = $database->record[0]; if( empty($transaction->passkey)) { $vmLogger->err($VM_LANG->_('PHPSHOP_PAYMENT_ERROR'),false); return false; } $db = new ps_DB; $q = "SELECT * FROM #__{vm}_orders, #__{vm}_order_payment WHERE "; $q .= "order_number='".$d['order_number']."' "; $q .= "AND #__{vm}_orders.order_id=#__{vm}_order_payment.order_id"; $db->query( $q ); if( !$db->next_record() ) { $vmLogger->err("Error: Order not found."); return false; } $expire_date = date( "my", $db->f("order_payment_expire") ); $cvv2_code = $db->f("order_payment_code"); // DECODE Account Number $dbaccount = new ps_DB; $q = "SELECT ".VM_DECRYPT_FUNCTION."(order_payment_number,'".ENCODE_KEY."') AS account_number from #__{vm}_order_payment WHERE order_id='".$db->f("order_id")."'"; $dbaccount->query($q); $dbaccount->next_record(); // Get user billing information $dbbt = new ps_DB; $qt = "SELECT * FROM #__{vm}_user_info WHERE user_id='".$db->f("user_id")."'"; $dbbt->query($qt); $dbbt->next_record(); $user_info_id = $dbbt->f("user_info_id"); if( $user_info_id != $db->f("user_info_id")) { // Get user's alternative shipping information $dbst = new ps_DB; $qt = "SELECT * FROM #__{vm}_user_info WHERE user_info_id='".$db->f("user_info_id")."' AND address_type='ST'"; $dbst->query($qt); $dbst->next_record(); } else { $dbst = $dbbt; } $tempstr = $dbaccount->f('account_number') . $db->f('order_total') . date('YmdGis'); $request_id = md5($tempstr); //Authnet vars to send $formdata = array ( 'PARTNER' => PFP_PARTNER, 'VENDOR' => PFP_VENDOR, 'USER' => PFP_USER, 'PWD' => $transaction->passkey, 'TEST' => PFP_TEST_REQUEST, // Transaction Data 'AMT' => $db->f('order_total'), // amount 'TRXTYPE' => 'V', // transaction type: Void 'TENDER' => 'C', // payment method (C = Credit Card) 'CURRENCY' => $vendor_currency, // Customer Name and Billing Address 'NAME' => strtoupper(substr($dbbt->f("first_name"), 0, 15).substr($dbbt->f("last_name"), 0, 15)), 'STREET' => substr($dbbt->f("address_1"), 0, 30), 'CITY' => substr($dbbt->f("city"), 0, 40), 'STATE' => substr($dbbt->f("state"), 0, 40), 'ZIP' => substr($dbbt->f("zip"), 0, 9 ), // Invoice Information 'CUSTREF' => substr($db->f('order_number'), 0, 12), // Account Data 'ORIGID' => $db->f('order_payment_trans_id'), 'ACCT' => $dbaccount->f('account_number'), 'CVV2' => $cvv2_code, 'EXPDATE' => $expire_date ); //build the post string $poststring = ''; foreach($formdata AS $key => $val){ $poststring .= urlencode($key) . "=" . urlencode($val) . "&"; } // strip off trailing ampersand $poststring = substr($poststring, 0, -1); if(PFP_TEST_REQUEST=='TRUE') { $host = 'pilot-payflowpro.verisign.com'; } else { $host = 'payflowpro.verisign.com'; } $headers[] = "X-VPS-Timeout: 30"; $headers[] = "X-VPS-VIT-OS-Name: ".PHP_OS; // Name of your OS $headers[] = "X-VPS-VIT-OS-Version: ".PHP_OS; // OS Version $headers[] = "X-VPS-VIT-Client-Type: PHP/cURL"; // What you are using $headers[] = "X-VPS-VIT-Client-Version: 0.01"; // For your info $headers[] = "X-VPS-VIT-Client-Architecture: x86"; // For your info $headers[] = "X-VPS-VIT-Client-Certification-Id: ".PFP_CLIENT_CERTIFICATION_ID; // get this from Todd @ payflowintegrator@paypal.com $headers[] = "X-VPS-VIT-Integration-Product: ".phpversion()."::cURL"; // For your info, would populate with application name $headers[] = "X-VPS-VIT-Integration-Version: 0.01"; // Application version $headers[] = "X-VPS-Request-ID: " . $request_id; $result = vmConnector::handleCommunication( "https://$host:443/transaction", $poststring, $headers ); if( !$result ) { $vmLogger->err('The transaction could not be completed.' ); return false; } $result = strstr($result, 'RESULT'); $valArray = explode('&', $result); foreach($valArray as $val) { $valArray2 = explode('=', $val); $pfpro[$valArray2[0]] = $valArray2[1]; } $vmLogger->debug('Beginning to analyse the response from '.$host); $RESULT_CODE = vmGet( $pfpro, 'RESULT' ); $TRANSACTION_ID = vmGet( $pfpro, 'PNREF' ); $RESPMSG = vmGet( $pfpro, 'RESPMSG', '' ); $CVV2MATCH = vmGet( $pfpro, 'CVV2MATCH', '' ); $success = false; switch($RESULT_CODE) { case '0': // Approved - Success! $success = true; $d["order_payment_log"] = $VM_LANG->_('PHPSHOP_PAYMENT_TRANSACTION_SUCCESS').": "; $d["order_payment_log"] .= $RESPMSG; $q = "UPDATE #__{vm}_order_payment SET "; $q .="order_payment_log='".$d["order_payment_log"]."',"; $q .="order_payment_trans_id='".$TRANSACTION_ID."' "; $q .="WHERE order_id='".$db->f("order_id")."' "; $db->query( $q ); $vmLogger->debug( $d['order_payment_log']); break; default: $d["order_payment_log"] = payflow_pro::getResponseMsg( $RESULT_CODE ); if( !empty( $d["order_payment_log"] )) { $vmLogger->err( $d["order_payment_log"] ); } else { $vmLogger->err( 'An unknown Error occured while voiding the transaction.'); } break; } return $success; } /** * Returns the error / mesage for the response code returned by Payflow Pro * * @param int $response_code * @return string */ function getResponseMsg( $response_code ) { switch ( $response_code ) { case '1': return 'User authentication failed. Error is caused by one or more of the following: a) Login information is incorrect. Verify that USER, VENDOR, PARTNER, and PASSWORD have been entered correctly, b) Invalid Processor information entered. Contact merchant bank to verify. c) Allowed IP Address" security feature implemented. The transaction is coming from an unknown IP address. See PayPal Manager online help for details on how to use Manager to update the allowed IP addresses. c) You are using a test (not active) account to submit a transaction to the live PayPal servers. Change the URL from test-payflow.paypal.com to payflow.paypal.com.'; case '2': return "Invalid tender type. Your merchant bank account does not support the following credit card type that was submitted."; case '3': return 'Invalid transaction type. Transaction type is not appropriate for this transaction. For example, you cannot credit an authorization-only transaction.'; case '4': return 'Invalid amount format. Use the format: “#####.##” Do not include currency symbols or commas.'; case '5': return 'Invalid merchant information. Processor does not recognize your merchant account information. Contact your bank account acquirer to resolve this problem.'; case '6': return 'Invalid or unsupported currency code'; case '7': return 'Field format error. Invalid information entered. See RESPMSG.'; case '8': return 'Not a transaction server'; case '9': return 'Too many parameters or invalid stream'; case '10': return 'Too many line items'; case '11': return 'Client time-out waiting for response'; case '12': return 'Declined. Check the credit card number, expiration date, and transaction information to make sure they were entered correctly. If this does not resolve the problem, have the customer call their card issuing bank to resolve.'; case '13': return 'Referral. Transaction cannot be approved electronically but can be approved with a verbal authorization. Contact your merchant bank to obtain an authorization and submit a manual Voice Authorization transaction.'; case '14': return 'Invalid Client Certification ID. Check the HTTP header. If the tag, X-VPS-VIT-CLIENT-CERTIFICATION-ID, is missing, RESULT code 14 is returned.'; case '19': return 'Original transaction ID not found. The transaction ID you entered for this transaction is not valid. See RESPMSG.'; case '20': return 'Cannot find the customer reference number'; case '22': return 'Invalid ABA number'; case '23': return 'Invalid account number. Check credit card number and re-submit.'; case '24': return 'Invalid expiration date. Check and re-submit.'; case '25': return 'Invalid Host Mapping. You are trying to process a tender type such as Discover Card, but you are not set up with your merchant bank to accept this card type.'; case '26': return 'Invalid vendor account'; case '27': return 'Insufficient partner permissions'; case '28': return 'Insufficient user permissions'; case '29': return 'Invalid XML document. This could be caused by an unrecognized XML tag or a bad XML format that cannot be parsed by the system.'; case '50': return 'Insufficient funds available in account'; case '51': return 'Exceeds per transaction limit'; case '99': return 'General error. See RESPMSG.'; case '100': return 'Transaction type not supported by host'; case '101': return 'Time-out value too small'; case '102': return 'Processor not available'; case '103': return 'Error reading response from host'; case '104': return 'Timeout waiting for processor response. Try your transaction again.'; case '105': return 'Credit error. Make sure you have not already credited this transaction, or that this transaction ID is for a creditable transaction. (For example, you cannot credit an authorization.)'; case '106': return 'Host not available'; case '107': return 'Duplicate suppression time-out'; case '108': return 'Void error. See RESPMSG. Make sure the transaction ID entered has not already been voided. If not, then look at the Transaction Detail screen for this transaction to see if it has settled. (The Batch field is set to a number greater than zero if the transaction has been settled). If the transaction has already settled, your only recourse is a reversal (credit a payment or submit a payment for a credit).'; case '109': return 'Time-out waiting for host response'; case '111': return 'Capture error. Either an attempt to capture a transaction that is not an authorization transaction type, or an attempt to capture an authorization transaction that has already been captured.'; case '112': return 'Failed AVS check. Address and ZIP code do not match. An authorization may still exist on the cardholder’s account.'; case '113': return 'Merchant sale total will exceed the sales cap with current transaction. ACH transactions only.'; case '114': return 'Card Security Code (CSC) Mismatch. An authorization may still exist on the cardholder’s account.'; case '115': return 'System busy, try again later'; case '116': return 'VPS Internal error. Failed to lock terminal number'; case '117': return 'Failed merchant rule check. One or more of the following three failures occurred: An attempt was made to submit a transaction that failed to meet the security settings specified on the PayPal Manager Security Settings page. If the transaction exceeded the Maximum Amount security setting, then no values are returned for AVS or CSC. AVS validation failed. The AVS return value should appear in the RESPMSG. CSC validation failed. The CSC return value should appear in the RESPMSG.'; case '118': return 'Invalid keywords found in string fields'; case '122': return 'Merchant sale total will exceed the credit cap with current transaction. ACH transactions only.'; case '125': return 'Fraud Protection Services Filter — Declined by filters'; case '126': return 'Fraud Protection Services Filter — Flagged for review by filters'; break; } } } administrator/components/com_virtuemart/classes/payment/ps_authorize.cfg.php100644 0 0 770 10772527110 25375 0ustar 0 0 administrator/components/com_virtuemart/classes/payment/ps_authorize.php100644 0 0 64134 11263443355 24707 0ustar 0 0
    _('PHPSHOP_ADMIN_CFG_ENABLE_AUTORIZENET_TESTMODE') ?> _('PHPSHOP_ADMIN_CFG_ENABLE_AUTORIZENET_TESTMODE_EXPLAIN') ?>
    Authorize.net Server Hostname Name of the Authorize.net Server, the requests are sent to. Default Value: secure.authorize.net
    DO NOT CHANGE UNLESS YOU KNOW WHAT YOU'RE DOING.
    _('PHPSHOP_ADMIN_CFG_AUTORIZENET_USERNAME') ?> _('PHPSHOP_ADMIN_CFG_AUTORIZENET_USERNAME_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_AUTORIZENET_KEY') ?> " > _('PHPSHOP_CHANGE_TRANSACTION_KEY') ?>  
    _('PHPSHOP_PAYMENT_CVV2') ?> _('PHPSHOP_PAYMENT_CVV2_TOOLTIP') ?>
    _('PHPSHOP_PAYMENT_AN_RECURRING') ?> _('PHPSHOP_PAYMENT_AN_RECURRING_TOOLTIP') ?>
    _('PHPSHOP_ADMIN_CFG_AUTORIZENET_AUTENTICATIONTYPE') ?> _('PHPSHOP_ADMIN_CFG_AUTORIZENET_AUTENTICATIONTYPE_EXPLAIN') ?>

    _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_SUCC') ?> _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_SUCC_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_FAIL') ?> _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_FAIL_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_AUTORIZENET_RESPCODES') ?> _('PHPSHOP_ADMIN_CFG_AUTORIZENET_RESPCODES_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_AUTORIZENET_EMAIL_MERCHANT') ?> _('PHPSHOP_ADMIN_CFG_AUTORIZENET_EMAIL_MERCHANT_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_AUTORIZENET_EMAIL_CUSTOMER') ?> _('PHPSHOP_ADMIN_CFG_AUTORIZENET_EMAIL_CUSTOMER_EXPLAIN') ?>
    $d['AN_TEST_REQUEST'], "AN_LOGIN" => $d['AN_LOGIN'], "AN_HOSTNAME" => $d['AN_HOSTNAME'], "AN_TYPE" => $d['AN_TYPE'], "AN_CHECK_CARD_CODE" => $d['AN_CHECK_CARD_CODE'], "AN_VERIFIED_STATUS" => $d['AN_VERIFIED_STATUS'], "AN_INVALID_STATUS" => $d['AN_INVALID_STATUS'], "AN_RECURRING" => $d['AN_RECURRING'], "AN_EMAIL_MERCHANT" => $d['AN_EMAIL_MERCHANT'], "AN_EMAIL_CUSTOMER" => $d['AN_EMAIL_CUSTOMER'], "AN_SHOW_ERROR_CODE" => $d['AN_SHOW_ERROR_CODE'] ); $config = " $value ) { $config .= "define ('$key', '$value');\n"; } $config .= "?>"; if ($fp = fopen(CLASSPATH ."payment/".__CLASS__.".cfg.php", "w")) { fputs($fp, $config, strlen($config)); fclose ($fp); return true; } else { return false; } } /************************************************************************** ** name: process_payment() ** created by: Soeren ** description: process transaction with authorize.net ** parameters: $order_number, the number of the order, we're processing here ** $order_total, the total $ of the order ** returns: ***************************************************************************/ function process_payment($order_number, $order_total, &$d) { global $vendor_mail, $vendor_currency, $VM_LANG, $vmLogger; $database = new ps_DB; $ps_vendor_id = $_SESSION["ps_vendor_id"]; $auth = $_SESSION['auth']; $ps_checkout = new ps_checkout; // Get the Configuration File for authorize.net require_once(CLASSPATH ."payment/".__CLASS__.".cfg.php"); // connector class require_once(CLASSPATH ."connectionTools.class.php"); // Get the Transaction Key securely from the database $database->query( "SELECT ".VM_DECRYPT_FUNCTION."(payment_passkey,'".ENCODE_KEY."') as passkey FROM #__{vm}_payment_method WHERE payment_class='".__CLASS__."' AND payment_enabled = 'Y'" ); $transaction = $database->record[0]; if( empty($transaction->passkey)) { $vmLogger->err( $VM_LANG->_('PHPSHOP_PAYMENT_ERROR',false).'. Technical Note: The required transaction key is empty! The payment method settings must be reviewed.' ); return false; } // Get user billing information $dbbt = new ps_DB; $qt = "SELECT * FROM #__{vm}_user_info WHERE user_id=".$auth["user_id"]." AND address_type='BT'"; $dbbt->query($qt); $dbbt->next_record(); $user_info_id = $dbbt->f("user_info_id"); if( $user_info_id != $d["ship_to_info_id"]) { // Get user billing information $dbst = new ps_DB; $qt = "SELECT * FROM #__{vm}_user_info WHERE user_info_id='".$d["ship_to_info_id"]."' AND address_type='ST'"; $dbst->query($qt); $dbst->next_record(); } else { $dbst = $dbbt; } // Option to send email to merchant from gateway if (AN_EMAIL_MERCHANT == 'NO') { $vendor_mail = ""; } if (AN_EMAIL_CUSTOMER == 'YES') { $email_customer = "TRUE"; } else { $email_customer = "FALSE"; } //Authnet vars to send $formdata = array ( 'x_version' => '3.1', 'x_login' => AN_LOGIN, 'x_tran_key' => $transaction->passkey, 'x_test_request' => strtoupper( AN_TEST_REQUEST ), // Gateway Response Configuration 'x_delim_data' => 'TRUE', 'x_delim_char' => '|', 'x_relay_response' => 'FALSE', // Customer Name and Billing Address 'x_first_name' => substr($dbbt->f("first_name"), 0, 50), 'x_last_name' => substr($dbbt->f("last_name"), 0, 50), 'x_company' => substr($dbbt->f("company"), 0, 50), 'x_address' => substr($dbbt->f("address_1"), 0, 60), 'x_city' => substr($dbbt->f("city"), 0, 40), 'x_state' => substr($dbbt->f("state"), 0, 40), 'x_zip' => substr($dbbt->f("zip"), 0, 20), 'x_country' => substr($dbbt->f("country"), 0, 60), 'x_phone' => substr($dbbt->f("phone_1"), 0, 25), 'x_fax' => substr($dbbt->f("fax"), 0, 25), // Customer Shipping Address 'x_ship_to_first_name' => substr($dbst->f("first_name"), 0, 50), 'x_ship_to_last_name' => substr($dbst->f("last_name"), 0, 50), 'x_ship_to_company' => substr($dbst->f("company"), 0, 50), 'x_ship_to_address' => substr($dbst->f("address_1"), 0, 60), 'x_ship_to_city' => substr($dbst->f("city"), 0, 40), 'x_ship_to_state' => substr($dbst->f("state"), 0, 40), 'x_ship_to_zip' => substr($dbst->f("zip"), 0, 20), 'x_ship_to_country' => substr($dbst->f("country"), 0, 60), // Additional Customer Data 'x_cust_id' => $auth['user_id'], 'x_customer_ip' => $_SERVER["REMOTE_ADDR"], 'x_customer_tax_id' => $dbbt->f("tax_id"), // Email Settings 'x_email' => $dbbt->f("user_email"), 'x_email_customer' => $email_customer, 'x_merchant_email' => $vendor_mail, // Invoice Information 'x_invoice_num' => substr($order_number, 0, 20), 'x_description' => $VM_LANG->_('PHPSHOP_ORDER_PRINT_PO_LBL'), // Transaction Data 'x_amount' => $order_total, 'x_currency_code' => $vendor_currency, 'x_method' => 'CC', 'x_type' => AN_TYPE, 'x_recurring_billing' => AN_RECURRING, 'x_card_num' => $_SESSION['ccdata']['order_payment_number'], 'x_card_code' => $_SESSION['ccdata']['credit_card_code'], 'x_exp_date' => ($_SESSION['ccdata']['order_payment_expire_month']) . ($_SESSION['ccdata']['order_payment_expire_year']), // Level 2 data 'x_po_num' => substr($order_number, 0, 20), 'x_tax' => substr($d['order_tax'], 0, 15), 'x_tax_exempt' => "FALSE", 'x_freight' => $d['order_shipping'], 'x_duty' => 0 ); //build the post string $poststring = ''; foreach($formdata AS $key => $val){ $poststring .= urlencode($key) . "=" . urlencode($val) . "&"; } // strip off trailing ampersand $poststring = substr($poststring, 0, -1); if (defined('AN_HOSTNAME')) { $host = AN_HOSTNAME; } else { $host = 'secure.authorize.net'; } $result = vmConnector::handleCommunication( "https://$host:443/gateway/transact.dll", $poststring ); if( !$result ) { $vmLogger->err('The transaction could not be completed.' ); return false; } $c_mccomb = '|'; $resultmm = ''; $foundmm = 0; $iimm = 0; for($imm=0;$immdebug('Beginning to analyse the response from '.$host); // Approved - Success! if ($response[0] == '1') { $d["order_payment_log"] = $VM_LANG->_('PHPSHOP_PAYMENT_TRANSACTION_SUCCESS').": "; $d["order_payment_log"] .= $response[3]; $vmLogger->debug( $d['order_payment_log']); // Catch Transaction ID $d["order_payment_trans_id"] = $response[6]; return True; } // Payment Declined elseif ($response[0] == '2') { if (AN_SHOW_ERROR_CODE == 'YES') { $vmLogger->err( $response[0] . "-" . $response[1] . "-" . $response[2] . "-" . $response[5] . "-" . $response[38] . "-" . $response[39] . "-" . $response[3] ); } else { $vmLogger->err( $response[3] ); } $d["order_payment_log"] = $response[3]; // Catch Transaction ID $d["order_payment_trans_id"] = $response[6]; return False; } // Transaction Error elseif ($response[0] == '3') { if (AN_SHOW_ERROR_CODE == 'YES') { $vmLogger->err( $response[0] . "-" . $response[1] . "-" . $response[2] . "-" . $response[5] . "-" . $response[38] . "-" . $response[39] . "-" . $response[3] ); } else { $vmLogger->err( $response[3] ); } $d["order_payment_log"] = $response[3]; // Catch Transaction ID $d["order_payment_trans_id"] = $response[6]; return False; } else if ($response[0] == '4') { $d["order_payment_log"] = $VM_LANG->_('PHPSHOP_PAYMENT_TRANSACTION_SUCCESS').": "; $d["order_payment_log"] .= $response[3]; $vmLogger->debug( $d['order_payment_log']); // Catch Transaction ID $d["order_payment_trans_id"] = $response[6]; return True; } } /************************************************************************** ** name: capture_payment() ** created by: Soeren ** description: Process a previous transaction with authorize.net, Capture the Payment ** parameters: $order_number, the number of the order, we're processing here ** returns: ***************************************************************************/ function capture_payment( &$d ) { global $vendor_mail, $vendor_currency, $VM_LANG, $vmLogger; $database = new ps_DB(); require_once(CLASSPATH ."connectionTools.class.php"); /*CERTIFICATION Visa Test Account 4007000000027 Amex Test Account 370000000000002 Master Card Test Account 6011000000000012 Discover Test Account 5424000000000015 $host = "certification.authorize.net"; $port = 443; $path = "/gateway/transact.dll"; */ if( empty($d['order_number'])) { $vmLogger->err("Error: No Order Number provided."); return false; } /*** Get the Configuration File for authorize.net ***/ require_once(CLASSPATH ."payment/".__CLASS__.".cfg.php"); // Get the Transaction Key securely from the database $database->query( "SELECT ".VM_DECRYPT_FUNCTION."(payment_passkey,'".ENCODE_KEY."') as passkey FROM #__{vm}_payment_method WHERE payment_class='".__CLASS__."' AND payment_enabled = 'Y'" ); $transaction = $database->record[0]; if( empty($transaction->passkey)) { $vmLogger->err($VM_LANG->_('PHPSHOP_PAYMENT_ERROR'),false); return false; } $db = new ps_DB; $q = "SELECT * FROM #__{vm}_orders, #__{vm}_order_payment WHERE "; $q .= "order_number='".$d['order_number']."' "; $q .= "AND #__{vm}_orders.order_id=#__{vm}_order_payment.order_id"; $db->query( $q ); if( !$db->next_record() ) { $vmLogger->err("Error: Order not found."); return false; } $expire_date = date( "my", $db->f("order_payment_expire") ); // DECODE Account Number $dbaccount = new ps_DB; $q = "SELECT ".VM_DECRYPT_FUNCTION."(order_payment_number,'".ENCODE_KEY."') AS account_number from #__{vm}_order_payment WHERE order_id='".$db->f("order_id")."'"; $dbaccount->query($q); $dbaccount->next_record(); // Get user billing information $dbbt = new ps_DB; $qt = "SELECT * FROM #__{vm}_user_info WHERE user_id='".$db->f("user_id")."'"; $dbbt->query($qt); $dbbt->next_record(); $user_info_id = $dbbt->f("user_info_id"); if( $user_info_id != $db->f("user_info_id")) { // Get user's alternative shipping information $dbst = new ps_DB; $qt = "SELECT * FROM #__{vm}_user_info WHERE user_info_id='".$db->f("user_info_id")."' AND address_type='ST'"; $dbst->query($qt); $dbst->next_record(); } else { $dbst = $dbbt; } //Authnet vars to send $formdata = array ( 'x_version' => '3.1', 'x_login' => AN_LOGIN, 'x_tran_key' => $transaction->passkey, 'x_test_request' => strtoupper( AN_TEST_REQUEST ), // Gateway Response Configuration 'x_delim_data' => 'TRUE', 'x_delim_char' => '|', 'x_relay_response' => 'FALSE', // Customer Name and Billing Address 'x_first_name' => substr($dbbt->f("first_name"), 0, 50), 'x_last_name' => substr($dbbt->f("last_name"), 0, 50), 'x_company' => substr($dbbt->f("company"), 0, 50), 'x_address' => substr($dbbt->f("address_1"), 0, 60), 'x_city' => substr($dbbt->f("city"), 0, 40), 'x_state' => substr($dbbt->f("state"), 0, 40), 'x_zip' => substr($dbbt->f("zip"), 0, 20), 'x_country' => substr($dbbt->f("country"), 0, 60), 'x_phone' => substr($dbbt->f("phone_1"), 0, 25), 'x_fax' => substr($dbbt->f("fax"), 0, 25), // Customer Shipping Address 'x_ship_to_first_name' => substr($dbst->f("first_name"), 0, 50), 'x_ship_to_last_name' => substr($dbst->f("last_name"), 0, 50), 'x_ship_to_company' => substr($dbst->f("company"), 0, 50), 'x_ship_to_address' => substr($dbst->f("address_1"), 0, 60), 'x_ship_to_city' => substr($dbst->f("city"), 0, 40), 'x_ship_to_state' => substr($dbst->f("state"), 0, 40), 'x_ship_to_zip' => substr($dbst->f("zip"), 0, 20), 'x_ship_to_country' => substr($dbst->f("country"), 0, 60), // Additional Customer Data 'x_cust_id' => $db->f('user_id'), 'x_customer_ip' => $dbbt->f("ip_address"), 'x_customer_tax_id' => $dbbt->f("tax_id"), // Email Settings 'x_email' => $dbbt->f("email"), 'x_email_customer' => 'False', 'x_merchant_email' => $vendor_mail, // Invoice Information 'x_invoice_num' => substr($d['order_number'], 0, 20), 'x_description' => '', // Transaction Data 'x_amount' => $db->f("order_total"), 'x_currency_code' => $vendor_currency, 'x_method' => 'CC', 'x_type' => 'PRIOR_AUTH_CAPTURE', 'x_recurring_billing' => AN_RECURRING, 'x_card_num' => $dbaccount->f("account_number"), 'x_card_code' => $db->f('order_payment_code'), 'x_exp_date' => $expire_date, 'x_trans_id' => $db->f("order_payment_trans_id"), // Level 2 data 'x_po_num' => substr($d['order_number'], 0, 20), 'x_tax' => substr($db->f('order_tax'), 0, 15), 'x_tax_exempt' => "FALSE", 'x_freight' => $db->f('order_shipping'), 'x_duty' => 0 ); //build the post string $poststring = ''; foreach($formdata AS $key => $val){ $poststring .= urlencode($key) . "=" . urlencode($val) . "&"; } // strip off trailing ampersand $poststring = substr($poststring, 0, -1); if (defined('AN_HOSTNAME')) { $host = AN_HOSTNAME; } else { $host = 'secure.authorize.net'; } $result = vmConnector::handleCommunication( "https://$host:443/gateway/transact.dll", $poststring ); if( !$result ) { $vmLogger->err('We\'re sorry, but an error has occured when we tried to communicate with the authorize.net server. Please try again later, thank you.' ); return false; } $response = explode("|", $result); // Approved - Success! if ($response[0] == '1') { $d["order_payment_log"] = $VM_LANG->_('PHPSHOP_PAYMENT_TRANSACTION_SUCCESS').": "; $d["order_payment_log"] .= $response[3]; // Catch Transaction ID $d["order_payment_trans_id"] = $response[6]; $q = "UPDATE #__{vm}_order_payment SET "; $q .="order_payment_log='".$d["order_payment_log"]."',"; $q .="order_payment_trans_id='".$d["order_payment_trans_id"]."' "; $q .="WHERE order_id='".$db->f("order_id")."' "; $db->query( $q ); return True; } // Payment Declined elseif ($response[0] == '2') { $vmLogger->err($response[3]); $d["order_payment_log"] = $response[3]; // Catch Transaction ID $d["order_payment_trans_id"] = $response[6]; return False; } // Transaction Error elseif ($response[0] == '3') { $vmLogger->err($response[3]); $d["order_payment_log"] = $response[3]; // Catch Transaction ID $d["order_payment_trans_id"] = $response[6]; return False; } } } administrator/components/com_virtuemart/classes/payment/ps_cashondel.cfg.php100644 0 0 2062 10732276304 25341 0ustar 0 0 administrator/components/com_virtuemart/classes/payment/ps_cashondel.php100644 0 0 14635 11173717120 24630 0ustar 0 0 classname.".cfg.php"); echo $VM_LANG->_('PHPSHOP_SPEC_CASH_ON_DELIVER_RATES'); ?>
    _('PHPSHOP_ORDER_PRINT_TOTAL'); ?> _('PHPSHOP_PAYMENT_METHOD_LIST_FEE'); ?>
    5000 =>
    10000 =>
    20000 =>
    30000 =>
    40000 =>
    50000 =>
    100000 =>
    classname.".cfg.php" ); } /** * Returns the "is_readable" status of the configuration file * @param void * @returns boolean True when the configuration file is writeable, false when not */ function configfile_readable() { return is_readable( CLASSPATH."payment/".$this->classname.".cfg.php" ); } /** * Writes the configuration file for this payment method * @param array An array of objects * @returns boolean True when writing was successful */ function write_configuration( &$d ) { $my_config_array = array("CASH_ON_DEL_5000" => $d['CASH_ON_DEL_5000'], "CASH_ON_DEL_10000" => $d['CASH_ON_DEL_10000'], "CASH_ON_DEL_20000" => $d['CASH_ON_DEL_20000'], "CASH_ON_DEL_30000" => $d['CASH_ON_DEL_30000'], "CASH_ON_DEL_40000" => $d['CASH_ON_DEL_40000'], "CASH_ON_DEL_50000" => $d['CASH_ON_DEL_50000'], "CASH_ON_DEL_100000" => $d['CASH_ON_DEL_100000'], ); $config = " $value ) { $config .= "define ('$key', '$value');\n"; } $config .= "?>"; if ($fp = fopen(CLASSPATH ."payment/".$this->classname.".cfg.php", "w")) { fputs($fp, $config, strlen($config)); fclose ($fp); return true; } else return false; } function get_payment_rate($sum) { /*** Get the Configuration File ***/ require_once(CLASSPATH ."payment/".$this->classname.".cfg.php"); if ($sum < 5000) return -(CASH_ON_DEL_5000); elseif ($sum < 10000) return -(CASH_ON_DEL_10000); elseif ($sum < 20000) return -(CASH_ON_DEL_20000); elseif ($sum < 30000) return -(CASH_ON_DEL_30000); elseif ($sum < 40000) return -(CASH_ON_DEL_40000); elseif ($sum < 50000) return -(CASH_ON_DEL_50000); elseif ($sum < 100000) return -(CASH_ON_DEL_100000); else return -(CASH_ON_DEL_100000); // return -($sum * 0.10); } /************************************************************************** ** name: process_payment() ** returns: ***************************************************************************/ function process_payment($order_number, $order_total, &$d) { //echo "process_payment $order_number $order_total "; return true; } } administrator/components/com_virtuemart/classes/payment/ps_echeck.cfg.php100644 0 0 1731 10732276304 24625 0ustar 0 0 administrator/components/com_virtuemart/classes/payment/ps_echeck.php100644 0 0 40005 11263443355 24106 0ustar 0 0 classname.".cfg.php"); ?>
    _('PHPSHOP_ADMIN_CFG_ENABLE_AUTORIZENET_TESTMODE') ?> _('PHPSHOP_ADMIN_CFG_ENABLE_AUTORIZENET_TESTMODE_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_ECHECK_USERNAME') ?> _('PHPSHOP_ADMIN_CFG_ECHECK_USERNAME_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_ECHECK_KEY') ?> " > _('PHPSHOP_ADMIN_CFG_ECHECK_KEY_EXPLAIN') ?>
    _('PHPSHOP_PAYMENT_AN_RECURRING') ?> _('PHPSHOP_PAYMENT_AN_RECURRING_TOOLTIP') ?>
    _('PHPSHOP_ADMIN_CFG_ECHECK_AUTENTICATIONTYPE') ?> _('PHPSHOP_ADMIN_CFG_ECHECK_AUTENTICATIONTYPE_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_ECHECK_TRANSACTIONTYPE') ?> _('PHPSHOP_ADMIN_CFG_ECHECK_TRANSACTIONTYPE_EXPLAIN') ?>
    classname.".cfg.php" ); } /** * Returns the "is_readable" status of the configuration file * @param void * @returns boolean True when the configuration file is writeable, false when not */ function configfile_readable() { return is_readable( CLASSPATH."payment/".$this->classname.".cfg.php" ); } /** * Writes the configuration file for this payment method * @param array An array of objects * @returns boolean True when writing was successful */ function write_configuration( &$d ) { $my_config_array = array("ECK_TEST_REQUEST" => $d['ECK_TEST_REQUEST'], "ECK_LOGIN" => $d['ECK_LOGIN'], "ECK_TYPE" => $d['ECK_TYPE'], "ECK_ECHECK_TYPE" => $d['ECK_ECHECK_TYPE'], "ECK_RECURRING" => $d['ECK_RECURRING'] ); $config = " $value ) { $config .= "define ('$key', '$value');\n"; } $config .= "?>"; if ($fp = fopen(CLASSPATH ."payment/".$this->classname.".cfg.php", "w")) { fputs($fp, $config, strlen($config)); fclose ($fp); return true; } else return false; } /************************************************************************** ** name: process_payment() ** created by: jep ** description: process transaction authorize.net ** parameters: $order_number, the number of the order, we're processing here ** $order_total, the total $ of the order ** returns: ***************************************************************************/ function process_payment($order_number, $order_total, &$d) { global $vendor_mail, $vendor_currency, $VM_LANG, $vmLogger; $database = new ps_DB(); $ps_vendor_id = $_SESSION["ps_vendor_id"]; $auth = $_SESSION['auth']; $ps_checkout = new ps_checkout; /*** Get the Configuration File for authorize.net ***/ require_once(CLASSPATH ."payment/".$this->classname.".cfg.php"); // Get the Transaction Key securely from the database $database->query( "SELECT ".VM_DECRYPT_FUNCTION."(payment_passkey,'".ENCODE_KEY."') as passkey FROM #__{vm}_payment_method WHERE payment_class='".$this->classname."'" ); $transaction = $database->record[0]; if( empty($transaction->passkey)) { $vmLogger->err($VM_LANG->_('PHPSHOP_PAYMENT_ERROR'),false); return false; } // Get user billing information $dbbt = new ps_DB; $qt = "SELECT * FROM #__{vm}_user_info WHERE user_id='".$auth["user_id"]."' AND address_type='BT'"; $dbbt->query($qt); $dbbt->next_record(); $user_info_id = $dbbt->f("user_info_id"); if( $user_info_id != $d["ship_to_info_id"]) { // Get user billing information $dbst = new ps_DB; $qt = "SELECT * FROM #__{vm}_user_info WHERE user_info_id='".$d["ship_to_info_id"]."' AND address_type='ST'"; $dbst->query($qt); $dbst->next_record(); } else { $dbst = $dbbt; } $host = "secure.authorize.net"; $port = 443; $path = "/gateway/transact.dll"; //Authnet vars to send $formdata = array ( 'x_version' => '3.1', 'x_login' => ECK_LOGIN, 'x_tran_key' => $transaction->passkey, 'x_test_request' => ECK_TEST_REQUEST, 'x_delim_data' => 'TRUE', 'x_delim_char' => '|', 'x_relay_response' => 'FALSE', 'x_first_name' => substr($dbbt->f("first_name"), 0, 50), 'x_last_name' => substr($dbbt->f("last_name"), 0, 50), 'x_company' => substr($dbbt->f("company"), 0, 50), 'x_address' => substr($dbbt->f("address_1"), 0, 60), 'x_city' => substr($dbbt->f("city"), 0, 40), 'x_state' => substr($dbbt->f("state"), 0, 40), 'x_zip' => substr($dbbt->f("zip"), 0, 20), 'x_country' => substr($dbbt->f("country"), 0, 60), 'x_phone' => substr($dbbt->f("phone_1"), 0, 25), 'x_fax' => substr($dbbt->f("fax"), 0, 25), 'x_ship_to_first_name' => substr($dbst->f("first_name"), 0, 50), 'x_ship_to_last_name' => substr($dbst->f("last_name"), 0, 50), 'x_ship_to_company' => substr($dbst->f("company"), 0, 50), 'x_ship_to_address' => substr($dbst->f("address_1"), 0, 60), 'x_ship_to_city' => substr($dbst->f("city"), 0, 40), 'x_ship_to_state' => substr($dbst->f("state"), 0, 40), 'x_ship_to_zip' => substr($dbst->f("zip"), 0, 20), 'x_ship_to_country' => substr($dbst->f("country"), 0, 60), 'x_cust_id' => $auth['user_id'], 'x_customer_ip' => $_SERVER["REMOTE_ADDR"], 'x_customer_tax_id' => $dbbt->f("tax_id"), 'x_email' => $dbbt->f("email"), 'x_email_customer' => 'True', 'x_merchant_email' => $vendor_mail, 'x_invoice_num' => substr($order_number, 0, 20), 'x_description' => '', 'x_amount' => $order_total, 'x_currency_code' => $vendor_currency, 'x_method' => 'ECHECK', 'x_type' => ECK_TYPE, 'x_echeck_type' => ECK_ECHECK_TYPE, 'x_recurring_billing' => ECK_RECURRING, 'x_bank_aba_code' => $dbbt->f("bank_iban"), 'x_bank_acct_num' => $dbbt->f("bank_account_nr"), 'x_bank_acct_type' => $dbbt->f("bank_account_type"), 'x_bank_name' => $dbbt->f("bank_name"), 'x_bank_acct_name' => $dbbt->f("bank_account_holder"), // Level 2 data 'x_po_num' => substr($order_number, 0, 20), 'x_tax' => substr($d['order_tax'], 0, 15), 'x_tax_exempt' => "FALSE", 'x_freight' => $d['order_shipping'], 'x_duty' => 0 ); //build the post string $poststring = ''; foreach($formdata AS $key => $val){ $poststring .= urlencode($key) . "=" . urlencode($val) . "&"; } // strip off trailing ampersand $poststring = substr($poststring, 0, -1); if( function_exists( "curl_init" )) { $CR = curl_init(); curl_setopt($CR, CURLOPT_URL, "https://".$host.$path); curl_setopt($CR, CURLOPT_POST, 1); curl_setopt($CR, CURLOPT_FAILONERROR, true); curl_setopt($CR, CURLOPT_POSTFIELDS, $poststring); curl_setopt($CR, CURLOPT_RETURNTRANSFER, 1); // No PEER certificate validation...as we don't have // a certificate file for it to authenticate the host www.ups.com against! curl_setopt($CR, CURLOPT_SSL_VERIFYPEER, 0); //curl_setopt($CR, CURLOPT_SSLCERT , "/usr/locale/xxxx/clientcertificate.pem"); $result = curl_exec( $CR ); $error = curl_error( $CR ); if( !empty( $error )) { $vmLogger->err( curl_error( $CR ) ); $html = "
    ".$VM_LANG->_('PHPSHOP_PAYMENT_INTERNAL_ERROR')." authorize.net"; return false; } else { //echo $result; exit(); } curl_close( $CR ); } else { $fp = fsockopen("ssl://".$host, $port, $errno, $errstr, $timeout = 60); if(!$fp){ //error tell us $vmLogger->err( "$errstr ($errno)" ); } else { //send the server request fputs($fp, "POST $path HTTP/1.1\r\n"); fputs($fp, "Host: $host\r\n"); fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n"); fputs($fp, "Content-length: ".strlen($poststring)."\r\n"); fputs($fp, "Connection: close\r\n\r\n"); fputs($fp, $poststring . "\r\n\r\n"); //Get the response header from the server $str = ''; while(!feof($fp) && !stristr($str, 'content-length')) { $str = fgets($fp, 4096); } // If didnt get content-lenght, something is wrong, return false. if (!stristr($str, 'content-length')) { return false; } $data = ""; while (!feof($fp)) { $data .= fgets ($fp, 1024); } $result = trim( $data ); /* // Get length of data to be received. $length = trim(substr($str,strpos($str,'content-length') + 15)); // Get buffer (blank data before real data) fgets($fp, 4096); // Get real data $data = fgets($fp, $length); fclose($fp);*/ } } $response = explode("|", $result); // Approved - Success! if ($response[0] == '1') { $d["order_payment_log"] = $VM_LANG->_('PHPSHOP_PAYMENT_TRANSACTION_SUCCESS').": "; $d["order_payment_log"] .= $response[3]; return True; } // Payment Declined elseif ($response[0] == '2') { $vmLogger->err($response[3]); $d["order_payment_log"] = $response[3]; return False; } // Transaction Error elseif ($response[0] == '3') { $vmLogger->err($response[3]); $d["order_payment_log"] = $response[3]; return False; } } } administrator/components/com_virtuemart/classes/payment/ps_epay.cfg.php100644 0 0 2437 11014353306 24335 0ustar 0 0 administrator/components/com_virtuemart/classes/payment/ps_epay.php100644 0 0 73703 11263442304 23626 0ustar 0 0
    _('PHPSHOP_ADMIN_CFG_EPAY_MERCHANTNUMBER');?> _('PHPSHOP_ADMIN_CFG_EPAY_MERCHANTNUMBER_EXPLAIN');?>
    _('PHPSHOP_ADMIN_CFG_PAYPAL_STATUS_SUCCESS');?> _('PHPSHOP_ADMIN_CFG_PAYPAL_STATUS_SUCCESS_EXPLAIN');?>
    _('PHPSHOP_ADMIN_CFG_PAYPAL_STATUS_FAILED');?> _('PHPSHOP_ADMIN_CFG_PAYPAL_STATUS_FAILED_EXPLAIN');?>
    _('PHPSHOP_ADMIN_CFG_EPAY_CARDTYPES');?> value="1" onclick="javascript:enableDisableAll();">_('PHPSHOP_ALL');?>
    value="1">DANKORT
    value="1">VISA DANKORT
    value="1">VISA ELECTRON
    value="1">MASTERCARD (DK)
    value="1">MASTERCARD
    value="1">VISA ELECTRON (DK)
    value="1">JCB
    value="1">DINERS (DK)
    value="1">MAESTRO (DK)
    value="1">AMERICAN EXPRESS (DK)
    value="1">DINERS
    value="1">JCB Secure (3D-Secure)
    value="1">AMERICAN EXPRESS
    value="1">MAESTRO
    value="1">FORBRUGSFORENINGEN
    value="1">EWIRE
    value="1">VISA
    value="1">IKANO
    value="1">NORDEA
    value="1">DANSKE BANK
    _('PHPSHOP_ADMIN_CFG_EPAY_CARDTYPES_EXPLAIN');?>
    _('PHPSHOP_ADMIN_CFG_EPAY_LANGUAGE');?> _('PHPSHOP_ADMIN_CFG_EPAY_LANGUAGE_EXPLAIN');?>
    _('PHPSHOP_ADMIN_CFG_EPAY_INSTANT_CAPTURE');?> _('PHPSHOP_ADMIN_CFG_EPAY_INSTANT_CAPTURE_EXPLAIN');?>
    _('PHPSHOP_ADMIN_CFG_EPAY_GROUP');?> _('PHPSHOP_ADMIN_CFG_EPAY_GROUP_EXPLAIN');?>
    MD5 _('PHPSHOP_ADMIN_CFG_EPAY_MD5_TYPE_EXPLAIN');?>
    _('PHPSHOP_ADMIN_CFG_EPAY_MD5_KEY');?> _('PHPSHOP_ADMIN_CFG_EPAY_MD5_KEY_EXPLAIN');?>
    _('PHPSHOP_ADMIN_CFG_EPAY_AUTHSMS');?> _('PHPSHOP_ADMIN_CFG_EPAY_AUTHSMS_EXPLAIN');?>
    _('PHPSHOP_ADMIN_CFG_EPAY_AUTHEMAIL');?> _('PHPSHOP_ADMIN_CFG_EPAY_AUTHEMAIL_EXPLAIN');?>
    _('PHPSHOP_ADMIN_CFG_EPAY_WINDOWSTATE');?>  
    _('PHPSHOP_ADMIN_CFG_EPAY_3DSECURE');?>  
    _('PHPSHOP_ADMIN_CFG_EPAY_CALLBACK');?> _('PHPSHOP_ADMIN_CFG_EPAY_CALLBACK_EXPLAIN');?>
    _('PHPSHOP_ADMIN_CFG_EPAY_ADDFEE');?> _('PHPSHOP_ADMIN_CFG_EPAY_ADDFEE_EXPLAIN');?>
    _('PHPSHOP_ADMIN_CFG_EPAY_SUBSCRIPTION');?> _('PHPSHOP_ADMIN_CFG_EPAY_SUBSCRIPTION_EXPLAIN');?>
    _('PHPSHOP_ADMIN_CFG_EPAY_AUTHEMAIL');?> _('PHPSHOP_ADMIN_CFG_EPAY_AUTHEMAIL_EXPLAIN');?>


    _('PHPSHOP_ADMIN_CFG_EPAY_EXTRAINFO_RESET_EXPLAIN');?>



    $d['EPAY_MERCHANTNUMBER'], "EPAY_LANGUAGE" => $d['EPAY_LANGUAGE'], "EPAY_CALLBACK" => $d['EPAY_CALLBACK'], "EPAY_VERIFIED_STATUS" => $d['EPAY_VERIFIED_STATUS'], "EPAY_INVALID_STATUS" => $d['EPAY_INVALID_STATUS'], "EPAY_INSTANT_CAPTURE" => $d['EPAY_INSTANT_CAPTURE'], "EPAY_GROUP" => $d['EPAY_GROUP'], "EPAY_MD5_TYPE" => $d['EPAY_MD5_TYPE'], "EPAY_MD5_KEY" => $d['EPAY_MD5_KEY'], "EPAY_AUTH_SMS" => $d['EPAY_AUTH_SMS'], "EPAY_AUTH_MAIL" => $d['EPAY_AUTH_MAIL'], "EPAY_WINDOW_STATE" => $d['EPAY_WINDOW_STATE'], "EPAY_3DSECURE" => $d['EPAY_3DSECURE'], "EPAY_SUBSCRIPTION" => $d['EPAY_SUBSCRIPTION'], "EPAY_ADDFEE" => $d['EPAY_ADDFEE'], "EPAY_CARDTYPES_0" => $d['EPAY_CARDTYPES_0'], "EPAY_CARDTYPES_1" => $d['EPAY_CARDTYPES_1'], "EPAY_CARDTYPES_2" => $d['EPAY_CARDTYPES_2'], "EPAY_CARDTYPES_3" => $d['EPAY_CARDTYPES_3'], "EPAY_CARDTYPES_4" => $d['EPAY_CARDTYPES_4'], "EPAY_CARDTYPES_5" => $d['EPAY_CARDTYPES_5'], "EPAY_CARDTYPES_6" => $d['EPAY_CARDTYPES_6'], "EPAY_CARDTYPES_7" => $d['EPAY_CARDTYPES_7'], "EPAY_CARDTYPES_8" => $d['EPAY_CARDTYPES_8'], "EPAY_CARDTYPES_9" => $d['EPAY_CARDTYPES_9'], "EPAY_CARDTYPES_10" => $d['EPAY_CARDTYPES_10'], "EPAY_CARDTYPES_12" => $d['EPAY_CARDTYPES_12'], "EPAY_CARDTYPES_13" => $d['EPAY_CARDTYPES_13'], "EPAY_CARDTYPES_14" => $d['EPAY_CARDTYPES_14'], "EPAY_CARDTYPES_15" => $d['EPAY_CARDTYPES_15'], "EPAY_CARDTYPES_16" => $d['EPAY_CARDTYPES_16'], "EPAY_CARDTYPES_17" => $d['EPAY_CARDTYPES_17'], "EPAY_CARDTYPES_18" => $d['EPAY_CARDTYPES_18'], "EPAY_CARDTYPES_19" => $d['EPAY_CARDTYPES_19'], "EPAY_CARDTYPES_21" => $d['EPAY_CARDTYPES_21'], "EPAY_CARDTYPES_22" => $d['EPAY_CARDTYPES_22'], "EPAY_AUTHEMAILCUSTOMER" => $d['EPAY_AUTHEMAILCUSTOMER'] ); $config = " $value ) { $config .= "define ('$key', '$value');\n"; } $config .= "?>"; if ($fp = fopen(CLASSPATH ."payment/".__CLASS__.".cfg.php", "w")) { fputs($fp, $config, strlen($config)); fclose ($fp); // // Store the form which is posted to ePay // //$d['payment_extrainfo'] return true; } else { $d["error"] = $VM_LANG->_('PHPSHOP_ADMIN_CFG_EPAY_ERR_CONFIGFILE')." ".CLASSPATH ."payment/".__CLASS__.".cfg.php"; return false; } } // // The complete list of country currency codes. // function get_iso_code($code) { switch ($code) { case 'ADP': return '020'; break; case 'AED': return '784'; break; case 'AFA': return '004'; break; case 'ALL': return '008'; break; case 'AMD': return '051'; break; case 'ANG': return '532'; break; case 'AOA': return '973'; break; case 'ARS': return '032'; break; case 'AUD': return '036'; break; case 'AWG': return '533'; break; case 'AZM': return '031'; break; case 'BAM': return '977'; break; case 'BBD': return '052'; break; case 'BDT': return '050'; break; case 'BGL': return '100'; break; case 'BGN': return '975'; break; case 'BHD': return '048'; break; case 'BIF': return '108'; break; case 'BMD': return '060'; break; case 'BND': return '096'; break; case 'BOB': return '068'; break; case 'BOV': return '984'; break; case 'BRL': return '986'; break; case 'BSD': return '044'; break; case 'BTN': return '064'; break; case 'BWP': return '072'; break; case 'BYR': return '974'; break; case 'BZD': return '084'; break; case 'CAD': return '124'; break; case 'CDF': return '976'; break; case 'CHF': return '756'; break; case 'CLF': return '990'; break; case 'CLP': return '152'; break; case 'CNY': return '156'; break; case 'COP': return '170'; break; case 'CRC': return '188'; break; case 'CUP': return '192'; break; case 'CVE': return '132'; break; case 'CYP': return '196'; break; case 'CZK': return '203'; break; case 'DJF': return '262'; break; case 'DKK': return '208'; break; case 'DOP': return '214'; break; case 'DZD': return '012'; break; case 'ECS': return '218'; break; case 'ECV': return '983'; break; case 'EEK': return '233'; break; case 'EGP': return '818'; break; case 'ERN': return '232'; break; case 'ETB': return '230'; break; case 'EUR': return '978'; break; case 'FJD': return '242'; break; case 'FKP': return '238'; break; case 'GBP': return '826'; break; case 'GEL': return '981'; break; case 'GHC': return '288'; break; case 'GIP': return '292'; break; case 'GMD': return '270'; break; case 'GNF': return '324'; break; case 'GTQ': return '320'; break; case 'GWP': return '624'; break; case 'GYD': return '328'; break; case 'HKD': return '344'; break; case 'HNL': return '340'; break; case 'HRK': return '191'; break; case 'HTG': return '332'; break; case 'HUF': return '348'; break; case 'IDR': return '360'; break; case 'ILS': return '376'; break; case 'INR': return '356'; break; case 'IQD': return '368'; break; case 'IRR': return '364'; break; case 'ISK': return '352'; break; case 'JMD': return '388'; break; case 'JOD': return '400'; break; case 'JPY': return '392'; break; case 'KES': return '404'; break; case 'KGS': return '417'; break; case 'KHR': return '116'; break; case 'KMF': return '174'; break; case 'KPW': return '408'; break; case 'KRW': return '410'; break; case 'KWD': return '414'; break; case 'KYD': return '136'; break; case 'KZT': return '398'; break; case 'LAK': return '418'; break; case 'LBP': return '422'; break; case 'LKR': return '144'; break; case 'LRD': return '430'; break; case 'LSL': return '426'; break; case 'LTL': return '440'; break; case 'LVL': return '428'; break; case 'LYD': return '434'; break; case 'MAD': return '504'; break; case 'MDL': return '498'; break; case 'MGF': return '450'; break; case 'MKD': return '807'; break; case 'MMK': return '104'; break; case 'MNT': return '496'; break; case 'MOP': return '446'; break; case 'MRO': return '478'; break; case 'MTL': return '470'; break; case 'MUR': return '480'; break; case 'MVR': return '462'; break; case 'MWK': return '454'; break; case 'MXN': return '484'; break; case 'MXV': return '979'; break; case 'MYR': return '458'; break; case 'MZM': return '508'; break; case 'NAD': return '516'; break; case 'NGN': return '566'; break; case 'NIO': return '558'; break; case 'NOK': return '578'; break; case 'NPR': return '524'; break; case 'NZD': return '554'; break; case 'OMR': return '512'; break; case 'PAB': return '590'; break; case 'PEN': return '604'; break; case 'PGK': return '598'; break; case 'PHP': return '608'; break; case 'PKR': return '586'; break; case 'PLN': return '985'; break; case 'PYG': return '600'; break; case 'QAR': return '634'; break; case 'ROL': return '642'; break; case 'RUB': return '643'; break; case 'RUR': return '810'; break; case 'RWF': return '646'; break; case 'SAR': return '682'; break; case 'SBD': return '090'; break; case 'SCR': return '690'; break; case 'SDD': return '736'; break; case 'SEK': return '752'; break; case 'SGD': return '702'; break; case 'SHP': return '654'; break; case 'SIT': return '705'; break; case 'SKK': return '703'; break; case 'SLL': return '694'; break; case 'SOS': return '706'; break; case 'SRG': return '740'; break; case 'STD': return '678'; break; case 'SVC': return '222'; break; case 'SYP': return '760'; break; case 'SZL': return '748'; break; case 'THB': return '764'; break; case 'TJS': return '972'; break; case 'TMM': return '795'; break; case 'TND': return '788'; break; case 'TOP': return '776'; break; case 'TPE': return '626'; break; case 'TRL': return '792'; break; case 'TRY': return '949'; break; case 'TTD': return '780'; break; case 'TWD': return '901'; break; case 'TZS': return '834'; break; case 'UAH': return '980'; break; case 'UGX': return '800'; break; case 'USD': return '840'; break; case 'UYU': return '858'; break; case 'UZS': return '860'; break; case 'VEB': return '862'; break; case 'VND': return '704'; break; case 'VUV': return '548'; break; case 'XAF': return '950'; break; case 'XCD': return '951'; break; case 'XOF': return '952'; break; case 'XPF': return '953'; break; case 'YER': return '886'; break; case 'YUM': return '891'; break; case 'ZAR': return '710'; break; case 'ZMK': return '894'; break; case 'ZWD': return '716'; break; } // // As default return 208 for Danish Kroner // return '208'; } /************************************************************************** ** name: process_payment() ** returns: ***************************************************************************/ function process_payment($order_number, $order_total, &$d) { return true; } } administrator/components/com_virtuemart/classes/payment/ps_epn.cfg.php100644 0 0 2044 10732276304 24163 0ustar 0 0 administrator/components/com_virtuemart/classes/payment/ps_epn.php100644 0 0 72447 11263443355 23465 0ustar 0 0 classname.".cfg.php"); ?>
    _('PHPSHOP_ADMIN_CFG_ENABLE_EPN_TESTMODE') ?> _('PHPSHOP_ADMIN_CFG_ENABLE_EPN_TESTMODE_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_EPN_USERNAME') ?> _('PHPSHOP_ADMIN_CFG_EPN_USERNAME_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_EPN_KEY') ?> " >  
    _('PHPSHOP_PAYMENT_CVV2') ?> _('PHPSHOP_PAYMENT_CVV2_TOOLTIP') ?>
    _('PHPSHOP_PAYMENT_AN_RECURRING') ?> _('PHPSHOP_PAYMENT_AN_RECURRING_TOOLTIP') ?>
    _('PHPSHOP_ADMIN_CFG_EPN_AUTENTICATIONTYPE') ?> _('PHPSHOP_ADMIN_CFG_EPN_AUTENTICATIONTYPE_EXPLAIN') ?>

    _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_SUCC') ?> _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_SUCC_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_FAIL') ?> _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_FAIL_EXPLAIN') ?>
    classname.".cfg.php" ); } /** * Returns the "is_readable" status of the configuration file * @param void * @returns boolean True when the configuration file is writeable, false when not */ function configfile_readable() { return is_readable( CLASSPATH."payment/".$this->classname.".cfg.php" ); } /** * Writes the configuration file for this payment method * @param array An array of objects * @returns boolean True when writing was successful */ function write_configuration( &$d ) { $my_config_array = array("EPN_TEST_REQUEST" => $d['EPN_TEST_REQUEST'], "EPN_LOGIN" => $d['EPN_LOGIN'], "EPN_TYPE" => $d['EPN_TYPE'], "EPN_INVALID_STATUS" => $d['EPN_INVALID_STATUS'], "EPN_VERIFIED_STATUS" => $d['EPN_VERIFIED_STATUS'], "EPN_CHECK_CARD_CODE" => $d['EPN_CHECK_CARD_CODE'], "EPN_RECURRING" => $d['EPN_RECURRING'] ); $config = " $value ) { $config .= "define ('$key', '$value');\n"; } $config .= "?>"; if ($fp = fopen(CLASSPATH ."payment/".$this->classname.".cfg.php", "w")) { fputs($fp, $config, strlen($config)); fclose ($fp); return true; } else return false; } /************************************************************************** ** name: process_payment() ** created by: jep ** description: process transaction eProcessingNetwork.com ** parameters: $order_number, the number of the order, we're processing here ** $order_total, the total $ of the order ** returns: ***************************************************************************/ function process_payment($order_number, $order_total, &$d) { global $vendor_mail, $vendor_currency, $VM_LANG, $vmLogger; $database = new ps_DB(); $ps_vendor_id = $_SESSION["ps_vendor_id"]; $auth = $_SESSION['auth']; $ps_checkout = new ps_checkout; /*** Get the Configuration File for eProcessingNetwork.com ***/ require_once(CLASSPATH ."payment/".$this->classname.".cfg.php"); // Get the Transaction Key securely from the database $database->query( "SELECT ".VM_DECRYPT_FUNCTION."(payment_passkey,'".ENCODE_KEY."') as passkey FROM #__{vm}_payment_method WHERE payment_class='".$this->classname."'" ); $transaction = $database->record[0]; if( empty($transaction->passkey)) { $vmLogger->err( $VM_LANG->_('PHPSHOP_PAYMENT_ERROR'),false ); return false; } // Get user billing information $dbbt = new ps_DB; $qt = "SELECT * FROM #__{vm}_user_info WHERE user_id='".$auth["user_id"]."' AND address_type='BT'"; $dbbt->query($qt); $dbbt->next_record(); $user_info_id = $dbbt->f("user_info_id"); if( $user_info_id != $d["ship_to_info_id"]) { // Get user billing information $dbst = new ps_DB; $qt = "SELECT * FROM #__{vm}_user_info WHERE user_info_id='".$d["ship_to_info_id"]."' AND address_type='ST'"; $dbst->query($qt); $dbst->next_record(); } else { $dbst = $dbbt; } $host = "www.eprocessingnetwork.com"; $port = 443; $path = "/cgi-bin/an/order.pl"; //Authnet vars to send $formdata = array ( 'x_version' => '3.1', 'x_login' => EPN_LOGIN, 'x_tran_key' => $transaction->passkey, 'x_test_request' => EPN_TEST_REQUEST, // Gateway Response Configuration 'x_delim_data' => 'TRUE', 'x_delim_char' => '|', 'x_relay_response' => 'FALSE', 'x_relay_url' => 'FALSE', // Customer Name and Billing Address 'x_first_name' => substr($dbbt->f("first_name"), 0, 50), 'x_last_name' => substr($dbbt->f("last_name"), 0, 50), 'x_company' => substr($dbbt->f("company"), 0, 50), 'x_address' => substr($dbbt->f("address_1"), 0, 60), 'x_city' => substr($dbbt->f("city"), 0, 40), 'x_state' => substr($dbbt->f("state"), 0, 40), 'x_zip' => substr($dbbt->f("zip"), 0, 20), 'x_country' => substr($dbbt->f("country"), 0, 60), 'x_phone' => substr($dbbt->f("phone_1"), 0, 25), 'x_fax' => substr($dbbt->f("fax"), 0, 25), // Customer Shipping Address 'x_ship_to_first_name' => substr($dbst->f("first_name"), 0, 50), 'x_ship_to_last_name' => substr($dbst->f("last_name"), 0, 50), 'x_ship_to_company' => substr($dbst->f("company"), 0, 50), 'x_ship_to_address' => substr($dbst->f("address_1"), 0, 60), 'x_ship_to_city' => substr($dbst->f("city"), 0, 40), 'x_ship_to_state' => substr($dbst->f("state"), 0, 40), 'x_ship_to_zip' => substr($dbst->f("zip"), 0, 20), 'x_ship_to_country' => substr($dbst->f("country"), 0, 60), // Additional Customer Data 'x_cust_id' => $auth['user_id'], 'x_customer_ip' => $_SERVER["REMOTE_ADDR"], 'x_customer_tax_id' => $dbbt->f("tax_id"), // Email Settings 'x_email' => $dbbt->f("email"), 'x_email_customer' => 'False', 'x_merchant_email' => $vendor_mail, // Invoice Information 'x_invoice_num' => substr($order_number, 0, 20), 'x_description' => '', // Transaction Data 'x_amount' => $order_total, 'x_currency_code' => $vendor_currency, 'x_method' => 'CC', 'x_type' => EPN_TYPE, 'x_recurring_billing' => EPN_RECURRING, 'x_card_num' => $_SESSION['ccdata']['order_payment_number'], 'x_card_code' => $_SESSION['ccdata']['credit_card_code'], 'x_exp_date' => ($_SESSION['ccdata']['order_payment_expire_month']) . ($_SESSION['ccdata']['order_payment_expire_year']), // Level 2 data 'x_po_num' => substr($order_number, 0, 20), 'x_tax' => substr($d['order_tax'], 0, 15), 'x_tax_exempt' => "FALSE", 'x_freight' => $d['order_shipping'], 'x_duty' => 0 ); //build the post string $poststring = ''; foreach($formdata AS $key => $val){ $poststring .= urlencode($key) . "=" . urlencode($val) . "&"; } // strip off trailing ampersand $poststring = substr($poststring, 0, -1); if( function_exists( "curl_init" )) { $CR = curl_init(); curl_setopt($CR, CURLOPT_URL, "https://".$host.$path); curl_setopt($CR, CURLOPT_POST, 1); curl_setopt($CR, CURLOPT_FAILONERROR, true); curl_setopt($CR, CURLOPT_POSTFIELDS, $poststring); curl_setopt($CR, CURLOPT_RETURNTRANSFER, 1); // No PEER certificate validation...as we don't have // a certificate file for it to authenticate the host www.ups.com against! curl_setopt($CR, CURLOPT_SSL_VERIFYPEER, 0); //curl_setopt($CR, CURLOPT_SSLCERT , "/usr/locale/xxxx/clientcertificate.pem"); $result = curl_exec( $CR ); $error = curl_error( $CR ); if( !empty( $error )) { $vmLogger->err( curl_error( $CR ) ); $html = "
    ".$VM_LANG->_('PHPSHOP_PAYMENT_INTERNAL_ERROR')." eProcessingNetwork.com"; return false; } else { //echo $result; exit(); } curl_close( $CR ); } else { $fp = fsockopen("ssl://".$host, $port, $errno, $errstr, $timeout = 60); if(!$fp){ //error tell us $vmLogger->err( "$errstr ($errno)" ); } else { //send the server request fputs($fp, "POST $path HTTP/1.1\r\n"); fputs($fp, "Host: $host\r\n"); fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n"); fputs($fp, "Content-length: ".strlen($poststring)."\r\n"); fputs($fp, "Connection: close\r\n\r\n"); fputs($fp, $poststring . "\r\n\r\n"); //Get the response header from the server $str = ''; while(!feof($fp) && !stristr($str, 'content-length')) { $str = fgets($fp, 4096); } // If didnt get content-lenght, something is wrong, return false. if (!stristr($str, 'content-length')) { return false; } $data = ""; while (!feof($fp)) { $data .= fgets ($fp, 1024); } $result = trim( $data ); /* // Get length of data to be received. $length = trim(substr($str,strpos($str,'content-length') + 15)); // Get buffer (blank data before real data) fgets($fp, 4096); // Get real data $data = fgets($fp, $length); fclose($fp);*/ } } $response = explode("|", $result); // Approved - Success! if ($response[0] == '1') { $d["order_payment_log"] = $VM_LANG->_('PHPSHOP_PAYMENT_TRANSACTION_SUCCESS').": "; $d["order_payment_log"] .= $response[3]; // Catch Transaction ID $d["order_payment_trans_id"] = $response[6]; return True; } // Payment Declined elseif ($response[0] == '2') { $vmLogger->err( $response[3] ); $d["order_payment_log"] = $response[3]; // Catch Transaction ID $d["order_payment_trans_id"] = $response[6]; return False; } // Transaction Error elseif ($response[0] == '3') { $vmLogger->err( $response[3] ); $d["order_payment_log"] = $response[3]; // Catch Transaction ID $d["order_payment_trans_id"] = $response[6]; return False; } } /************************************************************************** ** name: capture_payment() ** created by: Soeren ** description: Process a previous transaction with eProcessingNetwork.com, Capture the Payment ** parameters: $order_number, the number of the order, we're processing here ** returns: ***************************************************************************/ function capture_payment( &$d ) { global $vendor_mail, $vendor_currency, $VM_LANG, $vmLogger; $database = new ps_DB(); /* $host = "www.eprocessingnetwork.com"; $port = 443; $path = "/cgi-bin/an/order.pl"; CERTIFICATION Visa Test Account 4007000000027 Amex Test Account 370000000000002 Master Card Test Account 6011000000000012 Discover Test Account 5424000000000015 */ $host = "www.eprocessingnetwork.com"; $port = 443; $path = "/cgi-bin/an/order.pl"; if( empty($d['order_number'])) { $vmLogger->err("Error: No Order Number provided."); return false; } /*** Get the Configuration File for eProcessingNetwork.com ***/ require_once(CLASSPATH ."payment/".$this->classname.".cfg.php"); // Get the Transaction Key securely from the database $database->query( "SELECT ".VM_DECRYPT_FUNCTION."(payment_passkey,'".ENCODE_KEY."') as passkey FROM #__{vm}_payment_method WHERE payment_class='".$this->classname."'" ); $transaction = $database->record[0]; if( empty($transaction->passkey)) { $vmLogger->err($VM_LANG->_('PHPSHOP_PAYMENT_ERROR'),false); return false; } $db = new ps_DB; $q = "SELECT * FROM #__{vm}_orders, #__{vm}_order_payment WHERE "; $q .= "order_number='".$d['order_number']."' "; $q .= "AND #__{vm}_orders.order_id=#__{vm}_order_payment.order_id"; $db->query( $q ); if( !$db->next_record() ) { $vmLogger->err("Error: Order not found."); return false; } $expire_date = date( "my", $db->f("order_payment_expire") ); // DECODE Account Number $dbaccount = new ps_DB; $q = "SELECT ".VM_DECRYPT_FUNCTION."(order_payment_number,'".ENCODE_KEY."') AS account_number from #__{vm}_order_payment WHERE order_id='".$db->f("order_id")."'"; $dbaccount->query($q); $dbaccount->next_record(); // Get user billing information $dbbt = new ps_DB; $qt = "SELECT * FROM #__{vm}_user_info WHERE user_id='".$db->f("user_id")."'"; $dbbt->query($qt); $dbbt->next_record(); $user_info_id = $dbbt->f("user_info_id"); if( $user_info_id != $db->f("user_info_id")) { // Get user billing information $dbst = new ps_DB; $qt = "SELECT * FROM #__{vm}_user_info WHERE user_info_id='".$db->f("user_info_id")."' AND address_type='ST'"; $dbst->query($qt); $dbst->next_record(); } else { $dbst = $dbbt; } //Authnet vars to send $formdata = array ( 'x_version' => '3.1', 'x_login' => EPN_LOGIN, 'x_tran_key' => $transaction->passkey, 'x_test_request' => EPN_TEST_REQUEST, // Gateway Response Configuration 'x_delim_data' => 'TRUE', 'x_delim_char' => '|', 'x_relay_response' => 'FALSE', 'x_relay_url' => 'FALSE', // Customer Name and Billing Address 'x_first_name' => substr($dbbt->f("first_name"), 0, 50), 'x_last_name' => substr($dbbt->f("last_name"), 0, 50), 'x_company' => substr($dbbt->f("company"), 0, 50), 'x_address' => substr($dbbt->f("address_1"), 0, 60), 'x_city' => substr($dbbt->f("city"), 0, 40), 'x_state' => substr($dbbt->f("state"), 0, 40), 'x_zip' => substr($dbbt->f("zip"), 0, 20), 'x_country' => substr($dbbt->f("country"), 0, 60), 'x_phone' => substr($dbbt->f("phone_1"), 0, 25), 'x_fax' => substr($dbbt->f("fax"), 0, 25), // Customer Shipping Address 'x_ship_to_first_name' => substr($dbst->f("first_name"), 0, 50), 'x_ship_to_last_name' => substr($dbst->f("last_name"), 0, 50), 'x_ship_to_company' => substr($dbst->f("company"), 0, 50), 'x_ship_to_address' => substr($dbst->f("address_1"), 0, 60), 'x_ship_to_city' => substr($dbst->f("city"), 0, 40), 'x_ship_to_state' => substr($dbst->f("state"), 0, 40), 'x_ship_to_zip' => substr($dbst->f("zip"), 0, 20), 'x_ship_to_country' => substr($dbst->f("country"), 0, 60), // Additional Customer Data 'x_cust_id' => $db->f('user_id'), 'x_customer_ip' => $dbbt->f("ip_address"), 'x_customer_tax_id' => $dbbt->f("tax_id"), // Email Settings 'x_email' => $dbbt->f("email"), 'x_email_customer' => 'False', 'x_merchant_email' => $vendor_mail, // Invoice Information 'x_invoice_num' => substr($d['order_number'], 0, 20), 'x_description' => '', // Transaction Data 'x_amount' => $db->f("order_total"), 'x_currency_code' => $vendor_currency, 'x_method' => 'CC', 'x_type' => 'PRIOR_AUTH_CAPTURE', 'x_recurring_billing' => EPN_RECURRING, 'x_card_num' => $dbaccount->f("account_number"), 'x_card_code' => $db->f('order_payment_code'), 'x_exp_date' => $expire_date, 'x_trans_id' => $db->f("order_payment_trans_id"), // Level 2 data 'x_po_num' => substr($d['order_number'], 0, 20), 'x_tax' => substr($db->f('order_tax'), 0, 15), 'x_tax_exempt' => "FALSE", 'x_freight' => $db->f('order_shipping'), 'x_duty' => 0 ); //build the post string $poststring = ''; foreach($formdata AS $key => $val){ $poststring .= urlencode($key) . "=" . urlencode($val) . "&"; } // strip off trailing ampersand $poststring = substr($poststring, 0, -1); if( function_exists( "curl_init" )) { $CR = curl_init(); curl_setopt($CR, CURLOPT_URL, "https://".$host.$path); curl_setopt($CR, CURLOPT_POST, 1); curl_setopt($CR, CURLOPT_FAILONERROR, true); curl_setopt($CR, CURLOPT_POSTFIELDS, $poststring); curl_setopt($CR, CURLOPT_RETURNTRANSFER, 1); // No PEER certificate validation...as we don't have // a certificate file for it to authenticate the host www.ups.com against! curl_setopt($CR, CURLOPT_SSL_VERIFYPEER, 0); //curl_setopt($CR, CURLOPT_SSLCERT , "/usr/locale/xxxx/clientcertificate.pem"); $result = curl_exec( $CR ); $error = curl_error( $CR ); if( !empty( $error )) { $vmLogger->err( curl_error( $CR ) ); $html = "
    ".$VM_LANG->_('PHPSHOP_PAYMENT_INTERNAL_ERROR')." eProcessingNetork.com"; return false; } else { //echo $result; exit(); } curl_close( $CR ); } else { $fp = fsockopen("ssl://".$host, $port, $errno, $errstr, $timeout = 60); if(!$fp){ //error tell us $vmLogger->err( "$errstr ($errno)" ); } else { //send the server request fputs($fp, "POST $path HTTP/1.1\r\n"); fputs($fp, "Host: $host\r\n"); fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n"); fputs($fp, "Content-length: ".strlen($poststring)."\r\n"); fputs($fp, "Connection: close\r\n\r\n"); fputs($fp, $poststring . "\r\n\r\n"); //Get the response header from the server $str = ''; while(!feof($fp) && !stristr($str, 'content-length')) { $str = fgets($fp, 4096); } // If didnt get content-lenght, something is wrong, return false. if (!stristr($str, 'content-length')) { return false; } $data = ""; while (!feof($fp)) { $data .= fgets ($fp, 1024); } $result = trim( $data ); /* // Get length of data to be received. $length = trim(substr($str,strpos($str,'content-length') + 15)); // Get buffer (blank data before real data) fgets($fp, 4096); // Get real data $data = fgets($fp, $length); fclose($fp);*/ } } $response = explode("|", $result); // Approved - Success! if ($response[0] == '1') { $d["order_payment_log"] = $VM_LANG->_('PHPSHOP_PAYMENT_TRANSACTION_SUCCESS').": "; $d["order_payment_log"] .= $response[3]; // Catch Transaction ID $d["order_payment_trans_id"] = $response[6]; $q = "UPDATE #__{vm}_order_payment SET "; $q .="order_payment_log='".$d["order_payment_log"]."',"; $q .="order_payment_trans_id='".$d["order_payment_trans_id"]."' "; $q .="WHERE order_id='".$db->f("order_id")."' "; $db->query( $q ); return True; } // Payment Declined elseif ($response[0] == '2') { $vmLogger->err( $response[3] ); $d["order_payment_log"] = $response[3]; // Catch Transaction ID $d["order_payment_trans_id"] = $response[6]; return False; } // Transaction Error elseif ($response[0] == '3') { $vmLogger->err( $response[3] ); $d["order_payment_log"] = $response[3]; // Catch Transaction ID $d["order_payment_trans_id"] = $response[6]; return False; } } } administrator/components/com_virtuemart/classes/payment/ps_eway.cfg.php100644 0 0 1744 10732276304 24354 0ustar 0 0 administrator/components/com_virtuemart/classes/payment/ps_eway.php100644 0 0 52727 11225702275 23644 0ustar 0 0 classname.".cfg.php"); ?>
    _('PHPSHOP_ADMIN_CFG_EWAY_CUSTID') ?> _('PHPSHOP_ADMIN_CFG_EWAY_CUSTID_EXPLAIN') ?>
    _('PHPSHOP_PAYMENT_CVV2') ?> _('PHPSHOP_PAYMENT_CVV2_TOOLTIP') ?>
    _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_SUCC') ?> _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_SUCC_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_FAIL') ?> _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_FAIL_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_ENABLE_AUTORIZENET_TESTMODE') ?> _('PHPSHOP_ADMIN_CFG_ENABLE_AUTORIZENET_TESTMODE_EXPLAIN') ?>
    classname.".cfg.php" ); } /** * Returns the "is_readable" status of the configuration file * @param void * @returns boolean True when the configuration file is writeable, false when not */ function configfile_readable() { return is_readable( CLASSPATH."payment/".$this->classname.".cfg.php" ); } /** * Writes the configuration file for this payment method * @param array An array of objects * @returns boolean True when writing was successful */ function write_configuration( &$d ) { $my_config_array = array("EWAY_CUSTID" => $d['EWAY_CUSTID'], "EWAY_CHECK_CARD_CODE" => $d['EWAY_CHECK_CARD_CODE'], "EWAY_VERIFIED_STATUS" => $d['EWAY_VERIFIED_STATUS'], "EWAY_INVALID_STATUS" => $d['EWAY_INVALID_STATUS'], "EWAY_TEST_REQUEST" => $d['EWAY_TEST_REQUEST'] ); $config = " $value ) { $config .= "define ('$key', '$value');\n"; } $config .= "?>"; if ($fp = fopen(CLASSPATH ."payment/".$this->classname.".cfg.php", "w")) { fputs($fp, $config, strlen($config)); fclose ($fp); return true; } else return false; } /************************************************************************** ** name: process_payment() ** returns: ***************************************************************************/ function process_payment($order_number, $order_total, &$d) { global $vendor_name, $VM_LANG, $vmLogger; $auth = $_SESSION['auth']; /*** Get the Configuration File for eway ***/ require_once(CLASSPATH ."payment/".$this->classname.".cfg.php"); /* eWAY Gateway Location (URI) */ if( EWAY_TEST_REQUEST == "FALSE" ) define( "GATEWAY_URL", "https://www.eway.com.au/gateway_cvn/xmlpayment.asp"); else define( "GATEWAY_URL", "https://www.eway.com.au/gateway_cvn/xmltest/testpage.asp"); // Get user billing information $db = new ps_DB; $qt = "SELECT * FROM #__users WHERE id='".$auth["user_id"]."' AND address_type='BT'"; $db->query($qt); $db->next_record(); // WE need the $order_total in cents! $order_total = $order_total * 100; // We need to show the year with two digits only $year = substr( $_SESSION['ccdata']['order_payment_expire_year'], 2, 2 ); $my_trxn_number = uniqid( "eway_" ); $payer_name_is = $_SESSION['ccdata']['order_payment_name']; $eway = new EwayPayment( EWAY_CUSTID, GATEWAY_URL ); $eway->setCustomerFirstname( $db->f("first_name") ); $eway->setCustomerLastname( $db->f("last_name") ); $eway->setCustomerEmail( $db->f("email") ); $eway->setCustomerAddress( $db->f("address_1") ); $eway->setCustomerPostcode( $db->f("zip") ); $eway->setCustomerInvoiceDescription( $vendor_name." Order" ); $eway->setCustomerInvoiceRef( $order_number ); $eway->setCardHoldersName( $payer_name_is + '' ); $eway->setCardNumber( $_SESSION['ccdata']['order_payment_number'] ); $eway->setCardExpiryMonth( $_SESSION['ccdata']['order_payment_expire_month'] ); $eway->setCardExpiryYear( $year + '' ); $eway->setCardCVN( $_SESSION['ccdata']['credit_card_code'] ); $eway->setTrxnNumber( $my_trxn_number ); $eway->setTotalAmount( $order_total ); if( $eway->doPayment() == EWAY_TRANSACTION_OK ) { $d["order_payment_log"] = $VM_LANG->_('PHPSHOP_PAYMENT_TRANSACTION_SUCCESS'); //Catch Transaction ID $d["order_payment_trans_id"] = $eway->getTrxnNumber(); //$d["error"] = ""; return true; } else { $vmLogger->err( $VM_LANG->_('PHPSHOP_PAYMENT_ERROR',false).": " .$eway->getErrorMessage() ); //Catch Transaction ID $d["order_payment_trans_id"] = $eway->getTrxnNumber(); return false; } } } /* * class EwayPayment * Electronic Payment XML Interface for eWAY * * (c) Copyright Matthew Horoschun, CanPrint Communications 2005. * * $Id: ps_eway.php 1845 2009-07-10 18:13:17Z Aravot $ * * Date: 2005-04-18 * Version: 2.0 * */ define( 'EWAY_DEFAULT_GATEWAY_URL', 'https://www.eway.com.au/gateway_cvn/xmlpayment.asp' ); define( 'EWAY_DEFAULT_CUSTOMER_ID', '87654321' ); define( 'EWAY_CURL_ERROR_OFFSET', 1000 ); define( 'EWAY_XML_ERROR_OFFSET', 2000 ); define( 'EWAY_TRANSACTION_OK', 0 ); define( 'EWAY_TRANSACTION_FAILED', 1 ); define( 'EWAY_TRANSACTION_UNKNOWN', 2 ); class EwayPayment { var $parser; var $xmlData; var $currentTag; var $myGatewayURL; var $myCustomerID; var $myTotalAmount; var $myCustomerFirstname; var $myCustomerLastname; var $myCustomerEmail; var $myCustomerAddress; var $myCustomerPostcode; var $myCustomerInvoiceDescription; var $myCustomerInvoiceRef; var $myCardHoldersName; var $myCardNumber; var $myCardExpiryMonth; var $myCardExpiryYear; var $myCardCVN; var $myTrxnNumber; var $myOption1; var $myOption2; var $myOption3; var $myResultTrxnStatus; var $myResultTrxnNumber; var $myResultTrxnOption1; var $myResultTrxnOption2; var $myResultTrxnOption3; var $myResultTrxnReference; var $myResultTrxnError; var $myResultAuthCode; var $myResultReturnAmount; var $myCardName; var $myError; var $myErrorMessage; /*********************************************************************** *** Class Constructor *** ***********************************************************************/ function EwayPayment( $customerID = EWAY_DEFAULT_CUSTOMER_ID, $gatewayURL = EWAY_DEFAULT_GATEWAY_URL ) { $this->myCustomerID = $customerID; $this->myGatewayURL = $gatewayURL; } /*********************************************************************** *** XML Parser - Callback functions *** ***********************************************************************/ function epXmlElementStart ($parser, $tag, $attributes) { $this->currentTag = $tag; } function epXmlElementEnd ($parser, $tag) { $this->currentTag = ""; } function epXmlData ($parser, $cdata) { $this->xmlData[$this->currentTag] = $cdata; } /*********************************************************************** *** SET values to send to eWAY *** ***********************************************************************/ function setCustomerID( $customerID ) { $this->myCustomerID = $customerID; } function setTotalAmount( $totalAmount ) { $this->myTotalAmount = $totalAmount; } function setCustomerFirstname( $customerFirstname ) { $this->myCustomerFirstname = $customerFirstname; } function setCustomerLastname( $customerLastname ) { $this->myCustomerLastname = $customerLastname; } function setCustomerEmail( $customerEmail ) { $this->myCustomerEmail = $customerEmail; } function setCustomerAddress( $customerAddress ) { $this->myCustomerAddress = $customerAddress; } function setCustomerPostcode( $customerPostcode ) { $this->myCustomerPostcode = $customerPostcode; } function setCustomerInvoiceDescription( $customerInvoiceDescription ) { $this->myCustomerInvoiceDescription = $customerInvoiceDescription; } function setCustomerInvoiceRef( $customerInvoiceRef ) { $this->myCustomerInvoiceRef = $customerInvoiceRef; } function setCardHoldersName( $cardHoldersName ) { $this->myCardHoldersName = $cardHoldersName; } function setCardNumber( $cardNumber ) { $this->myCardNumber = $cardNumber; } function setCardExpiryMonth( $cardExpiryMonth ) { $this->myCardExpiryMonth = $cardExpiryMonth; } function setCardExpiryYear( $cardExpiryYear ) { $this->myCardExpiryYear = $cardExpiryYear; } function setCardCVN( $cardCVN ) { $this->myCardCVN = $cardCVN; } function setTrxnNumber( $trxnNumber ) { $this->myTrxnNumber = $trxnNumber; } function setOption1( $option1 ) { $this->myOption1 = $option1; } function setOption2( $option2 ) { $this->myOption2 = $option2; } function setOption3( $option3 ) { $this->myOption3 = $option3; } /*********************************************************************** *** GET values returned by eWAY *** ***********************************************************************/ function getTrxnStatus() { return $this->myResultTrxnStatus; } function getTrxnNumber() { return $this->myResultTrxnNumber; } function getTrxnOption1() { return $this->myResultTrxnOption1; } function getTrxnOption2() { return $this->myResultTrxnOption2; } function getTrxnOption3() { return $this->myResultTrxnOption3; } function getTrxnReference() { return $this->myResultTrxnReference; } function getTrxnError() { return $this->myResultTrxnError; } function getAuthCode() { return $this->myResultAuthCode; } function getReturnAmount() { return $this->myResultReturnAmount; } function getError() { if( $this->myError != 0 ) { // Internal Error return $this->myError; } else { // eWAY Error if( $this->getTrxnStatus() == 'True' ) { return EWAY_TRANSACTION_OK; } elseif( $this->getTrxnStatus() == 'False' ) { return EWAY_TRANSACTION_FAILED; } else { return EWAY_TRANSACTION_UNKNOWN; } } } function getErrorMessage() { if( $this->myError != 0 ) { // Internal Error return $this->myErrorMessage; } else { // eWAY Error return $this->getTrxnError(); } } /*********************************************************************** *** Business Logic *** ***********************************************************************/ function doPayment() { $xmlRequest = "". "".htmlentities( $this->myCustomerID )."". "".htmlentities( $this->myTotalAmount)."". "".htmlentities( $this->myCustomerFirstname )."". "".htmlentities( $this->myCustomerLastname )."". "".htmlentities( $this->myCustomerEmail )."". "".htmlentities( $this->myCustomerAddress )."". "".htmlentities( $this->myCustomerPostcode )."". "".htmlentities( $this->myCustomerInvoiceDescription )."". "".htmlentities( $this->myCustomerInvoiceRef )."". "".htmlentities( $this->myCardName )."". "".htmlentities( $this->myCardNumber )."". "".htmlentities( $this->myCardExpiryMonth )."". "".htmlentities( $this->myCardExpiryYear )."". "".htmlentities( $this->myTrxnNumber )."". "".htmlentities( $this->myOption1 )."". "".htmlentities( $this->myOption2 )."". "".htmlentities( $this->myOption3 )."". "".htmlentities( $this->myCardCVN )."". ""; /* Use CURL to execute XML POST and write output into a string */ $ch = curl_init( $this->myGatewayURL ); curl_setopt( $ch, CURLOPT_POST, 1 ); curl_setopt( $ch, CURLOPT_POSTFIELDS, $xmlRequest ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); curl_setopt( $ch, CURLOPT_TIMEOUT, 240 ); $xmlResponse = curl_exec( $ch ); //exit; // Check whether the curl_exec worked. if( curl_errno( $ch ) == CURLE_OK ) { // It worked, so setup an XML parser for the result. $this->parser = xml_parser_create(); // Disable XML tag capitalisation (Case Folding) xml_parser_set_option ($this->parser, XML_OPTION_CASE_FOLDING, FALSE); // Define Callback functions for XML Parsing xml_set_object($this->parser, $this); xml_set_element_handler ($this->parser, "epXmlElementStart", "epXmlElementEnd"); xml_set_character_data_handler ($this->parser, "epXmlData"); // Parse the XML response xml_parse($this->parser, $xmlResponse, TRUE); if( xml_get_error_code( $this->parser ) == XML_ERROR_NONE ) { // Get the result into local variables. $this->myResultTrxnStatus = $this->xmlData['ewayTrxnStatus']; $this->myResultTrxnNumber = $this->xmlData['ewayTrxnNumber']; $this->myResultTrxnOption1 = $this->xmlData['ewayTrxnOption1']; $this->myResultTrxnOption2 = $this->xmlData['ewayTrxnOption2']; $this->myResultTrxnOption3 = $this->xmlData['ewayTrxnOption3']; $this->myResultTrxnReference = $this->xmlData['ewayTrxnReference']; $this->myResultAuthCode = $this->xmlData['ewayAuthCode']; $this->myResultReturnAmount = $this->xmlData['ewayReturnAmount']; $this->myResultTrxnError = $this->xmlData['ewayTrxnError']; $this->myError = 0; $this->myErrorMessage = ''; } else { // An XML error occured. Return the error message and number. $this->myError = xml_get_error_code( $this->parser ) + EWAY_XML_ERROR_OFFSET; $this->myErrorMessage = xml_error_string( $myError ); } // Clean up our XML parser xml_parser_free( $this->parser ); } else { // A CURL Error occured. Return the error message and number. (offset so we can pick the error apart) $this->myError = curl_errno( $ch ) + EWAY_CURL_ERROR_OFFSET; $this->myErrorMessage = curl_error( $ch ); } // Clean up CURL, and return any error. curl_close( $ch ); return $this->getError(); } } ?> administrator/components/com_virtuemart/classes/payment/ps_ipayment.cfg.php100644 0 0 770 11153553177 25217 0ustar 0 0 administrator/components/com_virtuemart/classes/payment/ps_ipayment.php100644 0 0 21144 11153553177 24517 0ustar 0 0
    Account/Händler ID
    Anwendungs-ID/ User-ID
    Anwendungs-Passwort/ Transaktionsuser-Passwort
    Aktions-Passwort
    Transaktions-Security-Key
    _('PHPSHOP_ADMIN_CFG_PAYPAL_STATUS_SUCCESS') ?> _('PHPSHOP_ADMIN_CFG_PAYPAYL_STATUS_SUCCESS_EXPLAIN') ?>
    _('VM_ADMIN_CFG_PAYPAL_STATUS_PENDING') ?> _('VM_ADMIN_CFG_PAYPAL_STATUS_PENDING_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_PAYPAL_STATUS_FAILED') ?> _('PHPSHOP_ADMIN_CFG_PAYPAL_STATUS_FAILED_EXPLAIN') ?>
    $d['IPAYMENT_ACCOUNTID'], "IPAYMENT_APPID" => $d['IPAYMENT_APPID'], "IPAYMENT_APP_PASSWORD" => $d['IPAYMENT_APP_PASSWORD'], "IPAYMENT_ACTION_PASSWORD" => $d['IPAYMENT_ACTION_PASSWORD'], "IPAYMENT_SECRET" => $d['IPAYMENT_SECRET'], "IPAYMENT_VERIFIED_STATUS" => $d['IPAYMENT_VERIFIED_STATUS'], "IPAYMENT_PENDING_STATUS" => $d['IPAYMENT_PENDING_STATUS'], "IPAYMENT_INVALID_STATUS" => $d['IPAYMENT_INVALID_STATUS'] ); $config = " $value ) { $config .= "define ('$key', '$value');\n"; } $config .= "?>"; if ($fp = fopen(CLASSPATH ."payment/".__CLASS__.".cfg.php", "w")) { fputs($fp, $config, strlen($config)); fclose ($fp); return true; } else return false; } /************************************************************************** ** name: process_payment() ** returns: ***************************************************************************/ function process_payment($order_number, $order_total, &$d) { return true; } } administrator/components/com_virtuemart/classes/payment/ps_linkpoint.cfg.php100644 0 0 2030 10732276304 25403 0ustar 0 0 administrator/components/com_virtuemart/classes/payment/ps_linkpoint.php100644 0 0 40322 11263443355 24675 0ustar 0 0 Payment Method List -> Creditcard LP -> Configuration * you can insert your store number, and public key location. * * Any questions, email jimmy@freshstation.org * @copyright (C) 2005 James McMillan */ define ('LP_VERIFIED_STATUS', 'C'); class ps_linkpoint { var $payment_code = "LP"; var $classname = "ps_linkpoint"; /** * Most of this top configuration code was stripped and hacked from the authorize.net payment class * Show all configuration parameters for this payment method * @returns boolean False when the Payment method has no configration */ function show_configuration() { global $VM_LANG, $sess; $payment_method_id = vmGet( $_REQUEST, 'payment_method_id', null ); /** Read current Configuration ***/ require_once(CLASSPATH ."payment/".$this->classname.".cfg.php"); ?>
    _('PHPSHOP_PAYMENT_CVV2') ?> _('PHPSHOP_PAYMENT_CVV2_TOOLTIP') ?>
    _('PHPSHOP_PAYMENT_AN_RECURRING') ?> _('PHPSHOP_PAYMENT_AN_RECURRING_TOOLTIP') ?>
    classname.".cfg.php" ); } /** * Returns the "is_readable" status of the configuration file * @param void * @returns boolean True when the configuration file is writeable, false when not */ function configfile_readable() { return is_readable( CLASSPATH."payment/".$this->classname.".cfg.php" ); } /** * Writes the configuration file for this payment method * @param array An array of objects * @returns boolean True when writing was successful */ function write_configuration( &$d ) { $my_config_array = array("LP_TEST_REQUEST" => $d['LP_TEST_REQUEST'], "LP_LOGIN" => $d['LP_LOGIN'], "LP_TYPE" => $d['LP_TYPE'], "LP_KEYFILE" => $d['LP_KEYFILE'], "LP_CHECK_CARD_CODE" => $d['LP_CHECK_CARD_CODE'], "LP_RECURRING" => $d['LP_RECURRING'], "LP_PREAUTH" => $d['LP_PREAUTH'] ); $config = " $value ) { $config .= "define ('$key', '$value');\n"; } $config .= "?>"; if ($fp = fopen(CLASSPATH ."payment/".$this->classname.".cfg.php", "w")) { fputs($fp, $config, strlen($config)); fclose ($fp); return true; } else return false; } /************************************************************************** ** name: process_payment() ** created by: James McMillan ** description: process transaction linkpoint.net ** parameters: $order_number, the number of the order, we're processing here ** $order_total, the total $ of the order ** returns: T/F ***************************************************************************/ function process_payment($order_number, $order_total, &$d) { global $vmLogger; // We must include the yourpay/linkpoint api file. require( CLASSPATH ."payment/lphp.php" ); // Declare new linkpoint php class $mylphp = new lphp(); global $vendor_mail, $vendor_currency, $VM_LANG, $database; $ps_vendor_id = $_SESSION["ps_vendor_id"]; $auth = $_SESSION['auth']; $ps_checkout = new ps_checkout; require_once(CLASSPATH ."payment/".$this->classname.".cfg.php"); // Get user billing information $dbbt = new ps_DB; $qt = "SELECT * FROM `#__{vm}_user_info` WHERE user_id='".$auth["user_id"]."' AND address_type='BT'"; $dbbt->query($qt); $dbbt->next_record(); $user_info_id = $dbbt->f("user_info_id"); if( $user_info_id != $d["ship_to_info_id"]) { // Get user billing information $dbst = new ps_DB; $qt = "SELECT * FROM #__{vm}_user_info WHERE user_info_id='".$d["ship_to_info_id"]."' AND address_type='ST'"; $dbst->query($qt); $dbst->next_record(); } else { $dbst = $dbbt; } // Start gathering the information needed for the XML transaction $cuname = substr($dbbt->f("first_name"), 0, 25) . " " . substr($dbbt->f("last_name"), 0, 25); // The following should be static for linkpoint, if not, change to the specified host (secure/staging.linkpt.net) $myorder["host"] = "secure.linkpt.net"; $myorder["port"] = "1129"; $myorder["keyfile"] = LP_KEYFILE; $myorder["configfile"] = LP_LOGIN; //Atlanticom Mod - Adding substitution for ampersand sign to correct //XML rejection of linkpoint transactions including same (usually in company name). $myorder["name"] = str_replace("&","",$cuname); $myorder["company"] = str_replace("&","",substr($dbbt->f("company"), 0, 50)); $myorder["address1"] = str_replace("&","",substr($dbbt->f("address_1"), 0, 60)); $myorder["address2"] = str_replace("&","",substr($dbbt->f("address_2"), 0, 60)); $myorder["city"] = str_replace("&","",substr($dbbt->f("city"), 0, 40)); $myorder["state"] = str_replace("&","",substr($dbbt->f("state"), 0, 40)); $myorder["zip"] = str_replace("&","",substr($dbbt->f("zip"), 0, 20)); $myorder["country"] = str_replace("&","",substr($dbbt->f("country"), 0, 60)); $myorder["phone"] = str_replace("&","",substr($dbbt->f("phone_1"), 0, 25)); $myorder["fax"] = str_replace("&","",substr($dbbt->f("fax"), 0, 25)); $myorder["email"] = str_replace("&","",$dbbt->f("email")); //End Atlanticom Mod $myorder["cardnumber"] = $_SESSION['ccdata']['order_payment_number']; $myorder["cardexpmonth"] = $_SESSION['ccdata']['order_payment_expire_month']; $myorder["cardexpyear"] = substr($_SESSION['ccdata']['order_payment_expire_year'],2,2); $myorder["cvmindicator"] = "provided"; $myorder["cvmvalue"] = $_SESSION['ccdata']['credit_card_code']; $myorder["chargetotal"] = $order_total; //Atlanticom Mod: Let's anticipate the next order_id (an auto increment field) that will be used for this //payment if it is successful, and what the heck... let's append the word WEB to it. // Get last attempt $dbLP = new ps_DB; $qt = "SELECT * FROM #__{vm}_linkpoint WHERE Id=1"; $dbLP->query($qt); $dbLP->next_record(); $LP_LastAttempt = $dbLP->f("LastAttempt"); $LP_LastAttemptParts = explode("-",$LP_LastAttempt); if($LP_LastAttemptParts[2] == "") $LP_next_suffix = "a"; else { $this_char = ord($LP_LastAttemptParts[2]); $LP_next_suffix = chr($this_char + 1); } $dbord = new ps_DB; $qord = "SELECT MAX(order_id)+1 As expected_order_id FROM #__{vm}_orders"; $dbord->query($qord); $dbord->next_record(); $expected_order_id = $dbord->f("expected_order_id"); //has this order # already been attempted and failed? if($LP_LastAttemptParts[1] == $expected_order_id){ //we need to increment the attempt. $this_order_id = "WEB-" . $expected_order_id . "-" . $LP_next_suffix; } else { //it's a new order number $this_order_id = "WEB-" . $expected_order_id; } $myorder["oid"] = $this_order_id; //save this attempt to the database $q = "UPDATE #__{vm}_linkpoint SET LastAttempt = '" . $this_order_id . "' WHERE Id=1"; $dbLP->query($q); //old code // Working on a fix for this orderid, this process seems to send "Duplicate transaction" // if the user made a typo the first time they entered their card number. All in all, it works // but their could ba a change. // $myorder["oid"] = $order_number; // need to clean this up, no offence Soeren, but those order numbers are a mess. //end old code //END MOD // Debugging - Let me see the output. //$myorder["debugging"]="true"; // debugging (can move this block around to force result) // $vmLogger->err( "Credit Card Processing Under Test" ); // $d["order_payment_log"] = "Credit Card Processing Under Test"; // $d["order_payment_log"] .= "Please Call In Your Order"; // $d["order_payment_trans_id"] = "test1"; // return False; if (LP_RECURRING == "YES") { //if we are doing recurring billing, and the payments are not processed imedeately, we should run a Pre-Auth // This is mostly if you are offering a customer x ammount of free days for a service, if you are charging the card // at this time, you can uncomment the following 2 lines Pre-Auth part . if (LP_PREAUTH == "YES") { $myorder["ordertype"] = "PREAUTH"; // Process the PREAUTH $result = $mylphp->curl_process($myorder); if ($result["r_approved"] != "APPROVED") { // transaction failed, print the reason $vmLogger->err( $result["r_error"] ); $d["order_payment_log"] = $result["r_error"]; $d["order_payment_log"] .= $result["r_message"]; $d["order_payment_trans_id"] = $result["r_ordernum"]; return False; } } $myorder["action"] = "SUBMIT"; $myorder["installments"] = -1; $myorder["periodicity"] = monthly; // We will give them 30 days free. $myorder["startdate"] = date(Ymd,time()+2592000); $myorder["threshold"] = 3; $myorder["ordertype"] = "SALE"; // If everything worked out fine, then process the order here and leave the class. Saved by the Bell $result = $mylphp->curl_process($myorder); if ($result["r_approved"] != "APPROVED") // transaction failed, print the reason { $vmLogger->err( $result["r_error"] ); $d["order_payment_log"] = $result["r_error"]; $d["order_payment_log"] .= $result["r_message"]; $d["order_payment_trans_id"] = $result["r_ordernum"]; return False; } else // Success, let's return { $d["order_payment_log"] = $VM_LANG->_('PHPSHOP_PAYMENT_TRANSACTION_SUCCESS').": "; $d["order_payment_log"] = $result["r_approved"]; // Catch Transaction ID $d["order_payment_trans_id"] = $result["r_ordernum"]; return True; } } else{ // Not recurring, just plain old sale. $myorder["ordertype"] = "SALE"; // If everything worked out fine, then process the order. $result = $mylphp->curl_process($myorder); if ($result["r_approved"] != "APPROVED") // transaction failed, print the reason { $vmLogger->err( $result["r_error"] . "\n" . $result["r_message"] ); $d["order_payment_log"] = $result["r_error"]; $d["order_payment_log"] .= $result["r_message"]; $d["order_payment_trans_id"] = $result["r_ordernum"]; return False; } else // Success, let's return { $d["order_payment_log"] = $VM_LANG->_('PHPSHOP_PAYMENT_TRANSACTION_SUCCESS').": "; $d["order_payment_log"] = $result["r_approved"]; // Catch Transaction ID $d["order_payment_trans_id"] = $result["r_ordernum"]; return True; } } //close recurring or normal }//close function } //close class ?> administrator/components/com_virtuemart/classes/payment/ps_montrada.cfg.php100644 0 0 470 10732276304 25167 0ustar 0 0 administrator/components/com_virtuemart/classes/payment/ps_montrada.php100644 0 0 35151 11263443355 24477 0ustar 0 0 classname.".cfg.php"); ?>

    _('PHPSHOP_PAYMENT_CVV2') ?> _('PHPSHOP_PAYMENT_CVV2_TOOLTIP') ?>
    _('PHPSHOP_ADMIN_CFG_MONTRADA_USERNAME') ?>
    _('PHPSHOP_ADMIN_CFG_MONTRADA_PASSWORD') ?>
    _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_SUCC') ?> _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_SUCC_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_FAIL') ?> _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_FAIL_EXPLAIN') ?>
    classname.".cfg.php" ); } /** * Returns the "is_readable" status of the configuration file * @param void * @returns boolean True when the configuration file is writeable, false when not */ function configfile_readable() { return is_readable( CLASSPATH."payment/".$this->classname.".cfg.php" ); } /** * Writes the configuration file for this payment method * @param array An array of objects * @returns boolean True when writing was successful */ function write_configuration( &$d ) { $my_config_array = array( "MO_CHECK_CARD_CODE" => $d['MO_CHECK_CARD_CODE'], "MO_VERIFIED_STATUS" => $d['MO_VERIFIED_STATUS'], "MO_INVALID_STATUS" => $d['MO_INVALID_STATUS'], "MO_USERNAME" => $d['MO_USERNAME'], "MO_PASSWORD" => $d['MO_PASSWORD'] ); $config = " $value ) { $config .= "define ('$key', '$value');\n"; } $config .= "?".">"; if ($fp = fopen(CLASSPATH ."payment/".$this->classname.".cfg.php", "w")) { fputs($fp, $config, strlen($config)); fclose ($fp); return true; } else return false; } /************************************************************************** ** name: process_payment() ** created by: Benjamin Schirmer ** description: process transaction with Montrada GmbH ** parameters: $order_number, the number of the order, we're processing here ** $order_total, the total $ of the order ** returns: ***************************************************************************/ function process_payment($order_number, $order_total, &$d) { global $vendor_mail, $vendor_currency, $VM_LANG, $vmLogger; $ps_vendor_id = $_SESSION["ps_vendor_id"]; $auth = $_SESSION['auth']; $ps_checkout = new ps_checkout; /*** Get the Configuration File for authorize.net ***/ require_once(CLASSPATH ."payment/".$this->classname.".cfg.php"); // Get user billing information $dbbt = new ps_DB; $qt = "SELECT * FROM #__{vm}_user_info WHERE user_id='".$auth["user_id"]."' AND address_type='BT'"; $dbbt->query($qt); $dbbt->next_record(); $user_info_id = $dbbt->f("user_info_id"); if( $user_info_id != $d["ship_to_info_id"]) { // Get user billing information $dbst = new ps_DB; $qt = "SELECT * FROM #__{vm}_user_info WHERE user_info_id='".$d["ship_to_info_id"]."' AND address_type='ST'"; $dbst->query($qt); $dbst->next_record(); } else { $dbst = $dbbt; } $host = "posh.montrada.de"; $port = 443; $path = "/posh/cmd/posh/tpl/txn_result.tpl"; //Montrada vars to send $formdata = array ( 'command' => 'authorization', 'orderid' => substr($order_number, 0, 20), 'creditc' => $_SESSION['ccdata']['order_payment_number'], 'expdat' => substr($_SESSION['ccdata']['order_payment_expire_year'], 2, 2).$_SESSION['ccdata']['order_payment_expire_month'], 'currency' => $vendor_currency, 'amount' => $order_total*100, 'cvcode' => $_SESSION['ccdata']['credit_card_code'] ); //build the post string $poststring = ''; foreach($formdata AS $key => $val){ $poststring .= urlencode($key) . "=" . urlencode($val) . "&"; } // strip off trailing ampersand $poststring = substr($poststring, 0, -1); /* DEBUG Message */ if ($this->debug) { $vmLogger->debug( wordwrap($poststring, 60, "
    ", 1) ); } if( function_exists( "curl_init" )) { $CR = curl_init(); curl_setopt($CR, CURLOPT_URL, "https://".$host.$path); curl_setopt($CR, CURLOPT_POST, 1); curl_setopt($CR, CURLOPT_FAILONERROR, true); curl_setopt($CR, CURLOPT_POSTFIELDS, $poststring); curl_setopt($CR, CURLOPT_USERPWD, MO_USERNAME.":".MO_PASSWORD); curl_setopt($CR, CURLOPT_RETURNTRANSFER, 1); // No PEER certificate validation...as we don't have // a certificate file for it to authenticate the host www.ups.com against! curl_setopt($CR, CURLOPT_SSL_VERIFYPEER, 0); //curl_setopt($CR, CURLOPT_SSLCERT , "/usr/locale/xxxx/clientcertificate.pem"); $result = curl_exec( $CR ); $error = curl_error( $CR ); if( !empty( $error )) { $vmLogger->err( curl_error( $CR ) ."
    ".$VM_LANG->_('PHPSHOP_PAYMENT_INTERNAL_ERROR')." authorize.net" ); return false; } else { //echo $result; exit(); } curl_close( $CR ); } else { $fp = fsockopen("ssl://".$host, $port, $errno, $errstr, $timeout = 60); if(!$fp){ //error tell us $vmLogger->err( "$errstr ($errno)" ); } else { //send the server request fputs($fp, "POST $path HTTP/1.1\r\n"); fputs($fp, "Host: $host\r\n"); fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n"); fputs($fp, "Content-length: ".strlen($poststring)."\r\n"); fputs($fp, "Authorization: Basic ".base64_encode(MO_USERNAME.":".MO_PASSWORD)."\r\n"); fputs($fp, "Connection: close\r\n\r\n"); fputs($fp, $poststring . "\r\n\r\n"); //Get the response header from the server $data = ""; while (!feof($fp)) { $data .= fgets ($fp, 1024); } $data = explode("\r\n\r\n", $data); $result = trim( $data[1] ); } } /* DEBUG Message */ if ($this->debug) $vmLogger->debug( wordwrap( urldecode($result), 60, "
    ", 1) ); // Split Response-Data $data = explode("&", $result); foreach ($data as $var) { $var = explode("=", $var); $key = urldecode( $var[0] ); $value = urldecode( $var[1] ); $response[$key] = $value; } // Array of posherr values that get displayed $posherr1 = array("0", "100", "2014", "2016", "2018", "2040", "2042", "2048", "2090". "2092", "2094", "2202", "2204"); /* Display these error messages (ordered by id) 0 (Transaktion erfolgreich abgeschlossen) 100 (Transaktion ohne Erfolg abgeschlossen) 2014 (Kartennummer, Parameter 'creditc' falsch) 2016 (G�ltigkeitsdatum, Parameter 'expdat' falsch) 2018 (Kartenpr�fwert, Parameter 'cvcode' falsch) 2040 (Anfang oder L�nge der Kartennummer falsch) 2042 (Pr�fsumme der Kartennummer falsch) 2048 (Karte abgelaufen) 2090 (Bankleitzahl, Parameter 'bankcode' falsch) 2092 (Kontonummer, Parameter 'account' falsch) 2094 (Name, Parameter 'cname' falsch) 2202 (Bankleitzahl unbekannt) 2204 (Kontonummer paSst nicht zur Bankleitzahl) */ // Array of rc values that get display if posherr=100 $rc1 = array("000", "005", "033", "091", "096"); // Approved - Success! if (isset($response['posherr']) && ($response['posherr'] == 0)) { $d["order_payment_log"] = $VM_LANG->_('PHPSHOP_PAYMENT_TRANSACTION_SUCCESS').": "; $d["order_payment_log"] .= $response['rmsg']; // Catch Transaction ID $d["order_payment_trans_id"] = $response['trefnum']; return True; $db = new ps_DB; $q = "UPDATE #__{vm}_order_payment SET order_payment_code='',order_payment_number='',order_payment_expire='' WHERE order_id=$order_number"; $db->query($q); $db->next_record(); } else { if ($response['posherr'] = "") $response['posherr'] = -1; $vmLogger->err( $VM_LANG->_('PHPSHOP_PAYMENT_ERROR',false)." ($response[posherr])" ); if (in_array($response['posherr'], $posherr1)) { if ($response['posherr'] == 100) { if (in_array($response['rc'], $rc1)) $vmLogger->err( $response['rmsg'] ); } else { $vmLogger->err( $response['rmsg'] ); } } $d["order_payment_log"] = $response['rmsg']; // Catch Transaction ID $d["order_payment_trans_id"] = $response['retrefnr']; return False; } } } ?>administrator/components/com_virtuemart/classes/payment/ps_nochex.cfg.php100644 0 0 1333 10717123254 24663 0ustar 0 0 administrator/components/com_virtuemart/classes/payment/ps_nochex.php100644 0 0 6751 11176513601 24135 0ustar 0 0 classname.".cfg.php"); ?>
    _('PHPSHOP_ADMIN_CFG_NOCHEX_EMAIL')?> _('PHPSHOP_ADMIN_CFG_NOCHEX_EMAIL_EXPLAIN')?>
    classname.".cfg.php" ); } /** * Returns the "is_readable" status of the configuration file * @param void * @returns boolean True when the configuration file is writeable, false when not */ function configfile_readable() { return is_readable( CLASSPATH."payment/".$this->classname.".cfg.php" ); } /** * Writes the configuration file for this payment method * @param array An array of objects * @returns boolean True when writing was successful */ function write_configuration( &$d ) { $my_config_array = array("NOCHEX_EMAIL" => $d['NOCHEX_EMAIL']); $config = " $value ) { $config .= "define ('$key', '$value');\n"; } $config .= "?>"; if ($fp = fopen(CLASSPATH ."payment/".$this->classname.".cfg.php", "w")) { fputs($fp, $config, strlen($config)); fclose ($fp); return true; } else return false; } /************************************************************************** ** name: process_payment() ** returns: ***************************************************************************/ function process_payment($order_number, $order_total, &$d) { return true; } } administrator/components/com_virtuemart/classes/payment/ps_paymate.cfg.php100644 0 0 1520 10732276304 25037 0ustar 0 0 administrator/components/com_virtuemart/classes/payment/ps_paymate.php100644 0 0 7134 11176513601 24305 0ustar 0 0 classname.".cfg.php"); ?>
    _('PHPSHOP_ADMIN_CFG_PAYMATE_USERNAME') ?> _('PHPSHOP_ADMIN_CFG_PAYMATE_USERNAME_EXPLAIN') ?>
    classname.".cfg.php" ); } /** * Returns the "is_readable" status of the configuration file * @param void * @returns boolean True when the configuration file is writeable, false when not */ function configfile_readable() { return is_readable( CLASSPATH."payment/".$this->classname.".cfg.php" ); } /** * Writes the configuration file for this payment method * @param array An array of objects * @returns boolean True when writing was successful */ function write_configuration( &$d ) { $my_config_array = array("PAYMATE_USERNAME" => $d['PAYMATE_USERNAME'] ); $config = " $value ) { $config .= "define ('$key', '$value');\n"; } $config .= "?>"; if ($fp = fopen(CLASSPATH ."payment/".$this->classname.".cfg.php", "w")) { fputs($fp, $config, strlen($config)); fclose ($fp); return true; } else return false; } /************************************************************************** ** name: process_payment() ** returns: ***************************************************************************/ function process_payment($order_number, $order_total, &$d) { return true; } } administrator/components/com_virtuemart/classes/payment/ps_paymenow.cfg.php100644 0 0 1663 10732276304 25246 0ustar 0 0 administrator/components/com_virtuemart/classes/payment/ps_paymenow.php100644 0 0 22415 11263443355 24530 0ustar 0 0 classname.".cfg.php"); ?>
    _('PHPSHOP_ADMIN_CFG_PN_LOGIN') ?> _('PHPSHOP_ADMIN_CFG_PN_LOGIN_EXPLAIN') ?>
    _('PHPSHOP_PAYMENT_CVV2') ?> _('PHPSHOP_PAYMENT_CVV2_TOOLTIP') ?>
    _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_SUCC') ?> _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_SUCC_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_FAIL') ?> _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_FAIL_EXPLAIN') ?>
    classname.".cfg.php" ); } /** * Returns the "is_readable" status of the configuration file * @param void * @returns boolean True when the configuration file is writeable, false when not */ function configfile_readable() { return is_readable( CLASSPATH."payment/".$this->classname.".cfg.php" ); } /** * Writes the configuration file for this payment method * @param array An array of objects * @returns boolean True when writing was successful */ function write_configuration( &$d ) { $my_config_array = array("PN_LOGIN" => $d['PN_LOGIN'], "PN_CHECK_CARD_CODE" => $d['PN_CHECK_CARD_CODE'], "PN_VERIFIED_STATUS" => $d['PN_VERIFIED_STATUS'], "PN_INVALID_STATUS" => $d['PN_INVALID_STATUS'] ); $config = " $value ) { $config .= "define ('$key', '$value');\n"; } $config .= "?>"; if ($fp = fopen(CLASSPATH ."payment/".$this->classname.".cfg.php", "w")) { fputs($fp, $config, strlen($config)); fclose ($fp); return true; } else return false; } /************************************************************************** ** name: process_payment() ** created by: ryan ** description: process transaction for PayMeNow ** parameters: $order_number, the number of the order, we're processing here ** $order_total, the total $ of the order ** returns: ***************************************************************************/ function process_payment($order_number, $order_total, &$d) { global $vmLogger; require_once(CLASSPATH ."payment/".__CLASS__.".cfg.php"); $vars = array( "action" => "ns_quicksale_cc", "ecxid" => PN_LOGIN, "amount" => "$order_total", "ccname" => $_SESSION['ccdata']['order_payment_name'], "ccnum" => $_SESSION['ccdata']['order_payment_number'], "expmon" => $_SESSION['ccdata']['order_payment_expire_month'], "expyear"=> $_SESSION['ccdata']['order_payment_expire_year'] ); $results = http_post("trans.atsbank.com", 443, "/cgi-bin/trans.cgi",$vars); if (stristr($results, "Accepted")) { #Clean up the cart, send out the emails, and display thankyyou page. return true; } else { if ($reason = stristr($results, "Declined")) { $vmLogger->err( "The transaction was declined because of: $reason
    " ); } else { $vmLogger->err( "FATAL ERROR! Declined for an unknown reason, possibly a server misconfiguration error.
    $results" ); } return false; } #echo $results; } } function http_post($server, $port, $url, $vars) { // example: // http_post( // "www.fat.com", // 80, // "/weightloss.pl", // array("name" => "obese bob", "age" => "20") // ); $user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)"; $urlencoded = ""; while (list($key,$value) = each($vars)) $urlencoded.= urlencode($key) . "=" . urlencode($value) . "&"; $urlencoded = substr($urlencoded,0,-1); $content_length = strlen($urlencoded); $headers = "POST $url HTTP/1.1 Accept: */* Accept-Language: en-au Content-Type: application/x-www-form-urlencoded User-Agent: $user_agent Host: $server Connection: Keep-Alive Cache-Control: no-cache Content-Length: $content_length "; #$fp = fsockopen($host, $port, $errno, $errstr, $timeout = 60); $fp = fsockopen("ssl://".$server, $port, $errno, $errstr); if (!$fp) { # return false; } fputs($fp, $headers); fputs($fp, $urlencoded); $ret = ""; error_reporting(0); while (!feof($fp)) { $ret.= fgets($fp, 4096); } error_reporting(E_ALL ^ E_NOTICE); fclose($fp); #$ret = stristr($ret, 'html'); return $ret; } administrator/components/com_virtuemart/classes/payment/ps_payment.php100644 0 0 4660 10732276304 24326 0ustar 0 0 classname.".cfg.php" ); } /** * Returns the "is_readable" status of the configuration file * @param void * @returns boolean True when the configuration file is writeable, false when not */ function configfile_readable() { return is_readable( CLASSPATH."payment/".$this->classname.".cfg.php" ); } /** * Writes the configuration file for this payment method * @param array An array of objects * @returns boolean True when writing was successful */ function write_configuration( &$d ) { /* ... */ } /************************************************************************** ** name: process_payment() ** returns: ***************************************************************************/ function process_payment($order_number, $order_total, &$d) { return true; } } administrator/components/com_virtuemart/classes/payment/ps_paypal.cfg.php100644 0 0 1754 10732276304 24676 0ustar 0 0 administrator/components/com_virtuemart/classes/payment/ps_paypal.php100644 0 0 21312 10732276304 24150 0ustar 0 0 classname.".cfg.php"); ?>
    _('PHPSHOP_ADMIN_CFG_ENABLE_AUTORIZENET_TESTMODE') ?> _('VM_ADMIN_CFG_PAYPAL_NOTIFYSCRIPT_TIP'), '
    '. COMPONENTURL."notify.php
    " ); ?>
    _('PHPSHOP_ADMIN_CFG_PAYPAL_EMAIL') ?> _('PHPSHOP_ADMIN_CFG_PAYPAL_EMAIL_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_PAYPAL_STATUS_SUCCESS') ?> _('PHPSHOP_ADMIN_CFG_PAYPAL_STATUS_SUCCESS_EXPLAIN') ?>
    _('VM_ADMIN_CFG_PAYPAL_STATUS_PENDING') ?> _('VM_ADMIN_CFG_PAYPAL_STATUS_PENDING_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_PAYPAL_ONLYVERIFIED') ?> _('PHPSHOP_ADMIN_CFG_PAYPAL_ONLYVERIFIED_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_PAYPAL_STATUS_FAILED') ?> _('PHPSHOP_ADMIN_CFG_PAYPAL_STATUS_FAILED_EXPLAIN') ?>
    classname.".cfg.php" ); } /** * Returns the "is_readable" status of the configuration file * @param void * @returns boolean True when the configuration file is writeable, false when not */ function configfile_readable() { return is_readable( CLASSPATH."payment/".$this->classname.".cfg.php" ); } /** * Writes the configuration file for this payment method * @param array An array of objects * @returns boolean True when writing was successful */ function write_configuration( &$d ) { $my_config_array = array( "PAYPAL_DEBUG" => $d['PAYPAL_DEBUG'], "PAYPAL_EMAIL" => $d['PAYPAL_EMAIL'], "PAYPAL_VERIFIED_ONLY" => $d['PAYPAL_VERIFIED_ONLY'], "PAYPAL_VERIFIED_STATUS" => $d['PAYPAL_VERIFIED_STATUS'], "PAYPAL_PENDING_STATUS" => $d['PAYPAL_PENDING_STATUS'], "PAYPAL_INVALID_STATUS" => $d['PAYPAL_INVALID_STATUS'] ); $config = " $value ) { $config .= "define ('$key', '$value');\n"; } $config .= "?>"; if ($fp = fopen(CLASSPATH ."payment/".$this->classname.".cfg.php", "w")) { fputs($fp, $config, strlen($config)); fclose ($fp); return true; } else return false; } /************************************************************************** ** name: process_payment() ** returns: ***************************************************************************/ function process_payment($order_number, $order_total, &$d) { return true; } } administrator/components/com_virtuemart/classes/payment/ps_paysbuy.cfg.php100644 0 0 432 11246673567 25071 0ustar 0 0 administrator/components/com_virtuemart/classes/payment/ps_paysbuy.php100644 0 0 14277 11220612113 24353 0ustar 0 0 classname.".cfg.php"); ?>
    PaySbuy Email The Email-Account for your PaySbuy Payments.
    Currency Currency
    GateWay Choose Gateway For Payment
    Language Choose Language
    Form PaySbuy
    classname.".cfg.php" ); } /** * Returns the "is_readable" status of the configuration file * @param void * @returns boolean True when the configuration file is writeable, false when not */ function configfile_readable() { return is_readable( CLASSPATH."payment/".$this->classname.".cfg.php" ); } /** * Writes the configuration file for this payment method * @param array An array of objects * @returns boolean True when writing was successful */ function write_configuration( &$d ) { $my_config_array = array( "PaySbuy_EMAIL" => $d['PaySbuy_EMAIL'], "PaySbuy_CURRENCY" => $d['PaySbuy_CURRENCY'], "PaySbuy_GATEWAY" => $d['PaySbuy_GATEWAY'], "PaySbuy_LANG" => $d['PaySbuy_LANG'] ); $config = " $value ) { $config .= "define ('$key', '$value');\n"; } $config .= "?>"; if ($fp = fopen(CLASSPATH ."payment/".$this->classname.".cfg.php", "w")) { fputs($fp, $config, strlen($config)); fclose ($fp); return true; } else return false; } /************************************************************************** ** name: process_payment() ** returns: ***************************************************************************/ function process_payment($order_number, $order_total, &$d) { return true; } } administrator/components/com_virtuemart/classes/payment/ps_twocheckout.cfg.php100644 0 0 561 10732276304 25722 0ustar 0 0 administrator/components/com_virtuemart/classes/payment/ps_twocheckout.php100644 0 0 20376 11176513601 25227 0ustar 0 0 classname.".cfg.php"); ?>
    _('PHPSHOP_ADMIN_CFG_2CHECKOUT_LOGIN') ?> _('PHPSHOP_ADMIN_CFG_2CHECKOUT_LOGIN_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_2CHECKOUT_SECRETWORD') ?> _('PHPSHOP_ADMIN_CFG_2CHECKOUT_SECRETWORD_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_SUCC') ?> _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_SUCC_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_FAIL') ?> _('PHPSHOP_ADMIN_CFG_PAYMENT_ORDERSTATUS_FAIL_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_2CHECKOUT_MERCHANT_NOTIF') ?> _('PHPSHOP_ADMIN_CFG_2CHECKOUT_MERCHANT_NOTIF_EXPLAIN') ?>
    _('PHPSHOP_ADMIN_CFG_ENABLE_AUTORIZENET_TESTMODE') ?> _('PHPSHOP_ADMIN_CFG_ENABLE_AUTORIZENET_TESTMODE_EXPLAIN') ?>
    classname.".cfg.php" ); } /** * Returns the "is_readable" status of the configuration file * @param void * @returns boolean True when the configuration file is writeable, false when not */ function configfile_readable() { return is_readable( CLASSPATH."payment/".$this->classname.".cfg.php" ); } /** * Writes the configuration file for this payment method * @param array An array of objects * @returns boolean True when writing was successful */ function write_configuration( &$d ) { $my_config_array = array("TWOCO_LOGIN" => $d['TWOCO_LOGIN'], "TWOCO_SECRETWORD" => $d['TWOCO_SECRETWORD'], "TWOCO_VERIFIED_STATUS" => $d['TWOCO_VERIFIED_STATUS'], "TWOCO_INVALID_STATUS" => $d['TWOCO_INVALID_STATUS'], "TWOCO_TESTMODE" => $d['TWOCO_TESTMODE'], "TWOCO_MERCHANT_EMAIL" => $d['TWOCO_MERCHANT_EMAIL'] ); $config = " $value ) { $config .= "define ('$key', '$value');\n"; } $config .= "?>"; if ($fp = fopen(CLASSPATH ."payment/".$this->classname.".cfg.php", "w")) { fputs($fp, $config, strlen($config)); fclose ($fp); return true; } else return false; } /************************************************************************** ** name: process_payment() ** created by: soeren ** description: ** parameters: $order_number, the number of the order, we're processing here ** $order_total, the total $ of the order ** returns: ***************************************************************************/ function process_payment($order_number, $order_total, &$d) { return true; } } administrator/components/com_virtuemart/classes/payment/ps_worldpay.cfg.php100644 0 0 1514 10732276304 25243 0ustar 0 0 administrator/components/com_virtuemart/classes/payment/ps_worldpay.php100644 0 0 7062 11176513601 24506 0ustar 0 0 classname.".cfg.php"); ?>
    _('PHPSHOP_ADMIN_CFG_WORLDPAY_INSTID') ?> _('PHPSHOP_ADMIN_CFG_WORLDPAY_INSTID_EXPLAIN') ?>
    classname.".cfg.php" ); } /** * Returns the "is_readable" status of the configuration file * @param void * @returns boolean True when the configuration file is writeable, false when not */ function configfile_readable() { return is_readable( CLASSPATH."payment/".$this->classname.".cfg.php" ); } /** * Writes the configuration file for this payment method * @param array An array of objects * @returns boolean True when writing was successful */ function write_configuration( &$d ) { $my_config_array = array("WORLDPAY_INST_ID" => $d['WORLDPAY_INST_ID'] ); $config = " $value ) { $config .= "define ('$key', '$value');\n"; } $config .= "?>"; if ($fp = fopen(CLASSPATH ."payment/".$this->classname.".cfg.php", "w")) { fputs($fp, $config, strlen($config)); fclose ($fp); return true; } else return false; } /************************************************************************** ** name: process_payment() ** returns: ***************************************************************************/ function process_payment($order_number, $order_total, &$d) { return true; } } administrator/components/com_virtuemart/classes/pdf/credits.txt100644 0 0 2135 10547254314 22724 0ustar 0 0 ********* *CREDITS* __________ ********* Thanks to: -Olivier Plathey for the fpdf.php class [http://www.fpdf.org] -Damon Kohler for the Flowing Block script [mailto:damonkohler@yahoo.com] -Clment Lavoillotte for HTML-oriented FPDF idea -Yamasoft for the gif.php class [http://www.yamasoft.com/] -Jrme Fenal for the _parsegif() function -"VIETCOM" for the PDFTable code [http://www.freepgs.com/vietcom/tool/pdftable/] [mailto:vncommando@yahoo.com] -Yukihiro O. for the SetDash() function [mailto:yukihiro_o@infoseek.jp] -Ron Korving for the WordWrap() function -Michel Poulain for the DisplayPreferences() function -Patrick Benny for the MultiCellBlt() function idea [no longer in use] -Seb for the _SetTextRendering() and SetTextOutline() functions [mailto:captainseb@wanadoo.fr] -MorphSoft for the colornames list idea -W3SCHOOLS for HTML-related reference info [http://www.w3schools.com/] __________________ Special Thanks to: --- Montfort Cultural Association - the site for which I generated this script [http://www.montfort.org.br] administrator/components/com_virtuemart/classes/pdf/font/courier.php100644 0 0 2021 10732276304 23646 0ustar 0 0 administrator/components/com_virtuemart/classes/pdf/font/helvetica.php100644 0 0 7554 10732276304 24162 0ustar 0 0 278,chr(1)=>278,chr(2)=>278,chr(3)=>278,chr(4)=>278,chr(5)=>278,chr(6)=>278,chr(7)=>278,chr(8)=>278,chr(9)=>278,chr(10)=>278,chr(11)=>278,chr(12)=>278,chr(13)=>278,chr(14)=>278,chr(15)=>278,chr(16)=>278,chr(17)=>278,chr(18)=>278,chr(19)=>278,chr(20)=>278,chr(21)=>278, chr(22)=>278,chr(23)=>278,chr(24)=>278,chr(25)=>278,chr(26)=>278,chr(27)=>278,chr(28)=>278,chr(29)=>278,chr(30)=>278,chr(31)=>278,' '=>278,'!'=>278,'"'=>355,'#'=>556,'$'=>556,'%'=>889,'&'=>667,'\''=>191,'('=>333,')'=>333,'*'=>389,'+'=>584, ','=>278,'-'=>333,'.'=>278,'/'=>278,'0'=>556,'1'=>556,'2'=>556,'3'=>556,'4'=>556,'5'=>556,'6'=>556,'7'=>556,'8'=>556,'9'=>556,':'=>278,';'=>278,'<'=>584,'='=>584,'>'=>584,'?'=>556,'@'=>1015,'A'=>667, 'B'=>667,'C'=>722,'D'=>722,'E'=>667,'F'=>611,'G'=>778,'H'=>722,'I'=>278,'J'=>500,'K'=>667,'L'=>556,'M'=>833,'N'=>722,'O'=>778,'P'=>667,'Q'=>778,'R'=>722,'S'=>667,'T'=>611,'U'=>722,'V'=>667,'W'=>944, 'X'=>667,'Y'=>667,'Z'=>611,'['=>278,'\\'=>278,']'=>278,'^'=>469,'_'=>556,'`'=>333,'a'=>556,'b'=>556,'c'=>500,'d'=>556,'e'=>556,'f'=>278,'g'=>556,'h'=>556,'i'=>222,'j'=>222,'k'=>500,'l'=>222,'m'=>833, 'n'=>556,'o'=>556,'p'=>556,'q'=>556,'r'=>333,'s'=>500,'t'=>278,'u'=>556,'v'=>500,'w'=>722,'x'=>500,'y'=>500,'z'=>500,'{'=>334,'|'=>260,'}'=>334,'~'=>584,chr(127)=>350,chr(128)=>556,chr(129)=>350,chr(130)=>222,chr(131)=>556, chr(132)=>333,chr(133)=>1000,chr(134)=>556,chr(135)=>556,chr(136)=>333,chr(137)=>1000,chr(138)=>667,chr(139)=>333,chr(140)=>1000,chr(141)=>350,chr(142)=>611,chr(143)=>350,chr(144)=>350,chr(145)=>222,chr(146)=>222,chr(147)=>333,chr(148)=>333,chr(149)=>350,chr(150)=>556,chr(151)=>1000,chr(152)=>333,chr(153)=>1000, chr(154)=>500,chr(155)=>333,chr(156)=>944,chr(157)=>350,chr(158)=>500,chr(159)=>667,chr(160)=>278,chr(161)=>333,chr(162)=>556,chr(163)=>556,chr(164)=>556,chr(165)=>556,chr(166)=>260,chr(167)=>556,chr(168)=>333,chr(169)=>737,chr(170)=>370,chr(171)=>556,chr(172)=>584,chr(173)=>333,chr(174)=>737,chr(175)=>333, chr(176)=>400,chr(177)=>584,chr(178)=>333,chr(179)=>333,chr(180)=>333,chr(181)=>556,chr(182)=>537,chr(183)=>278,chr(184)=>333,chr(185)=>333,chr(186)=>365,chr(187)=>556,chr(188)=>834,chr(189)=>834,chr(190)=>834,chr(191)=>611,chr(192)=>667,chr(193)=>667,chr(194)=>667,chr(195)=>667,chr(196)=>667,chr(197)=>667, chr(198)=>1000,chr(199)=>722,chr(200)=>667,chr(201)=>667,chr(202)=>667,chr(203)=>667,chr(204)=>278,chr(205)=>278,chr(206)=>278,chr(207)=>278,chr(208)=>722,chr(209)=>722,chr(210)=>778,chr(211)=>778,chr(212)=>778,chr(213)=>778,chr(214)=>778,chr(215)=>584,chr(216)=>778,chr(217)=>722,chr(218)=>722,chr(219)=>722, chr(220)=>722,chr(221)=>667,chr(222)=>667,chr(223)=>611,chr(224)=>556,chr(225)=>556,chr(226)=>556,chr(227)=>556,chr(228)=>556,chr(229)=>556,chr(230)=>889,chr(231)=>500,chr(232)=>556,chr(233)=>556,chr(234)=>556,chr(235)=>556,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>556,chr(241)=>556, chr(242)=>556,chr(243)=>556,chr(244)=>556,chr(245)=>556,chr(246)=>556,chr(247)=>584,chr(248)=>611,chr(249)=>556,chr(250)=>556,chr(251)=>556,chr(252)=>556,chr(253)=>500,chr(254)=>556,chr(255)=>500); ?> administrator/components/com_virtuemart/classes/pdf/font/helveticab.php100644 0 0 7555 10732276304 24325 0ustar 0 0 278,chr(1)=>278,chr(2)=>278,chr(3)=>278,chr(4)=>278,chr(5)=>278,chr(6)=>278,chr(7)=>278,chr(8)=>278,chr(9)=>278,chr(10)=>278,chr(11)=>278,chr(12)=>278,chr(13)=>278,chr(14)=>278,chr(15)=>278,chr(16)=>278,chr(17)=>278,chr(18)=>278,chr(19)=>278,chr(20)=>278,chr(21)=>278, chr(22)=>278,chr(23)=>278,chr(24)=>278,chr(25)=>278,chr(26)=>278,chr(27)=>278,chr(28)=>278,chr(29)=>278,chr(30)=>278,chr(31)=>278,' '=>278,'!'=>333,'"'=>474,'#'=>556,'$'=>556,'%'=>889,'&'=>722,'\''=>238,'('=>333,')'=>333,'*'=>389,'+'=>584, ','=>278,'-'=>333,'.'=>278,'/'=>278,'0'=>556,'1'=>556,'2'=>556,'3'=>556,'4'=>556,'5'=>556,'6'=>556,'7'=>556,'8'=>556,'9'=>556,':'=>333,';'=>333,'<'=>584,'='=>584,'>'=>584,'?'=>611,'@'=>975,'A'=>722, 'B'=>722,'C'=>722,'D'=>722,'E'=>667,'F'=>611,'G'=>778,'H'=>722,'I'=>278,'J'=>556,'K'=>722,'L'=>611,'M'=>833,'N'=>722,'O'=>778,'P'=>667,'Q'=>778,'R'=>722,'S'=>667,'T'=>611,'U'=>722,'V'=>667,'W'=>944, 'X'=>667,'Y'=>667,'Z'=>611,'['=>333,'\\'=>278,']'=>333,'^'=>584,'_'=>556,'`'=>333,'a'=>556,'b'=>611,'c'=>556,'d'=>611,'e'=>556,'f'=>333,'g'=>611,'h'=>611,'i'=>278,'j'=>278,'k'=>556,'l'=>278,'m'=>889, 'n'=>611,'o'=>611,'p'=>611,'q'=>611,'r'=>389,'s'=>556,'t'=>333,'u'=>611,'v'=>556,'w'=>778,'x'=>556,'y'=>556,'z'=>500,'{'=>389,'|'=>280,'}'=>389,'~'=>584,chr(127)=>350,chr(128)=>556,chr(129)=>350,chr(130)=>278,chr(131)=>556, chr(132)=>500,chr(133)=>1000,chr(134)=>556,chr(135)=>556,chr(136)=>333,chr(137)=>1000,chr(138)=>667,chr(139)=>333,chr(140)=>1000,chr(141)=>350,chr(142)=>611,chr(143)=>350,chr(144)=>350,chr(145)=>278,chr(146)=>278,chr(147)=>500,chr(148)=>500,chr(149)=>350,chr(150)=>556,chr(151)=>1000,chr(152)=>333,chr(153)=>1000, chr(154)=>556,chr(155)=>333,chr(156)=>944,chr(157)=>350,chr(158)=>500,chr(159)=>667,chr(160)=>278,chr(161)=>333,chr(162)=>556,chr(163)=>556,chr(164)=>556,chr(165)=>556,chr(166)=>280,chr(167)=>556,chr(168)=>333,chr(169)=>737,chr(170)=>370,chr(171)=>556,chr(172)=>584,chr(173)=>333,chr(174)=>737,chr(175)=>333, chr(176)=>400,chr(177)=>584,chr(178)=>333,chr(179)=>333,chr(180)=>333,chr(181)=>611,chr(182)=>556,chr(183)=>278,chr(184)=>333,chr(185)=>333,chr(186)=>365,chr(187)=>556,chr(188)=>834,chr(189)=>834,chr(190)=>834,chr(191)=>611,chr(192)=>722,chr(193)=>722,chr(194)=>722,chr(195)=>722,chr(196)=>722,chr(197)=>722, chr(198)=>1000,chr(199)=>722,chr(200)=>667,chr(201)=>667,chr(202)=>667,chr(203)=>667,chr(204)=>278,chr(205)=>278,chr(206)=>278,chr(207)=>278,chr(208)=>722,chr(209)=>722,chr(210)=>778,chr(211)=>778,chr(212)=>778,chr(213)=>778,chr(214)=>778,chr(215)=>584,chr(216)=>778,chr(217)=>722,chr(218)=>722,chr(219)=>722, chr(220)=>722,chr(221)=>667,chr(222)=>667,chr(223)=>611,chr(224)=>556,chr(225)=>556,chr(226)=>556,chr(227)=>556,chr(228)=>556,chr(229)=>556,chr(230)=>889,chr(231)=>556,chr(232)=>556,chr(233)=>556,chr(234)=>556,chr(235)=>556,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>611,chr(241)=>611, chr(242)=>611,chr(243)=>611,chr(244)=>611,chr(245)=>611,chr(246)=>611,chr(247)=>584,chr(248)=>611,chr(249)=>611,chr(250)=>611,chr(251)=>611,chr(252)=>611,chr(253)=>556,chr(254)=>611,chr(255)=>556); ?> administrator/components/com_virtuemart/classes/pdf/font/helveticabi.php100644 0 0 7557 10732276304 24500 0ustar 0 0 278,chr(1)=>278,chr(2)=>278,chr(3)=>278,chr(4)=>278,chr(5)=>278,chr(6)=>278,chr(7)=>278,chr(8)=>278,chr(9)=>278,chr(10)=>278,chr(11)=>278,chr(12)=>278,chr(13)=>278,chr(14)=>278,chr(15)=>278,chr(16)=>278,chr(17)=>278,chr(18)=>278,chr(19)=>278,chr(20)=>278,chr(21)=>278, chr(22)=>278,chr(23)=>278,chr(24)=>278,chr(25)=>278,chr(26)=>278,chr(27)=>278,chr(28)=>278,chr(29)=>278,chr(30)=>278,chr(31)=>278,' '=>278,'!'=>333,'"'=>474,'#'=>556,'$'=>556,'%'=>889,'&'=>722,'\''=>238,'('=>333,')'=>333,'*'=>389,'+'=>584, ','=>278,'-'=>333,'.'=>278,'/'=>278,'0'=>556,'1'=>556,'2'=>556,'3'=>556,'4'=>556,'5'=>556,'6'=>556,'7'=>556,'8'=>556,'9'=>556,':'=>333,';'=>333,'<'=>584,'='=>584,'>'=>584,'?'=>611,'@'=>975,'A'=>722, 'B'=>722,'C'=>722,'D'=>722,'E'=>667,'F'=>611,'G'=>778,'H'=>722,'I'=>278,'J'=>556,'K'=>722,'L'=>611,'M'=>833,'N'=>722,'O'=>778,'P'=>667,'Q'=>778,'R'=>722,'S'=>667,'T'=>611,'U'=>722,'V'=>667,'W'=>944, 'X'=>667,'Y'=>667,'Z'=>611,'['=>333,'\\'=>278,']'=>333,'^'=>584,'_'=>556,'`'=>333,'a'=>556,'b'=>611,'c'=>556,'d'=>611,'e'=>556,'f'=>333,'g'=>611,'h'=>611,'i'=>278,'j'=>278,'k'=>556,'l'=>278,'m'=>889, 'n'=>611,'o'=>611,'p'=>611,'q'=>611,'r'=>389,'s'=>556,'t'=>333,'u'=>611,'v'=>556,'w'=>778,'x'=>556,'y'=>556,'z'=>500,'{'=>389,'|'=>280,'}'=>389,'~'=>584,chr(127)=>350,chr(128)=>556,chr(129)=>350,chr(130)=>278,chr(131)=>556, chr(132)=>500,chr(133)=>1000,chr(134)=>556,chr(135)=>556,chr(136)=>333,chr(137)=>1000,chr(138)=>667,chr(139)=>333,chr(140)=>1000,chr(141)=>350,chr(142)=>611,chr(143)=>350,chr(144)=>350,chr(145)=>278,chr(146)=>278,chr(147)=>500,chr(148)=>500,chr(149)=>350,chr(150)=>556,chr(151)=>1000,chr(152)=>333,chr(153)=>1000, chr(154)=>556,chr(155)=>333,chr(156)=>944,chr(157)=>350,chr(158)=>500,chr(159)=>667,chr(160)=>278,chr(161)=>333,chr(162)=>556,chr(163)=>556,chr(164)=>556,chr(165)=>556,chr(166)=>280,chr(167)=>556,chr(168)=>333,chr(169)=>737,chr(170)=>370,chr(171)=>556,chr(172)=>584,chr(173)=>333,chr(174)=>737,chr(175)=>333, chr(176)=>400,chr(177)=>584,chr(178)=>333,chr(179)=>333,chr(180)=>333,chr(181)=>611,chr(182)=>556,chr(183)=>278,chr(184)=>333,chr(185)=>333,chr(186)=>365,chr(187)=>556,chr(188)=>834,chr(189)=>834,chr(190)=>834,chr(191)=>611,chr(192)=>722,chr(193)=>722,chr(194)=>722,chr(195)=>722,chr(196)=>722,chr(197)=>722, chr(198)=>1000,chr(199)=>722,chr(200)=>667,chr(201)=>667,chr(202)=>667,chr(203)=>667,chr(204)=>278,chr(205)=>278,chr(206)=>278,chr(207)=>278,chr(208)=>722,chr(209)=>722,chr(210)=>778,chr(211)=>778,chr(212)=>778,chr(213)=>778,chr(214)=>778,chr(215)=>584,chr(216)=>778,chr(217)=>722,chr(218)=>722,chr(219)=>722, chr(220)=>722,chr(221)=>667,chr(222)=>667,chr(223)=>611,chr(224)=>556,chr(225)=>556,chr(226)=>556,chr(227)=>556,chr(228)=>556,chr(229)=>556,chr(230)=>889,chr(231)=>556,chr(232)=>556,chr(233)=>556,chr(234)=>556,chr(235)=>556,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>611,chr(241)=>611, chr(242)=>611,chr(243)=>611,chr(244)=>611,chr(245)=>611,chr(246)=>611,chr(247)=>584,chr(248)=>611,chr(249)=>611,chr(250)=>611,chr(251)=>611,chr(252)=>611,chr(253)=>556,chr(254)=>611,chr(255)=>556); ?> administrator/components/com_virtuemart/classes/pdf/font/helveticai.php100644 0 0 7556 10732276304 24335 0ustar 0 0 278,chr(1)=>278,chr(2)=>278,chr(3)=>278,chr(4)=>278,chr(5)=>278,chr(6)=>278,chr(7)=>278,chr(8)=>278,chr(9)=>278,chr(10)=>278,chr(11)=>278,chr(12)=>278,chr(13)=>278,chr(14)=>278,chr(15)=>278,chr(16)=>278,chr(17)=>278,chr(18)=>278,chr(19)=>278,chr(20)=>278,chr(21)=>278, chr(22)=>278,chr(23)=>278,chr(24)=>278,chr(25)=>278,chr(26)=>278,chr(27)=>278,chr(28)=>278,chr(29)=>278,chr(30)=>278,chr(31)=>278,' '=>278,'!'=>278,'"'=>355,'#'=>556,'$'=>556,'%'=>889,'&'=>667,'\''=>191,'('=>333,')'=>333,'*'=>389,'+'=>584, ','=>278,'-'=>333,'.'=>278,'/'=>278,'0'=>556,'1'=>556,'2'=>556,'3'=>556,'4'=>556,'5'=>556,'6'=>556,'7'=>556,'8'=>556,'9'=>556,':'=>278,';'=>278,'<'=>584,'='=>584,'>'=>584,'?'=>556,'@'=>1015,'A'=>667, 'B'=>667,'C'=>722,'D'=>722,'E'=>667,'F'=>611,'G'=>778,'H'=>722,'I'=>278,'J'=>500,'K'=>667,'L'=>556,'M'=>833,'N'=>722,'O'=>778,'P'=>667,'Q'=>778,'R'=>722,'S'=>667,'T'=>611,'U'=>722,'V'=>667,'W'=>944, 'X'=>667,'Y'=>667,'Z'=>611,'['=>278,'\\'=>278,']'=>278,'^'=>469,'_'=>556,'`'=>333,'a'=>556,'b'=>556,'c'=>500,'d'=>556,'e'=>556,'f'=>278,'g'=>556,'h'=>556,'i'=>222,'j'=>222,'k'=>500,'l'=>222,'m'=>833, 'n'=>556,'o'=>556,'p'=>556,'q'=>556,'r'=>333,'s'=>500,'t'=>278,'u'=>556,'v'=>500,'w'=>722,'x'=>500,'y'=>500,'z'=>500,'{'=>334,'|'=>260,'}'=>334,'~'=>584,chr(127)=>350,chr(128)=>556,chr(129)=>350,chr(130)=>222,chr(131)=>556, chr(132)=>333,chr(133)=>1000,chr(134)=>556,chr(135)=>556,chr(136)=>333,chr(137)=>1000,chr(138)=>667,chr(139)=>333,chr(140)=>1000,chr(141)=>350,chr(142)=>611,chr(143)=>350,chr(144)=>350,chr(145)=>222,chr(146)=>222,chr(147)=>333,chr(148)=>333,chr(149)=>350,chr(150)=>556,chr(151)=>1000,chr(152)=>333,chr(153)=>1000, chr(154)=>500,chr(155)=>333,chr(156)=>944,chr(157)=>350,chr(158)=>500,chr(159)=>667,chr(160)=>278,chr(161)=>333,chr(162)=>556,chr(163)=>556,chr(164)=>556,chr(165)=>556,chr(166)=>260,chr(167)=>556,chr(168)=>333,chr(169)=>737,chr(170)=>370,chr(171)=>556,chr(172)=>584,chr(173)=>333,chr(174)=>737,chr(175)=>333, chr(176)=>400,chr(177)=>584,chr(178)=>333,chr(179)=>333,chr(180)=>333,chr(181)=>556,chr(182)=>537,chr(183)=>278,chr(184)=>333,chr(185)=>333,chr(186)=>365,chr(187)=>556,chr(188)=>834,chr(189)=>834,chr(190)=>834,chr(191)=>611,chr(192)=>667,chr(193)=>667,chr(194)=>667,chr(195)=>667,chr(196)=>667,chr(197)=>667, chr(198)=>1000,chr(199)=>722,chr(200)=>667,chr(201)=>667,chr(202)=>667,chr(203)=>667,chr(204)=>278,chr(205)=>278,chr(206)=>278,chr(207)=>278,chr(208)=>722,chr(209)=>722,chr(210)=>778,chr(211)=>778,chr(212)=>778,chr(213)=>778,chr(214)=>778,chr(215)=>584,chr(216)=>778,chr(217)=>722,chr(218)=>722,chr(219)=>722, chr(220)=>722,chr(221)=>667,chr(222)=>667,chr(223)=>611,chr(224)=>556,chr(225)=>556,chr(226)=>556,chr(227)=>556,chr(228)=>556,chr(229)=>556,chr(230)=>889,chr(231)=>500,chr(232)=>556,chr(233)=>556,chr(234)=>556,chr(235)=>556,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>556,chr(241)=>556, chr(242)=>556,chr(243)=>556,chr(244)=>556,chr(245)=>556,chr(246)=>556,chr(247)=>584,chr(248)=>611,chr(249)=>556,chr(250)=>556,chr(251)=>556,chr(252)=>556,chr(253)=>500,chr(254)=>556,chr(255)=>500); ?> administrator/components/com_virtuemart/classes/pdf/font/index.html100644 0 0 0 10547254314 23376 0ustar 0 0 administrator/components/com_virtuemart/classes/pdf/font/symbol.php100644 0 0 7435 10732276304 23521 0ustar 0 0 250,chr(1)=>250,chr(2)=>250,chr(3)=>250,chr(4)=>250,chr(5)=>250,chr(6)=>250,chr(7)=>250,chr(8)=>250,chr(9)=>250,chr(10)=>250,chr(11)=>250,chr(12)=>250,chr(13)=>250,chr(14)=>250,chr(15)=>250,chr(16)=>250,chr(17)=>250,chr(18)=>250,chr(19)=>250,chr(20)=>250,chr(21)=>250, chr(22)=>250,chr(23)=>250,chr(24)=>250,chr(25)=>250,chr(26)=>250,chr(27)=>250,chr(28)=>250,chr(29)=>250,chr(30)=>250,chr(31)=>250,' '=>250,'!'=>333,'"'=>713,'#'=>500,'$'=>549,'%'=>833,'&'=>778,'\''=>439,'('=>333,')'=>333,'*'=>500,'+'=>549, ','=>250,'-'=>549,'.'=>250,'/'=>278,'0'=>500,'1'=>500,'2'=>500,'3'=>500,'4'=>500,'5'=>500,'6'=>500,'7'=>500,'8'=>500,'9'=>500,':'=>278,';'=>278,'<'=>549,'='=>549,'>'=>549,'?'=>444,'@'=>549,'A'=>722, 'B'=>667,'C'=>722,'D'=>612,'E'=>611,'F'=>763,'G'=>603,'H'=>722,'I'=>333,'J'=>631,'K'=>722,'L'=>686,'M'=>889,'N'=>722,'O'=>722,'P'=>768,'Q'=>741,'R'=>556,'S'=>592,'T'=>611,'U'=>690,'V'=>439,'W'=>768, 'X'=>645,'Y'=>795,'Z'=>611,'['=>333,'\\'=>863,']'=>333,'^'=>658,'_'=>500,'`'=>500,'a'=>631,'b'=>549,'c'=>549,'d'=>494,'e'=>439,'f'=>521,'g'=>411,'h'=>603,'i'=>329,'j'=>603,'k'=>549,'l'=>549,'m'=>576, 'n'=>521,'o'=>549,'p'=>549,'q'=>521,'r'=>549,'s'=>603,'t'=>439,'u'=>576,'v'=>713,'w'=>686,'x'=>493,'y'=>686,'z'=>494,'{'=>480,'|'=>200,'}'=>480,'~'=>549,chr(127)=>0,chr(128)=>0,chr(129)=>0,chr(130)=>0,chr(131)=>0, chr(132)=>0,chr(133)=>0,chr(134)=>0,chr(135)=>0,chr(136)=>0,chr(137)=>0,chr(138)=>0,chr(139)=>0,chr(140)=>0,chr(141)=>0,chr(142)=>0,chr(143)=>0,chr(144)=>0,chr(145)=>0,chr(146)=>0,chr(147)=>0,chr(148)=>0,chr(149)=>0,chr(150)=>0,chr(151)=>0,chr(152)=>0,chr(153)=>0, chr(154)=>0,chr(155)=>0,chr(156)=>0,chr(157)=>0,chr(158)=>0,chr(159)=>0,chr(160)=>750,chr(161)=>620,chr(162)=>247,chr(163)=>549,chr(164)=>167,chr(165)=>713,chr(166)=>500,chr(167)=>753,chr(168)=>753,chr(169)=>753,chr(170)=>753,chr(171)=>1042,chr(172)=>987,chr(173)=>603,chr(174)=>987,chr(175)=>603, chr(176)=>400,chr(177)=>549,chr(178)=>411,chr(179)=>549,chr(180)=>549,chr(181)=>713,chr(182)=>494,chr(183)=>460,chr(184)=>549,chr(185)=>549,chr(186)=>549,chr(187)=>549,chr(188)=>1000,chr(189)=>603,chr(190)=>1000,chr(191)=>658,chr(192)=>823,chr(193)=>686,chr(194)=>795,chr(195)=>987,chr(196)=>768,chr(197)=>768, chr(198)=>823,chr(199)=>768,chr(200)=>768,chr(201)=>713,chr(202)=>713,chr(203)=>713,chr(204)=>713,chr(205)=>713,chr(206)=>713,chr(207)=>713,chr(208)=>768,chr(209)=>713,chr(210)=>790,chr(211)=>790,chr(212)=>890,chr(213)=>823,chr(214)=>549,chr(215)=>250,chr(216)=>713,chr(217)=>603,chr(218)=>603,chr(219)=>1042, chr(220)=>987,chr(221)=>603,chr(222)=>987,chr(223)=>603,chr(224)=>494,chr(225)=>329,chr(226)=>790,chr(227)=>790,chr(228)=>786,chr(229)=>713,chr(230)=>384,chr(231)=>384,chr(232)=>384,chr(233)=>384,chr(234)=>384,chr(235)=>384,chr(236)=>494,chr(237)=>494,chr(238)=>494,chr(239)=>494,chr(240)=>0,chr(241)=>329, chr(242)=>274,chr(243)=>686,chr(244)=>686,chr(245)=>686,chr(246)=>384,chr(247)=>384,chr(248)=>384,chr(249)=>384,chr(250)=>384,chr(251)=>384,chr(252)=>494,chr(253)=>494,chr(254)=>494,chr(255)=>0); ?> administrator/components/com_virtuemart/classes/pdf/font/times.php100644 0 0 7540 10732276304 23332 0ustar 0 0 250,chr(1)=>250,chr(2)=>250,chr(3)=>250,chr(4)=>250,chr(5)=>250,chr(6)=>250,chr(7)=>250,chr(8)=>250,chr(9)=>250,chr(10)=>250,chr(11)=>250,chr(12)=>250,chr(13)=>250,chr(14)=>250,chr(15)=>250,chr(16)=>250,chr(17)=>250,chr(18)=>250,chr(19)=>250,chr(20)=>250,chr(21)=>250, chr(22)=>250,chr(23)=>250,chr(24)=>250,chr(25)=>250,chr(26)=>250,chr(27)=>250,chr(28)=>250,chr(29)=>250,chr(30)=>250,chr(31)=>250,' '=>250,'!'=>333,'"'=>408,'#'=>500,'$'=>500,'%'=>833,'&'=>778,'\''=>180,'('=>333,')'=>333,'*'=>500,'+'=>564, ','=>250,'-'=>333,'.'=>250,'/'=>278,'0'=>500,'1'=>500,'2'=>500,'3'=>500,'4'=>500,'5'=>500,'6'=>500,'7'=>500,'8'=>500,'9'=>500,':'=>278,';'=>278,'<'=>564,'='=>564,'>'=>564,'?'=>444,'@'=>921,'A'=>722, 'B'=>667,'C'=>667,'D'=>722,'E'=>611,'F'=>556,'G'=>722,'H'=>722,'I'=>333,'J'=>389,'K'=>722,'L'=>611,'M'=>889,'N'=>722,'O'=>722,'P'=>556,'Q'=>722,'R'=>667,'S'=>556,'T'=>611,'U'=>722,'V'=>722,'W'=>944, 'X'=>722,'Y'=>722,'Z'=>611,'['=>333,'\\'=>278,']'=>333,'^'=>469,'_'=>500,'`'=>333,'a'=>444,'b'=>500,'c'=>444,'d'=>500,'e'=>444,'f'=>333,'g'=>500,'h'=>500,'i'=>278,'j'=>278,'k'=>500,'l'=>278,'m'=>778, 'n'=>500,'o'=>500,'p'=>500,'q'=>500,'r'=>333,'s'=>389,'t'=>278,'u'=>500,'v'=>500,'w'=>722,'x'=>500,'y'=>500,'z'=>444,'{'=>480,'|'=>200,'}'=>480,'~'=>541,chr(127)=>350,chr(128)=>500,chr(129)=>350,chr(130)=>333,chr(131)=>500, chr(132)=>444,chr(133)=>1000,chr(134)=>500,chr(135)=>500,chr(136)=>333,chr(137)=>1000,chr(138)=>556,chr(139)=>333,chr(140)=>889,chr(141)=>350,chr(142)=>611,chr(143)=>350,chr(144)=>350,chr(145)=>333,chr(146)=>333,chr(147)=>444,chr(148)=>444,chr(149)=>350,chr(150)=>500,chr(151)=>1000,chr(152)=>333,chr(153)=>980, chr(154)=>389,chr(155)=>333,chr(156)=>722,chr(157)=>350,chr(158)=>444,chr(159)=>722,chr(160)=>250,chr(161)=>333,chr(162)=>500,chr(163)=>500,chr(164)=>500,chr(165)=>500,chr(166)=>200,chr(167)=>500,chr(168)=>333,chr(169)=>760,chr(170)=>276,chr(171)=>500,chr(172)=>564,chr(173)=>333,chr(174)=>760,chr(175)=>333, chr(176)=>400,chr(177)=>564,chr(178)=>300,chr(179)=>300,chr(180)=>333,chr(181)=>500,chr(182)=>453,chr(183)=>250,chr(184)=>333,chr(185)=>300,chr(186)=>310,chr(187)=>500,chr(188)=>750,chr(189)=>750,chr(190)=>750,chr(191)=>444,chr(192)=>722,chr(193)=>722,chr(194)=>722,chr(195)=>722,chr(196)=>722,chr(197)=>722, chr(198)=>889,chr(199)=>667,chr(200)=>611,chr(201)=>611,chr(202)=>611,chr(203)=>611,chr(204)=>333,chr(205)=>333,chr(206)=>333,chr(207)=>333,chr(208)=>722,chr(209)=>722,chr(210)=>722,chr(211)=>722,chr(212)=>722,chr(213)=>722,chr(214)=>722,chr(215)=>564,chr(216)=>722,chr(217)=>722,chr(218)=>722,chr(219)=>722, chr(220)=>722,chr(221)=>722,chr(222)=>556,chr(223)=>500,chr(224)=>444,chr(225)=>444,chr(226)=>444,chr(227)=>444,chr(228)=>444,chr(229)=>444,chr(230)=>667,chr(231)=>444,chr(232)=>444,chr(233)=>444,chr(234)=>444,chr(235)=>444,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>500,chr(241)=>500, chr(242)=>500,chr(243)=>500,chr(244)=>500,chr(245)=>500,chr(246)=>500,chr(247)=>564,chr(248)=>500,chr(249)=>500,chr(250)=>500,chr(251)=>500,chr(252)=>500,chr(253)=>500,chr(254)=>500,chr(255)=>500); ?> administrator/components/com_virtuemart/classes/pdf/font/timesb.php100644 0 0 7547 10732276304 23503 0ustar 0 0 250,chr(1)=>250,chr(2)=>250,chr(3)=>250,chr(4)=>250,chr(5)=>250,chr(6)=>250,chr(7)=>250,chr(8)=>250,chr(9)=>250,chr(10)=>250,chr(11)=>250,chr(12)=>250,chr(13)=>250,chr(14)=>250,chr(15)=>250,chr(16)=>250,chr(17)=>250,chr(18)=>250,chr(19)=>250,chr(20)=>250,chr(21)=>250, chr(22)=>250,chr(23)=>250,chr(24)=>250,chr(25)=>250,chr(26)=>250,chr(27)=>250,chr(28)=>250,chr(29)=>250,chr(30)=>250,chr(31)=>250,' '=>250,'!'=>333,'"'=>555,'#'=>500,'$'=>500,'%'=>1000,'&'=>833,'\''=>278,'('=>333,')'=>333,'*'=>500,'+'=>570, ','=>250,'-'=>333,'.'=>250,'/'=>278,'0'=>500,'1'=>500,'2'=>500,'3'=>500,'4'=>500,'5'=>500,'6'=>500,'7'=>500,'8'=>500,'9'=>500,':'=>333,';'=>333,'<'=>570,'='=>570,'>'=>570,'?'=>500,'@'=>930,'A'=>722, 'B'=>667,'C'=>722,'D'=>722,'E'=>667,'F'=>611,'G'=>778,'H'=>778,'I'=>389,'J'=>500,'K'=>778,'L'=>667,'M'=>944,'N'=>722,'O'=>778,'P'=>611,'Q'=>778,'R'=>722,'S'=>556,'T'=>667,'U'=>722,'V'=>722,'W'=>1000, 'X'=>722,'Y'=>722,'Z'=>667,'['=>333,'\\'=>278,']'=>333,'^'=>581,'_'=>500,'`'=>333,'a'=>500,'b'=>556,'c'=>444,'d'=>556,'e'=>444,'f'=>333,'g'=>500,'h'=>556,'i'=>278,'j'=>333,'k'=>556,'l'=>278,'m'=>833, 'n'=>556,'o'=>500,'p'=>556,'q'=>556,'r'=>444,'s'=>389,'t'=>333,'u'=>556,'v'=>500,'w'=>722,'x'=>500,'y'=>500,'z'=>444,'{'=>394,'|'=>220,'}'=>394,'~'=>520,chr(127)=>350,chr(128)=>500,chr(129)=>350,chr(130)=>333,chr(131)=>500, chr(132)=>500,chr(133)=>1000,chr(134)=>500,chr(135)=>500,chr(136)=>333,chr(137)=>1000,chr(138)=>556,chr(139)=>333,chr(140)=>1000,chr(141)=>350,chr(142)=>667,chr(143)=>350,chr(144)=>350,chr(145)=>333,chr(146)=>333,chr(147)=>500,chr(148)=>500,chr(149)=>350,chr(150)=>500,chr(151)=>1000,chr(152)=>333,chr(153)=>1000, chr(154)=>389,chr(155)=>333,chr(156)=>722,chr(157)=>350,chr(158)=>444,chr(159)=>722,chr(160)=>250,chr(161)=>333,chr(162)=>500,chr(163)=>500,chr(164)=>500,chr(165)=>500,chr(166)=>220,chr(167)=>500,chr(168)=>333,chr(169)=>747,chr(170)=>300,chr(171)=>500,chr(172)=>570,chr(173)=>333,chr(174)=>747,chr(175)=>333, chr(176)=>400,chr(177)=>570,chr(178)=>300,chr(179)=>300,chr(180)=>333,chr(181)=>556,chr(182)=>540,chr(183)=>250,chr(184)=>333,chr(185)=>300,chr(186)=>330,chr(187)=>500,chr(188)=>750,chr(189)=>750,chr(190)=>750,chr(191)=>500,chr(192)=>722,chr(193)=>722,chr(194)=>722,chr(195)=>722,chr(196)=>722,chr(197)=>722, chr(198)=>1000,chr(199)=>722,chr(200)=>667,chr(201)=>667,chr(202)=>667,chr(203)=>667,chr(204)=>389,chr(205)=>389,chr(206)=>389,chr(207)=>389,chr(208)=>722,chr(209)=>722,chr(210)=>778,chr(211)=>778,chr(212)=>778,chr(213)=>778,chr(214)=>778,chr(215)=>570,chr(216)=>778,chr(217)=>722,chr(218)=>722,chr(219)=>722, chr(220)=>722,chr(221)=>722,chr(222)=>611,chr(223)=>556,chr(224)=>500,chr(225)=>500,chr(226)=>500,chr(227)=>500,chr(228)=>500,chr(229)=>500,chr(230)=>722,chr(231)=>444,chr(232)=>444,chr(233)=>444,chr(234)=>444,chr(235)=>444,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>500,chr(241)=>556, chr(242)=>500,chr(243)=>500,chr(244)=>500,chr(245)=>500,chr(246)=>500,chr(247)=>570,chr(248)=>500,chr(249)=>556,chr(250)=>556,chr(251)=>556,chr(252)=>556,chr(253)=>500,chr(254)=>556,chr(255)=>500); ?> administrator/components/com_virtuemart/classes/pdf/font/timesbi.php100644 0 0 7545 10732276304 23652 0ustar 0 0 250,chr(1)=>250,chr(2)=>250,chr(3)=>250,chr(4)=>250,chr(5)=>250,chr(6)=>250,chr(7)=>250,chr(8)=>250,chr(9)=>250,chr(10)=>250,chr(11)=>250,chr(12)=>250,chr(13)=>250,chr(14)=>250,chr(15)=>250,chr(16)=>250,chr(17)=>250,chr(18)=>250,chr(19)=>250,chr(20)=>250,chr(21)=>250, chr(22)=>250,chr(23)=>250,chr(24)=>250,chr(25)=>250,chr(26)=>250,chr(27)=>250,chr(28)=>250,chr(29)=>250,chr(30)=>250,chr(31)=>250,' '=>250,'!'=>389,'"'=>555,'#'=>500,'$'=>500,'%'=>833,'&'=>778,'\''=>278,'('=>333,')'=>333,'*'=>500,'+'=>570, ','=>250,'-'=>333,'.'=>250,'/'=>278,'0'=>500,'1'=>500,'2'=>500,'3'=>500,'4'=>500,'5'=>500,'6'=>500,'7'=>500,'8'=>500,'9'=>500,':'=>333,';'=>333,'<'=>570,'='=>570,'>'=>570,'?'=>500,'@'=>832,'A'=>667, 'B'=>667,'C'=>667,'D'=>722,'E'=>667,'F'=>667,'G'=>722,'H'=>778,'I'=>389,'J'=>500,'K'=>667,'L'=>611,'M'=>889,'N'=>722,'O'=>722,'P'=>611,'Q'=>722,'R'=>667,'S'=>556,'T'=>611,'U'=>722,'V'=>667,'W'=>889, 'X'=>667,'Y'=>611,'Z'=>611,'['=>333,'\\'=>278,']'=>333,'^'=>570,'_'=>500,'`'=>333,'a'=>500,'b'=>500,'c'=>444,'d'=>500,'e'=>444,'f'=>333,'g'=>500,'h'=>556,'i'=>278,'j'=>278,'k'=>500,'l'=>278,'m'=>778, 'n'=>556,'o'=>500,'p'=>500,'q'=>500,'r'=>389,'s'=>389,'t'=>278,'u'=>556,'v'=>444,'w'=>667,'x'=>500,'y'=>444,'z'=>389,'{'=>348,'|'=>220,'}'=>348,'~'=>570,chr(127)=>350,chr(128)=>500,chr(129)=>350,chr(130)=>333,chr(131)=>500, chr(132)=>500,chr(133)=>1000,chr(134)=>500,chr(135)=>500,chr(136)=>333,chr(137)=>1000,chr(138)=>556,chr(139)=>333,chr(140)=>944,chr(141)=>350,chr(142)=>611,chr(143)=>350,chr(144)=>350,chr(145)=>333,chr(146)=>333,chr(147)=>500,chr(148)=>500,chr(149)=>350,chr(150)=>500,chr(151)=>1000,chr(152)=>333,chr(153)=>1000, chr(154)=>389,chr(155)=>333,chr(156)=>722,chr(157)=>350,chr(158)=>389,chr(159)=>611,chr(160)=>250,chr(161)=>389,chr(162)=>500,chr(163)=>500,chr(164)=>500,chr(165)=>500,chr(166)=>220,chr(167)=>500,chr(168)=>333,chr(169)=>747,chr(170)=>266,chr(171)=>500,chr(172)=>606,chr(173)=>333,chr(174)=>747,chr(175)=>333, chr(176)=>400,chr(177)=>570,chr(178)=>300,chr(179)=>300,chr(180)=>333,chr(181)=>576,chr(182)=>500,chr(183)=>250,chr(184)=>333,chr(185)=>300,chr(186)=>300,chr(187)=>500,chr(188)=>750,chr(189)=>750,chr(190)=>750,chr(191)=>500,chr(192)=>667,chr(193)=>667,chr(194)=>667,chr(195)=>667,chr(196)=>667,chr(197)=>667, chr(198)=>944,chr(199)=>667,chr(200)=>667,chr(201)=>667,chr(202)=>667,chr(203)=>667,chr(204)=>389,chr(205)=>389,chr(206)=>389,chr(207)=>389,chr(208)=>722,chr(209)=>722,chr(210)=>722,chr(211)=>722,chr(212)=>722,chr(213)=>722,chr(214)=>722,chr(215)=>570,chr(216)=>722,chr(217)=>722,chr(218)=>722,chr(219)=>722, chr(220)=>722,chr(221)=>611,chr(222)=>611,chr(223)=>500,chr(224)=>500,chr(225)=>500,chr(226)=>500,chr(227)=>500,chr(228)=>500,chr(229)=>500,chr(230)=>722,chr(231)=>444,chr(232)=>444,chr(233)=>444,chr(234)=>444,chr(235)=>444,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>500,chr(241)=>556, chr(242)=>500,chr(243)=>500,chr(244)=>500,chr(245)=>500,chr(246)=>500,chr(247)=>570,chr(248)=>500,chr(249)=>556,chr(250)=>556,chr(251)=>556,chr(252)=>556,chr(253)=>444,chr(254)=>500,chr(255)=>444); ?> administrator/components/com_virtuemart/classes/pdf/font/timesi.php100644 0 0 7540 10732276304 23503 0ustar 0 0 250,chr(1)=>250,chr(2)=>250,chr(3)=>250,chr(4)=>250,chr(5)=>250,chr(6)=>250,chr(7)=>250,chr(8)=>250,chr(9)=>250,chr(10)=>250,chr(11)=>250,chr(12)=>250,chr(13)=>250,chr(14)=>250,chr(15)=>250,chr(16)=>250,chr(17)=>250,chr(18)=>250,chr(19)=>250,chr(20)=>250,chr(21)=>250, chr(22)=>250,chr(23)=>250,chr(24)=>250,chr(25)=>250,chr(26)=>250,chr(27)=>250,chr(28)=>250,chr(29)=>250,chr(30)=>250,chr(31)=>250,' '=>250,'!'=>333,'"'=>420,'#'=>500,'$'=>500,'%'=>833,'&'=>778,'\''=>214,'('=>333,')'=>333,'*'=>500,'+'=>675, ','=>250,'-'=>333,'.'=>250,'/'=>278,'0'=>500,'1'=>500,'2'=>500,'3'=>500,'4'=>500,'5'=>500,'6'=>500,'7'=>500,'8'=>500,'9'=>500,':'=>333,';'=>333,'<'=>675,'='=>675,'>'=>675,'?'=>500,'@'=>920,'A'=>611, 'B'=>611,'C'=>667,'D'=>722,'E'=>611,'F'=>611,'G'=>722,'H'=>722,'I'=>333,'J'=>444,'K'=>667,'L'=>556,'M'=>833,'N'=>667,'O'=>722,'P'=>611,'Q'=>722,'R'=>611,'S'=>500,'T'=>556,'U'=>722,'V'=>611,'W'=>833, 'X'=>611,'Y'=>556,'Z'=>556,'['=>389,'\\'=>278,']'=>389,'^'=>422,'_'=>500,'`'=>333,'a'=>500,'b'=>500,'c'=>444,'d'=>500,'e'=>444,'f'=>278,'g'=>500,'h'=>500,'i'=>278,'j'=>278,'k'=>444,'l'=>278,'m'=>722, 'n'=>500,'o'=>500,'p'=>500,'q'=>500,'r'=>389,'s'=>389,'t'=>278,'u'=>500,'v'=>444,'w'=>667,'x'=>444,'y'=>444,'z'=>389,'{'=>400,'|'=>275,'}'=>400,'~'=>541,chr(127)=>350,chr(128)=>500,chr(129)=>350,chr(130)=>333,chr(131)=>500, chr(132)=>556,chr(133)=>889,chr(134)=>500,chr(135)=>500,chr(136)=>333,chr(137)=>1000,chr(138)=>500,chr(139)=>333,chr(140)=>944,chr(141)=>350,chr(142)=>556,chr(143)=>350,chr(144)=>350,chr(145)=>333,chr(146)=>333,chr(147)=>556,chr(148)=>556,chr(149)=>350,chr(150)=>500,chr(151)=>889,chr(152)=>333,chr(153)=>980, chr(154)=>389,chr(155)=>333,chr(156)=>667,chr(157)=>350,chr(158)=>389,chr(159)=>556,chr(160)=>250,chr(161)=>389,chr(162)=>500,chr(163)=>500,chr(164)=>500,chr(165)=>500,chr(166)=>275,chr(167)=>500,chr(168)=>333,chr(169)=>760,chr(170)=>276,chr(171)=>500,chr(172)=>675,chr(173)=>333,chr(174)=>760,chr(175)=>333, chr(176)=>400,chr(177)=>675,chr(178)=>300,chr(179)=>300,chr(180)=>333,chr(181)=>500,chr(182)=>523,chr(183)=>250,chr(184)=>333,chr(185)=>300,chr(186)=>310,chr(187)=>500,chr(188)=>750,chr(189)=>750,chr(190)=>750,chr(191)=>500,chr(192)=>611,chr(193)=>611,chr(194)=>611,chr(195)=>611,chr(196)=>611,chr(197)=>611, chr(198)=>889,chr(199)=>667,chr(200)=>611,chr(201)=>611,chr(202)=>611,chr(203)=>611,chr(204)=>333,chr(205)=>333,chr(206)=>333,chr(207)=>333,chr(208)=>722,chr(209)=>667,chr(210)=>722,chr(211)=>722,chr(212)=>722,chr(213)=>722,chr(214)=>722,chr(215)=>675,chr(216)=>722,chr(217)=>722,chr(218)=>722,chr(219)=>722, chr(220)=>722,chr(221)=>556,chr(222)=>611,chr(223)=>500,chr(224)=>500,chr(225)=>500,chr(226)=>500,chr(227)=>500,chr(228)=>500,chr(229)=>500,chr(230)=>667,chr(231)=>444,chr(232)=>444,chr(233)=>444,chr(234)=>444,chr(235)=>444,chr(236)=>278,chr(237)=>278,chr(238)=>278,chr(239)=>278,chr(240)=>500,chr(241)=>500, chr(242)=>500,chr(243)=>500,chr(244)=>500,chr(245)=>500,chr(246)=>500,chr(247)=>675,chr(248)=>500,chr(249)=>500,chr(250)=>500,chr(251)=>500,chr(252)=>500,chr(253)=>444,chr(254)=>500,chr(255)=>444); ?> administrator/components/com_virtuemart/classes/pdf/font/zapfdingbats.php100644 0 0 7400 10732276304 24660 0ustar 0 0 0,chr(1)=>0,chr(2)=>0,chr(3)=>0,chr(4)=>0,chr(5)=>0,chr(6)=>0,chr(7)=>0,chr(8)=>0,chr(9)=>0,chr(10)=>0,chr(11)=>0,chr(12)=>0,chr(13)=>0,chr(14)=>0,chr(15)=>0,chr(16)=>0,chr(17)=>0,chr(18)=>0,chr(19)=>0,chr(20)=>0,chr(21)=>0, chr(22)=>0,chr(23)=>0,chr(24)=>0,chr(25)=>0,chr(26)=>0,chr(27)=>0,chr(28)=>0,chr(29)=>0,chr(30)=>0,chr(31)=>0,' '=>278,'!'=>974,'"'=>961,'#'=>974,'$'=>980,'%'=>719,'&'=>789,'\''=>790,'('=>791,')'=>690,'*'=>960,'+'=>939, ','=>549,'-'=>855,'.'=>911,'/'=>933,'0'=>911,'1'=>945,'2'=>974,'3'=>755,'4'=>846,'5'=>762,'6'=>761,'7'=>571,'8'=>677,'9'=>763,':'=>760,';'=>759,'<'=>754,'='=>494,'>'=>552,'?'=>537,'@'=>577,'A'=>692, 'B'=>786,'C'=>788,'D'=>788,'E'=>790,'F'=>793,'G'=>794,'H'=>816,'I'=>823,'J'=>789,'K'=>841,'L'=>823,'M'=>833,'N'=>816,'O'=>831,'P'=>923,'Q'=>744,'R'=>723,'S'=>749,'T'=>790,'U'=>792,'V'=>695,'W'=>776, 'X'=>768,'Y'=>792,'Z'=>759,'['=>707,'\\'=>708,']'=>682,'^'=>701,'_'=>826,'`'=>815,'a'=>789,'b'=>789,'c'=>707,'d'=>687,'e'=>696,'f'=>689,'g'=>786,'h'=>787,'i'=>713,'j'=>791,'k'=>785,'l'=>791,'m'=>873, 'n'=>761,'o'=>762,'p'=>762,'q'=>759,'r'=>759,'s'=>892,'t'=>892,'u'=>788,'v'=>784,'w'=>438,'x'=>138,'y'=>277,'z'=>415,'{'=>392,'|'=>392,'}'=>668,'~'=>668,chr(127)=>0,chr(128)=>390,chr(129)=>390,chr(130)=>317,chr(131)=>317, chr(132)=>276,chr(133)=>276,chr(134)=>509,chr(135)=>509,chr(136)=>410,chr(137)=>410,chr(138)=>234,chr(139)=>234,chr(140)=>334,chr(141)=>334,chr(142)=>0,chr(143)=>0,chr(144)=>0,chr(145)=>0,chr(146)=>0,chr(147)=>0,chr(148)=>0,chr(149)=>0,chr(150)=>0,chr(151)=>0,chr(152)=>0,chr(153)=>0, chr(154)=>0,chr(155)=>0,chr(156)=>0,chr(157)=>0,chr(158)=>0,chr(159)=>0,chr(160)=>0,chr(161)=>732,chr(162)=>544,chr(163)=>544,chr(164)=>910,chr(165)=>667,chr(166)=>760,chr(167)=>760,chr(168)=>776,chr(169)=>595,chr(170)=>694,chr(171)=>626,chr(172)=>788,chr(173)=>788,chr(174)=>788,chr(175)=>788, chr(176)=>788,chr(177)=>788,chr(178)=>788,chr(179)=>788,chr(180)=>788,chr(181)=>788,chr(182)=>788,chr(183)=>788,chr(184)=>788,chr(185)=>788,chr(186)=>788,chr(187)=>788,chr(188)=>788,chr(189)=>788,chr(190)=>788,chr(191)=>788,chr(192)=>788,chr(193)=>788,chr(194)=>788,chr(195)=>788,chr(196)=>788,chr(197)=>788, chr(198)=>788,chr(199)=>788,chr(200)=>788,chr(201)=>788,chr(202)=>788,chr(203)=>788,chr(204)=>788,chr(205)=>788,chr(206)=>788,chr(207)=>788,chr(208)=>788,chr(209)=>788,chr(210)=>788,chr(211)=>788,chr(212)=>894,chr(213)=>838,chr(214)=>1016,chr(215)=>458,chr(216)=>748,chr(217)=>924,chr(218)=>748,chr(219)=>918, chr(220)=>927,chr(221)=>928,chr(222)=>928,chr(223)=>834,chr(224)=>873,chr(225)=>828,chr(226)=>924,chr(227)=>924,chr(228)=>917,chr(229)=>930,chr(230)=>931,chr(231)=>463,chr(232)=>883,chr(233)=>836,chr(234)=>836,chr(235)=>867,chr(236)=>867,chr(237)=>696,chr(238)=>696,chr(239)=>874,chr(240)=>0,chr(241)=>874, chr(242)=>760,chr(243)=>946,chr(244)=>771,chr(245)=>865,chr(246)=>771,chr(247)=>888,chr(248)=>967,chr(249)=>888,chr(250)=>831,chr(251)=>873,chr(252)=>927,chr(253)=>970,chr(254)=>918,chr(255)=>0); ?> administrator/components/com_virtuemart/classes/pdf/fpdf.php100644 0 0 235733 11220414326 22220 0ustar 0 0 _dochecks(); //Initialization of properties $this->page=0; $this->n=2; $this->buffer=''; $this->pages=array(); $this->OrientationChanges=array(); $this->state=0; $this->fonts=array(); $this->FontFiles=array(); $this->diffs=array(); $this->images=array(); $this->links=array(); $this->InFooter=false; $this->lasth=0; $this->FontFamily=''; $this->FontStyle=''; $this->FontSizePt=12; $this->underline=false; $this->DrawColor='0 G'; $this->FillColor='0 g'; $this->TextColor='0 g'; $this->ColorFlag=false; $this->ws=0; //Standard fonts $this->CoreFonts=array('courier'=>'Courier','courierB'=>'Courier-Bold','courierI'=>'Courier-Oblique','courierBI'=>'Courier-BoldOblique', 'helvetica'=>'Helvetica','helveticaB'=>'Helvetica-Bold','helveticaI'=>'Helvetica-Oblique','helveticaBI'=>'Helvetica-BoldOblique', 'times'=>'Times-Roman','timesB'=>'Times-Bold','timesI'=>'Times-Italic','timesBI'=>'Times-BoldItalic', 'symbol'=>'Symbol','zapfdingbats'=>'ZapfDingbats'); //Scale factor if($unit=='pt') $this->k=1; elseif($unit=='mm') $this->k=72/25.4; elseif($unit=='cm') $this->k=72/2.54; elseif($unit=='in') $this->k=72; else $this->Error('Incorrect unit: '.$unit); //Page format if(is_string($format)) { $format=strtolower($format); if($format=='a3') $format=array(841.89,1190.55); elseif($format=='a4') $format=array(595.28,841.89); elseif($format=='a5') $format=array(420.94,595.28); elseif($format=='letter') $format=array(612,792); elseif($format=='legal') $format=array(612,1008); else $this->Error('Unknown page format: '.$format); $this->fwPt=$format[0]; $this->fhPt=$format[1]; } else { $this->fwPt=$format[0]*$this->k; $this->fhPt=$format[1]*$this->k; } $this->fw=$this->fwPt/$this->k; $this->fh=$this->fhPt/$this->k; //Page orientation $orientation=strtolower($orientation); if($orientation=='p' or $orientation=='portrait') { $this->DefOrientation='P'; $this->wPt=$this->fwPt; $this->hPt=$this->fhPt; } elseif($orientation=='l' or $orientation=='landscape') { $this->DefOrientation='L'; $this->wPt=$this->fhPt; $this->hPt=$this->fwPt; } else $this->Error('Incorrect orientation: '.$orientation); $this->CurOrientation=$this->DefOrientation; $this->w=$this->wPt/$this->k; $this->h=$this->hPt/$this->k; //Page margins (1 cm) $margin=28.35/$this->k; $this->SetMargins($margin,$margin); //Interior cell margin (1 mm) $this->cMargin=$margin/10; //Line width (0.2 mm) $this->LineWidth=.567/$this->k; //Automatic page break $this->SetAutoPageBreak(true,2*$margin); //Full width display mode $this->SetDisplayMode('fullwidth'); //Compression $this->SetCompression(true); } function SetMargins($left,$top,$right=-1) { //Set left, top and right margins $this->lMargin=$left; $this->tMargin=$top; if($right==-1) $right=$left; $this->rMargin=$right; } function SetLeftMargin($margin) { //Set left margin $this->lMargin=$margin; if($this->page>0 and $this->x<$margin) $this->x=$margin; } function SetTopMargin($margin) { //Set top margin $this->tMargin=$margin; } function SetRightMargin($margin) { //Set right margin $this->rMargin=$margin; } function SetAutoPageBreak($auto,$margin=0) { //Set auto page break mode and triggering margin $this->AutoPageBreak=$auto; $this->bMargin=$margin; $this->PageBreakTrigger=$this->h-$margin; } function SetDisplayMode($zoom,$layout='continuous') { //Set display mode in viewer if($zoom=='fullpage' or $zoom=='fullwidth' or $zoom=='real' or $zoom=='default' or !is_string($zoom)) $this->ZoomMode=$zoom; else $this->Error('Incorrect zoom display mode: '.$zoom); if($layout=='single' or $layout=='continuous' or $layout=='two' or $layout=='default') $this->LayoutMode=$layout; else $this->Error('Incorrect layout display mode: '.$layout); } function SetCompression($compress) { //Set page compression if(function_exists('gzcompress')) $this->compress=$compress; else $this->compress=false; } function SetTitle($title) { //Title of document $this->title=$title; } function SetSubject($subject) { //Subject of document $this->subject=$subject; } function SetAuthor($author) { //Author of document $this->author=$author; } function SetKeywords($keywords) { //Keywords of document $this->keywords=$keywords; } function SetCreator($creator) { //Creator of document $this->creator=$creator; } function AliasNbPages($alias='{nb}') { //Define an alias for total number of pages $this->AliasNbPages=$alias; } function Error($msg) { //Fatal error die('FPDF error: '.$msg); } function Open() { //Begin document if($this->state==0) $this->_begindoc(); } function Close() { //Terminate document if($this->state==3) return; if($this->page==0) $this->AddPage(); //Page footer $this->InFooter=true; $this->Footer(); $this->InFooter=false; //Close page $this->_endpage(); //Close document $this->_enddoc(); } function AddPage($orientation='') { //Start a new page if($this->state==0) $this->Open(); $family=$this->FontFamily; $style=$this->FontStyle.($this->underline ? 'U' : ''); $size=$this->FontSizePt; $lw=$this->LineWidth; $dc=$this->DrawColor; $fc=$this->FillColor; $tc=$this->TextColor; $cf=$this->ColorFlag; if($this->page>0) { //Page footer $this->InFooter=true; $this->Footer(); $this->InFooter=false; //Close page $this->_endpage(); } //Start new page $this->_beginpage($orientation); //Set line cap style to square $this->_out('2 J'); //Set line width $this->LineWidth=$lw; $this->_out(sprintf('%.2f w',$lw*$this->k)); //Set font if($family) $this->SetFont($family,$style,$size); //Set colors $this->DrawColor=$dc; if($dc!='0 G') $this->_out($dc); $this->FillColor=$fc; if($fc!='0 g') $this->_out($fc); $this->TextColor=$tc; $this->ColorFlag=$cf; //Page header $this->Header(); //Restore line width if($this->LineWidth!=$lw) { $this->LineWidth=$lw; $this->_out(sprintf('%.2f w',$lw*$this->k)); } //Restore font if($family) $this->SetFont($family,$style,$size); //Restore colors if($this->DrawColor!=$dc) { $this->DrawColor=$dc; $this->_out($dc); } if($this->FillColor!=$fc) { $this->FillColor=$fc; $this->_out($fc); } $this->TextColor=$tc; $this->ColorFlag=$cf; } function Header() { //To be implemented in your own inherited class } function Footer() { //To be implemented in your own inherited class } function PageNo() { //Get current page number return $this->page; } function SetDrawColor($r,$g=-1,$b=-1) { //Set color for all stroking operations if(($r==0 and $g==0 and $b==0) or $g==-1) $this->DrawColor=sprintf('%.3f G',$r/255); else $this->DrawColor=sprintf('%.3f %.3f %.3f RG',$r/255,$g/255,$b/255); if($this->page>0) $this->_out($this->DrawColor); } function SetFillColor($r,$g=-1,$b=-1) { //Set color for all filling operations if(($r==0 and $g==0 and $b==0) or $g==-1) $this->FillColor=sprintf('%.3f g',$r/255); else$this->FillColor=sprintf('%.3f %.3f %.3f rg',$r/255,$g/255,$b/255); $this->ColorFlag = ($this->FillColor != $this->TextColor); if($this->page>0) $this->_out($this->FillColor); } function SetTextColor($r,$g=-1,$b=-1) { //Set color for text if(($r==0 and $g==0 and $b==0) or $g==-1) $this->TextColor=sprintf('%.3f g',$r/255); else $this->TextColor=sprintf('%.3f %.3f %.3f rg',$r/255,$g/255,$b/255); $this->ColorFlag = ($this->FillColor != $this->TextColor); } function GetStringWidth($s) { //Get width of a string in the current font $s=(string)$s; $cw=&$this->CurrentFont['cw']; $w=0; $l=strlen($s); for($i=0;$i<$l;$i++) $w+=$cw[$s{$i}]; return $w*$this->FontSize/1000; } function SetLineWidth($width) { //Set line width $this->LineWidth=$width; if($this->page>0) $this->_out(sprintf('%.2f w',$width*$this->k)); } function Line($x1,$y1,$x2,$y2) { //Draw a line $this->_out(sprintf('%.2f %.2f m %.2f %.2f l S',$x1*$this->k,($this->h-$y1)*$this->k,$x2*$this->k,($this->h-$y2)*$this->k)); } function Rect($x,$y,$w,$h,$style='') { //Draw a rectangle if($style=='F') $op='f'; elseif($style=='FD' or $style=='DF') $op='B'; else $op='S'; $this->_out(sprintf('%.2f %.2f %.2f %.2f re %s',$x*$this->k,($this->h-$y)*$this->k,$w*$this->k,-$h*$this->k,$op)); } function AddFont($family,$style='',$file='') { //Add a TrueType or Type1 font $family=strtolower($family); if($family=='arial') $family='helvetica'; $style=strtoupper($style); if($style=='IB') $style='BI'; if(isset($this->fonts[$family.$style])) $this->Error('Font already added: '.$family.' '.$style); if($file=='') $file=str_replace(' ','',$family).strtolower($style).'.php'; if(defined('FPDF_FONTPATH')) $file=FPDF_FONTPATH.$file; include($file); if(!isset($name)) $this->Error('Could not include font definition file'); $i=count($this->fonts)+1; $this->fonts[$family.$style]=array('i'=>$i,'type'=>$type,'name'=>$name,'desc'=>$desc,'up'=>$up,'ut'=>$ut,'cw'=>$cw,'enc'=>$enc,'file'=>$file); if($diff) { //Search existing encodings $d=0; $nb=count($this->diffs); for($i=1;$i<=$nb;$i++) if($this->diffs[$i]==$diff) { $d=$i; break; } if($d==0) { $d=$nb+1; $this->diffs[$d]=$diff; } $this->fonts[$family.$style]['diff']=$d; } if($file) { if($type=='TrueType') $this->FontFiles[$file]=array('length1'=>$originalsize); else $this->FontFiles[$file]=array('length1'=>$size1,'length2'=>$size2); } } function SetFont($family,$style='',$size=0) { //Select a font; size given in points global $fpdf_charwidths; $family=strtolower($family); if($family=='') $family=$this->FontFamily; //EDITEI - now understands: monospace,serif,sans [serif] if($family=='monospace') $family='courier'; if($family=='serif') $family='times'; if($family=='sans') $family='arial'; if($family=='arial') $family='helvetica'; elseif($family=='symbol' or $family=='zapfdingbats') $style=''; $style=strtoupper($style); if(is_int(strpos($style,'U'))) { $this->underline=true; $style=str_replace('U','',$style); } else $this->underline=false; if ($style=='IB') $style='BI'; if ($size==0) $size=$this->FontSizePt; //Test if font is already selected if($this->FontFamily==$family and $this->FontStyle==$style and $this->FontSizePt==$size) return; //Test if used for the first time $fontkey=$family.$style; if(!isset($this->fonts[$fontkey])) { //Check if one of the standard fonts if(isset($this->CoreFonts[$fontkey])) { if(!isset($fpdf_charwidths[$fontkey])) { //Load metric file $file=$family; if($family=='times' or $family=='helvetica') $file.=strtolower($style); $file.='.php'; if(defined('FPDF_FONTPATH')) $file=FPDF_FONTPATH.$file; include($file); if(!isset($fpdf_charwidths[$fontkey])) $this->Error('Could not include font metric file'); } $i=count($this->fonts)+1; $this->fonts[$fontkey]=array('i'=>$i,'type'=>'core','name'=>$this->CoreFonts[$fontkey],'up'=>-100,'ut'=>50,'cw'=>$fpdf_charwidths[$fontkey]); } else $this->Error('Undefined font: '.$family.' '.$style); } //Select it $this->FontFamily=$family; $this->FontStyle=$style; $this->FontSizePt=$size; $this->FontSize=$size/$this->k; $this->CurrentFont=&$this->fonts[$fontkey]; if($this->page>0) $this->_out(sprintf('BT /F%d %.2f Tf ET',$this->CurrentFont['i'],$this->FontSizePt)); } function SetFontSize($size) { //Set font size in points if($this->FontSizePt==$size) return; $this->FontSizePt=$size; $this->FontSize=$size/$this->k; if($this->page>0) $this->_out(sprintf('BT /F%d %.2f Tf ET',$this->CurrentFont['i'],$this->FontSizePt)); } function AddLink() { //Create a new internal link $n=count($this->links)+1; $this->links[$n]=array(0,0); return $n; } function SetLink($link,$y=0,$page=-1) { //Set destination of internal link if($y==-1) $y=$this->y; if($page==-1) $page=$this->page; $this->links[$link]=array($page,$y); } function Link($x,$y,$w,$h,$link) { //Put a link on the page $this->PageLinks[$this->page][]=array($x*$this->k,$this->hPt-$y*$this->k,$w*$this->k,$h*$this->k,$link); } function Text($x,$y,$txt) { //Output a string $s=sprintf('BT %.2f %.2f Td (%s) Tj ET',$x*$this->k,($this->h-$y)*$this->k,$this->_escape($txt)); if($this->underline and $txt!='') $s.=' '.$this->_dounderline($x,$y,$txt); if($this->ColorFlag) $s='q '.$this->TextColor.' '.$s.' Q'; $this->_out($s); } function AcceptPageBreak() { //Accept automatic page break or not return $this->AutoPageBreak; } function Cell($w,$h=0,$txt='',$border=0,$ln=0,$align='',$fill=0,$link='',$currentx=0) //EDITEI { //Output a cell $k=$this->k; if($this->y+$h>$this->PageBreakTrigger and !$this->InFooter and $this->AcceptPageBreak()) { //Automatic page break $x=$this->x;//Current X position $ws=$this->ws;//Word Spacing if($ws>0) { $this->ws=0; $this->_out('0 Tw'); } $this->AddPage($this->CurOrientation); $this->x=$x; if($ws>0) { $this->ws=$ws; $this->_out(sprintf('%.3f Tw',$ws*$k)); } } if($w==0) $w = $this->w-$this->rMargin-$this->x; $s=''; if($fill==1 or $border==1) { if ($fill==1) $op=($border==1) ? 'B' : 'f'; else $op='S'; //$op='S';//DEBUG $s=sprintf('%.2f %.2f %.2f %.2f re %s ',$this->x*$k,($this->h-$this->y)*$k,$w*$k,-$h*$k,$op); } if(is_string($border)) { $x=$this->x; $y=$this->y; if(is_int(strpos($border,'L'))) $s.=sprintf('%.2f %.2f m %.2f %.2f l S ',$x*$k,($this->h-$y)*$k,$x*$k,($this->h-($y+$h))*$k); if(is_int(strpos($border,'T'))) $s.=sprintf('%.2f %.2f m %.2f %.2f l S ',$x*$k,($this->h-$y)*$k,($x+$w)*$k,($this->h-$y)*$k); if(is_int(strpos($border,'R'))) $s.=sprintf('%.2f %.2f m %.2f %.2f l S ',($x+$w)*$k,($this->h-$y)*$k,($x+$w)*$k,($this->h-($y+$h))*$k); if(is_int(strpos($border,'B'))) $s.=sprintf('%.2f %.2f m %.2f %.2f l S ',$x*$k,($this->h-($y+$h))*$k,($x+$w)*$k,($this->h-($y+$h))*$k); } if($txt!='') { if($align=='R') $dx=$w-$this->cMargin-$this->GetStringWidth($txt); elseif($align=='C') $dx=($w-$this->GetStringWidth($txt))/2; elseif($align=='L' or $align=='J') $dx=$this->cMargin; else $dx = 0; if($this->ColorFlag) $s.='q '.$this->TextColor.' '; $txt = str_replace(''','\'',$txt); $txt2=str_replace(')','\\)',str_replace('(','\\(',str_replace('\\','\\\\',$txt))); //Check whether we are going to outline text or not if($this->outline_on) { $s.=' '.sprintf('%.2f w',$this->LineWidth*$this->k).' '; $s.=" $this->DrawColor "; $s.=" 2 Tr "; } //Superscript and Subscript Y coordinate adjustment $adjusty = 0; if($this->SUB) $adjusty = 1; if($this->SUP) $adjusty = -1; //End of coordinate adjustment $s.=sprintf('BT %.2f %.2f Td (%s) Tj ET',($this->x+$dx)*$k,($this->h-(($this->y+$adjusty)+.5*$h+.3*$this->FontSize))*$k,$txt2); //EDITEI if($this->underline) $s.=' '.$this->_dounderline($this->x+$dx,$this->y+.5*$h+.3*$this->FontSize+$adjusty,$txt2); //Superscript and Subscript Y coordinate adjustment (now for striked-through texts) $adjusty = 1.6; if($this->SUB) $adjusty = 3.05; if($this->SUP) $adjusty = 1.1; //End of coordinate adjustment if($this->strike) //EDITEI $s.=' '.$this->_dounderline($this->x+$dx,$this->y+$adjusty,$txt); if($this->ColorFlag) $s.=' Q'; if($link!='') $this->Link($this->x+$dx,$this->y+.5*$h-.5*$this->FontSize,$this->GetStringWidth($txt),$this->FontSize,$link); } if($s) $this->_out($s); $this->lasth=$h; if( strpos($txt,"\n") !== false) $ln=1; //EDITEI - cell now recognizes \n! << comes from
    tag if($ln>0) { //Go to next line $this->y += $h; if($ln==1) //EDITEI { //Move to next line if ($currentx != 0) $this->x=$currentx; else $this->x=$this->lMargin; } } else $this->x+=$w; } //EDITEI function MultiCell($w,$h,$txt,$border=0,$align='J',$fill=0,$link='') { //Output text with automatic or explicit line breaks $cw=&$this->CurrentFont['cw']; if($w==0) $w=$this->w-$this->rMargin-$this->x; $wmax=($w-2*$this->cMargin)*1000/$this->FontSize; $s=str_replace("\r",'',$txt); $nb=strlen($s); if($nb>0 and $s[$nb-1]=="\n") $nb--; $b=0; if($border) { if($border==1) { $border='LTRB'; $b='LRT'; $b2='LR'; } else { $b2=''; if(is_int(strpos($border,'L'))) $b2.='L'; if(is_int(strpos($border,'R'))) $b2.='R'; $b=is_int(strpos($border,'T')) ? $b2.'T' : $b2; } } $sep=-1; $i=0; $j=0; $l=0; $ns=0; $nl=1; while($i<$nb) { //Get next character $c=$s{$i}; if($c=="\n") { //Explicit line break if($this->ws>0) { $this->ws=0; $this->_out('0 Tw'); } $this->Cell($w,$h,substr($s,$j,$i-$j),$b,2,$align,$fill,$link); $i++; $sep=-1; $j=$i; $l=0; $ns=0; $nl++; if($border and $nl==2) $b=$b2; continue; } if($c==' ') { $sep=$i; $ls=$l; $ns++; } $l+=$cw[$c]; if($l>$wmax) { //Automatic line break if($sep==-1) { if($i==$j) $i++; if($this->ws>0) { $this->ws=0; $this->_out('0 Tw'); } $this->Cell($w,$h,substr($s,$j,$i-$j),$b,2,$align,$fill,$link); } else { if($align=='J') { $this->ws=($ns>1) ? ($wmax-$ls)/1000*$this->FontSize/($ns-1) : 0; $this->_out(sprintf('%.3f Tw',$this->ws*$this->k)); } $this->Cell($w,$h,substr($s,$j,$sep-$j),$b,2,$align,$fill,$link); $i=$sep+1; } $sep=-1; $j=$i; $l=0; $ns=0; $nl++; if($border and $nl==2) $b=$b2; } else $i++; } //Last chunk if($this->ws>0) { $this->ws=0; $this->_out('0 Tw'); } if($border and is_int(strpos($border,'B'))) $b.='B'; $this->Cell($w,$h,substr($s,$j,$i-$j),$b,2,$align,$fill,$link); $this->x=$this->lMargin; } function Write($h,$txt,$currentx=0,$link='') //EDITEI { //Output text in flowing mode $cw=&$this->CurrentFont['cw']; $w=$this->w-$this->rMargin-$this->x; $wmax=($w-2*$this->cMargin)*1000/$this->FontSize; $s=str_replace("\r",'',$txt); $nb=strlen($s); $sep=-1; $i=0; $j=0; $l=0; $nl=1; while($i<$nb) { //Get next character $c=$s{$i}; if($c=="\n") { //Explicit line break $this->Cell($w,$h,substr($s,$j,$i-$j),0,2,'',0,$link); $i++; $sep=-1; $j=$i; $l=0; if($nl==1) { if ($currentx != 0) $this->x=$currentx;//EDITEI else $this->x=$this->lMargin; $w=$this->w-$this->rMargin-$this->x; $wmax=($w-2*$this->cMargin)*1000/$this->FontSize; } $nl++; continue; } if($c == ' ') $sep=$i; $l += $cw[$c]; if($l > $wmax) { //Automatic line break if($sep==-1) { if($this->x > $this->lMargin) { //Move to next line if ($currentx != 0) $this->x=$currentx;//EDITEI else $this->x=$this->lMargin; $this->y+=$h; $w=$this->w-$this->rMargin-$this->x; $wmax=($w-2*$this->cMargin)*1000/$this->FontSize; $i++; $nl++; continue; } if($i==$j) $i++; $this->Cell($w,$h,substr($s,$j,$i-$j),0,2,'',0,$link); } else { $this->Cell($w,$h,substr($s,$j,$sep-$j),0,2,'',0,$link); $i=$sep+1; } $sep=-1; $j=$i; $l=0; if($nl==1) { if ($currentx != 0) $this->x=$currentx;//EDITEI else $this->x=$this->lMargin; $w=$this->w-$this->rMargin-$this->x; $wmax=($w-2*$this->cMargin)*1000/$this->FontSize; } $nl++; } else $i++; } //Last chunk if($i!=$j) $this->Cell($l/1000*$this->FontSize,$h,substr($s,$j),0,0,'',0,$link); } //-------------------------FLOWING BLOCK------------------------------------// //EDITEI some things (added/changed) // //The following functions were originally written by Damon Kohler // //--------------------------------------------------------------------------// function saveFont() { $saved = array(); $saved[ 'family' ] = $this->FontFamily; $saved[ 'style' ] = $this->FontStyle; $saved[ 'sizePt' ] = $this->FontSizePt; $saved[ 'size' ] = $this->FontSize; $saved[ 'curr' ] =& $this->CurrentFont; $saved[ 'color' ] = $this->TextColor; //EDITEI $saved[ 'bgcolor' ] = $this->FillColor; //EDITEI $saved[ 'HREF' ] = $this->HREF; //EDITEI $saved[ 'underline' ] = $this->underline; //EDITEI $saved[ 'strike' ] = $this->strike; //EDITEI $saved[ 'SUP' ] = $this->SUP; //EDITEI $saved[ 'SUB' ] = $this->SUB; //EDITEI $saved[ 'linewidth' ] = $this->LineWidth; //EDITEI $saved[ 'drawcolor' ] = $this->DrawColor; //EDITEI $saved[ 'is_outline' ] = $this->outline_on; //EDITEI return $saved; } function restoreFont( $saved ) { $this->FontFamily = $saved[ 'family' ]; $this->FontStyle = $saved[ 'style' ]; $this->FontSizePt = $saved[ 'sizePt' ]; $this->FontSize = $saved[ 'size' ]; $this->CurrentFont =& $saved[ 'curr' ]; $this->TextColor = $saved[ 'color' ]; //EDITEI $this->FillColor = $saved[ 'bgcolor' ]; //EDITEI $this->ColorFlag = ($this->FillColor != $this->TextColor); //Restore ColorFlag as well $this->HREF = $saved[ 'HREF' ]; //EDITEI $this->underline = $saved[ 'underline' ]; //EDITEI $this->strike = $saved[ 'strike' ]; //EDITEI $this->SUP = $saved[ 'SUP' ]; //EDITEI $this->SUB = $saved[ 'SUB' ]; //EDITEI $this->LineWidth = $saved[ 'linewidth' ]; //EDITEI $this->DrawColor = $saved[ 'drawcolor' ]; //EDITEI $this->outline_on = $saved[ 'is_outline' ]; //EDITEI if( $this->page > 0) $this->_out( sprintf( 'BT /F%d %.2f Tf ET', $this->CurrentFont[ 'i' ], $this->FontSizePt ) ); } function newFlowingBlock( $w, $h, $b = 0, $a = 'J', $f = 0 , $is_table = false ) { // cell width in points if ($is_table) $this->flowingBlockAttr[ 'width' ] = ($w * $this->k); else $this->flowingBlockAttr[ 'width' ] = ($w * $this->k) - (2*$this->cMargin*$this->k); // line height in user units $this->flowingBlockAttr[ 'is_table' ] = $is_table; $this->flowingBlockAttr[ 'height' ] = $h; $this->flowingBlockAttr[ 'lineCount' ] = 0; $this->flowingBlockAttr[ 'border' ] = $b; $this->flowingBlockAttr[ 'align' ] = $a; $this->flowingBlockAttr[ 'fill' ] = $f; $this->flowingBlockAttr[ 'font' ] = array(); $this->flowingBlockAttr[ 'content' ] = array(); $this->flowingBlockAttr[ 'contentWidth' ] = 0; } function finishFlowingBlock($outofblock=false) { if (!$outofblock) $currentx = $this->x; //EDITEI - in order to make the Cell method work better //prints out the last chunk $is_table = $this->flowingBlockAttr[ 'is_table' ]; $maxWidth =& $this->flowingBlockAttr[ 'width' ]; $lineHeight =& $this->flowingBlockAttr[ 'height' ]; $border =& $this->flowingBlockAttr[ 'border' ]; $align =& $this->flowingBlockAttr[ 'align' ]; $fill =& $this->flowingBlockAttr[ 'fill' ]; $content =& $this->flowingBlockAttr[ 'content' ]; $font =& $this->flowingBlockAttr[ 'font' ]; $contentWidth =& $this->flowingBlockAttr[ 'contentWidth' ]; $lineCount =& $this->flowingBlockAttr[ 'lineCount' ]; // set normal spacing $this->_out( sprintf( '%.3f Tw', 0 ) ); $this->ws = 0; // the amount of space taken up so far in user units $usedWidth = 0; // Print out each chunk //EDITEI - Print content according to alignment $empty = $maxWidth - $contentWidth; $empty /= $this->k; $b = ''; //do not use borders $arraysize = count($content); $margins = (2*$this->cMargin); if ($outofblock) { $align = 'C'; $empty = 0; $margins = $this->cMargin; } switch($align) { case 'R': foreach ( $content as $k => $chunk ) { $this->restoreFont( $font[ $k ] ); $stringWidth = $this->GetStringWidth( $chunk ) + ( $this->ws * substr_count( $chunk, ' ' ) / $this->k ); // determine which borders should be used $b = ''; if ( $lineCount == 1 && is_int( strpos( $border, 'T' ) ) ) $b .= 'T'; if ( $k == count( $content ) - 1 && is_int( strpos( $border, 'R' ) ) ) $b .= 'R'; if ($k == $arraysize-1 and !$outofblock) $skipln = 1; else $skipln = 0; if ($arraysize == 1) $this->Cell( $stringWidth + $margins + $empty, $lineHeight, $chunk, $b, $skipln, $align, $fill, $this->HREF , $currentx ); //mono-style line elseif ($k == 0) $this->Cell( $stringWidth + ($margins/2) + $empty, $lineHeight, $chunk, $b, 0, 'R', $fill, $this->HREF );//first part elseif ($k == $arraysize-1 ) $this->Cell( $stringWidth + ($margins/2), $lineHeight, $chunk, $b, $skipln, '', $fill, $this->HREF, $currentx );//last part else $this->Cell( $stringWidth , $lineHeight, $chunk, $b, 0, '', $fill, $this->HREF );//middle part } break; case 'L': case 'J': foreach ( $content as $k => $chunk ) { $this->restoreFont( $font[ $k ] ); $stringWidth = $this->GetStringWidth( $chunk ) + ( $this->ws * substr_count( $chunk, ' ' ) / $this->k ); // determine which borders should be used $b = ''; if ( $lineCount == 1 && is_int( strpos( $border, 'T' ) ) ) $b .= 'T'; if ( $k == 0 && is_int( strpos( $border, 'L' ) ) ) $b .= 'L'; if ($k == $arraysize-1 and !$outofblock) $skipln = 1; else $skipln = 0; if (!$is_table and !$outofblock and !$fill and $align=='L' and $k == 0) {$align='';$margins=0;} //Remove margins in this special (though often) case if ($arraysize == 1) $this->Cell( $stringWidth + $margins + $empty, $lineHeight, $chunk, $b, $skipln, $align, $fill, $this->HREF , $currentx ); //mono-style line elseif ($k == 0) $this->Cell( $stringWidth + ($margins/2), $lineHeight, $chunk, $b, $skipln, $align, $fill, $this->HREF );//first part elseif ($k == $arraysize-1 ) $this->Cell( $stringWidth + ($margins/2) + $empty, $lineHeight, $chunk, $b, $skipln, '', $fill, $this->HREF, $currentx );//last part else $this->Cell( $stringWidth , $lineHeight, $chunk, $b, $skipln, '', $fill, $this->HREF );//middle part } break; case 'C': foreach ( $content as $k => $chunk ) { $this->restoreFont( $font[ $k ] ); $stringWidth = $this->GetStringWidth( $chunk ) + ( $this->ws * substr_count( $chunk, ' ' ) / $this->k ); // determine which borders should be used $b = ''; if ( $lineCount == 1 && is_int( strpos( $border, 'T' ) ) ) $b .= 'T'; if ($k == $arraysize-1 and !$outofblock) $skipln = 1; else $skipln = 0; if ($arraysize == 1) $this->Cell( $stringWidth + $margins + $empty, $lineHeight, $chunk, $b, $skipln, $align, $fill, $this->HREF , $currentx ); //mono-style line elseif ($k == 0) $this->Cell( $stringWidth + ($margins/2) + ($empty/2), $lineHeight, $chunk, $b, 0, 'R', $fill, $this->HREF );//first part elseif ($k == $arraysize-1 ) $this->Cell( $stringWidth + ($margins/2) + ($empty/2), $lineHeight, $chunk, $b, $skipln, 'L', $fill, $this->HREF, $currentx );//last part else $this->Cell( $stringWidth , $lineHeight, $chunk, $b, 0, '', $fill, $this->HREF );//middle part } break; default: break; } } function WriteFlowingBlock( $s , $outofblock = false ) { if (!$outofblock) $currentx = $this->x; //EDITEI - in order to make the Cell method work better $is_table = $this->flowingBlockAttr[ 'is_table' ]; // width of all the content so far in points $contentWidth =& $this->flowingBlockAttr[ 'contentWidth' ]; // cell width in points $maxWidth =& $this->flowingBlockAttr[ 'width' ]; $lineCount =& $this->flowingBlockAttr[ 'lineCount' ]; // line height in user units $lineHeight =& $this->flowingBlockAttr[ 'height' ]; $border =& $this->flowingBlockAttr[ 'border' ]; $align =& $this->flowingBlockAttr[ 'align' ]; $fill =& $this->flowingBlockAttr[ 'fill' ]; $content =& $this->flowingBlockAttr[ 'content' ]; $font =& $this->flowingBlockAttr[ 'font' ]; $font[] = $this->saveFont(); $content[] = ''; $currContent =& $content[ count( $content ) - 1 ]; // where the line should be cutoff if it is to be justified $cutoffWidth = $contentWidth; // for every character in the string for ( $i = 0; $i < strlen( $s ); $i++ ) { // extract the current character $c = $s{$i}; // get the width of the character in points $cw = $this->CurrentFont[ 'cw' ][ $c ] * ( $this->FontSizePt / 1000 ); if ( $c == ' ' ) { $currContent .= ' '; $cutoffWidth = $contentWidth; $contentWidth += $cw; continue; } // try adding another char if ( $contentWidth + $cw > $maxWidth ) { // it won't fit, output what we already have $lineCount++; //Readjust MaxSize in order to use the whole page width if ($outofblock and ($lineCount == 1) ) $maxWidth = $this->pgwidth * $this->k; // contains any content that didn't make it into this print $savedContent = ''; $savedFont = array(); // first, cut off and save any partial words at the end of the string $words = explode( ' ', $currContent ); // if it looks like we didn't finish any words for this chunk if ( count( $words ) == 1 ) { // save and crop off the content currently on the stack $savedContent = array_pop( $content ); $savedFont = array_pop( $font ); // trim any trailing spaces off the last bit of content $currContent =& $content[ count( $content ) - 1 ]; $currContent = rtrim( $currContent ); } else // otherwise, we need to find which bit to cut off { $lastContent = ''; for ( $w = 0; $w < count( $words ) - 1; $w++) $lastContent .= "{$words[ $w ]} "; $savedContent = $words[ count( $words ) - 1 ]; $savedFont = $this->saveFont(); // replace the current content with the cropped version $currContent = rtrim( $lastContent ); } // update $contentWidth and $cutoffWidth since they changed with cropping $contentWidth = 0; foreach ( $content as $k => $chunk ) { $this->restoreFont( $font[ $k ] ); $contentWidth += $this->GetStringWidth( $chunk ) * $this->k; } $cutoffWidth = $contentWidth; // if it's justified, we need to find the char spacing if( $align == 'J' ) { // count how many spaces there are in the entire content string $numSpaces = 0; foreach ( $content as $chunk ) $numSpaces += substr_count( $chunk, ' ' ); // if there's more than one space, find word spacing in points if ( $numSpaces > 0 ) $this->ws = ( $maxWidth - $cutoffWidth ) / $numSpaces; else $this->ws = 0; $this->_out( sprintf( '%.3f Tw', $this->ws ) ); } // otherwise, we want normal spacing else $this->_out( sprintf( '%.3f Tw', 0 ) ); //EDITEI - Print content according to alignment if (!isset($numSpaces)) $numSpaces = 0; $contentWidth -= ($this->ws*$numSpaces); $empty = $maxWidth - $contentWidth - 2*($this->ws*$numSpaces); $empty /= $this->k; $b = ''; //do not use borders /*'If' below used in order to fix "first-line of other page with justify on" bug*/ if($this->y+$this->divheight>$this->PageBreakTrigger and !$this->InFooter and $this->AcceptPageBreak()) { $bak_x=$this->x;//Current X position $ws=$this->ws;//Word Spacing if($ws>0) { $this->ws=0; $this->_out('0 Tw'); } $this->AddPage($this->CurOrientation); $this->x=$bak_x; if($ws>0) { $this->ws=$ws; $this->_out(sprintf('%.3f Tw',$ws)); } } $arraysize = count($content); $margins = (2*$this->cMargin); if ($outofblock) { $align = 'C'; $empty = 0; $margins = $this->cMargin; } switch($align) { case 'R': foreach ( $content as $k => $chunk ) { $this->restoreFont( $font[ $k ] ); $stringWidth = $this->GetStringWidth( $chunk ) + ( $this->ws * substr_count( $chunk, ' ' ) / $this->k ); // determine which borders should be used $b = ''; if ( $lineCount == 1 && is_int( strpos( $border, 'T' ) ) ) $b .= 'T'; if ( $k == count( $content ) - 1 && is_int( strpos( $border, 'R' ) ) ) $b .= 'R'; if ($arraysize == 1) $this->Cell( $stringWidth + $margins + $empty, $lineHeight, $chunk, $b, 1, $align, $fill, $this->HREF , $currentx ); //mono-style line elseif ($k == 0) $this->Cell( $stringWidth + ($margins/2) + $empty, $lineHeight, $chunk, $b, 0, 'R', $fill, $this->HREF );//first part elseif ($k == $arraysize-1 ) $this->Cell( $stringWidth + ($margins/2), $lineHeight, $chunk, $b, 1, '', $fill, $this->HREF, $currentx );//last part else $this->Cell( $stringWidth , $lineHeight, $chunk, $b, 0, '', $fill, $this->HREF );//middle part } break; case 'L': case 'J': foreach ( $content as $k => $chunk ) { $this->restoreFont( $font[ $k ] ); $stringWidth = $this->GetStringWidth( $chunk ) + ( $this->ws * substr_count( $chunk, ' ' ) / $this->k ); // determine which borders should be used $b = ''; if ( $lineCount == 1 && is_int( strpos( $border, 'T' ) ) ) $b .= 'T'; if ( $k == 0 && is_int( strpos( $border, 'L' ) ) ) $b .= 'L'; if (!$is_table and !$outofblock and !$fill and $align=='L' and $k == 0) { //Remove margins in this special (though often) case $align=''; $margins=0; } if ($arraysize == 1) $this->Cell( $stringWidth + $margins + $empty, $lineHeight, $chunk, $b, 1, $align, $fill, $this->HREF , $currentx ); //mono-style line elseif ($k == 0) $this->Cell( $stringWidth + ($margins/2), $lineHeight, $chunk, $b, 0, $align, $fill, $this->HREF );//first part elseif ($k == $arraysize-1 ) $this->Cell( $stringWidth + ($margins/2) + $empty, $lineHeight, $chunk, $b, 1, '', $fill, $this->HREF, $currentx );//last part else $this->Cell( $stringWidth , $lineHeight, $chunk, $b, 0, '', $fill, $this->HREF );//middle part if (!$is_table and !$outofblock and !$fill and $align=='' and $k == 0) { $align = 'L'; $margins = (2*$this->cMargin); } } break; case 'C': foreach ( $content as $k => $chunk ) { $this->restoreFont( $font[ $k ] ); $stringWidth = $this->GetStringWidth( $chunk ) + ( $this->ws * substr_count( $chunk, ' ' ) / $this->k ); // determine which borders should be used $b = ''; if ( $lineCount == 1 && is_int( strpos( $border, 'T' ) ) ) $b .= 'T'; if ($arraysize == 1) $this->Cell( $stringWidth + $margins + $empty, $lineHeight, $chunk, $b, 1, $align, $fill, $this->HREF , $currentx ); //mono-style line elseif ($k == 0) $this->Cell( $stringWidth + ($margins/2) + ($empty/2), $lineHeight, $chunk, $b, 0, 'R', $fill, $this->HREF );//first part elseif ($k == $arraysize-1 ) $this->Cell( $stringWidth + ($margins/2) + ($empty/2), $lineHeight, $chunk, $b, 1, 'L', $fill, $this->HREF, $currentx );//last part else $this->Cell( $stringWidth , $lineHeight, $chunk, $b, 0, '', $fill, $this->HREF );//middle part } break; default: break; } // move on to the next line, reset variables, tack on saved content and current char $this->restoreFont( $savedFont ); $font = array( $savedFont ); $content = array( $savedContent . $s{ $i } ); $currContent =& $content[ 0 ]; $contentWidth = $this->GetStringWidth( $currContent ) * $this->k; $cutoffWidth = $contentWidth; } // another character will fit, so add it on else { $contentWidth += $cw; $currContent .= $s{ $i }; } } } //----------------------END OF FLOWING BLOCK------------------------------------// //EDITEI //Thanks to Ron Korving for the WordWrap() function function WordWrap(&$text, $maxwidth) { $biggestword=0;//EDITEI $toonarrow=false;//EDITEI $text = trim($text); if ($text==='') return 0; $space = $this->GetStringWidth(' '); $lines = explode("\n", $text); $text = ''; $count = 0; foreach ($lines as $line) { $words = preg_split('/ +/', $line); $width = 0; foreach ($words as $word) { $wordwidth = $this->GetStringWidth($word); //EDITEI //Warn user that maxwidth is insufficient if ($wordwidth > $maxwidth) { if ($wordwidth > $biggestword) $biggestword = $wordwidth; $toonarrow=true;//EDITEI } if ($width + $wordwidth <= $maxwidth) { $width += $wordwidth + $space; $text .= $word.' '; } else { $width = $wordwidth + $space; $text = rtrim($text)."\n".$word.' '; $count++; } } $text = rtrim($text)."\n"; $count++; } $text = rtrim($text); //Return -(wordsize) if word is bigger than maxwidth if ($toonarrow) return -$biggestword; else return $count; } //EDITEI //Thanks to Seb(captainseb@wanadoo.fr) for the _SetTextRendering() and SetTextOutline() functions /** * Set Text Rendering Mode * @param int $mode Set the rendering mode.
    • 0 : Fill text (default)
    • 1 : Stroke
    • 2 : Fill & stroke
    * @see SetTextOutline() */ //This function is not being currently used function _SetTextRendering($mode) { if (!(($mode == 0) || ($mode == 1) || ($mode == 2))) $this->Error("Text rendering mode should be 0, 1 or 2 (value : $mode)"); $this->_out($mode.' Tr'); } /** * Set Text Ouline On/Off * @param mixed $width If set to false the text rending mode is set to fill, else it's the width of the outline * @param int $r If g et b are given, red component; if not, indicates the gray level. Value between 0 and 255 * @param int $g Green component (between 0 and 255) * @param int $b Blue component (between 0 and 255) * @see _SetTextRendering() */ function SetTextOutline($width, $r=0, $g=-1, $b=-1) //EDITEI { if ($width == false) //Now resets all values { $this->outline_on = false; $this->SetLineWidth(0.2); $this->SetDrawColor(0); $this->_setTextRendering(0); $this->_out('0 Tr'); } else { $this->SetLineWidth($width); $this->SetDrawColor($r, $g , $b); $this->_out('2 Tr'); //Fixed } } //function Circle() thanks to Olivier PLATHEY //EDITEI function Circle($x,$y,$r,$style='') { $this->Ellipse($x,$y,$r,$r,$style); } //function Ellipse() thanks to Olivier PLATHEY //EDITEI function Ellipse($x,$y,$rx,$ry,$style='D') { if($style=='F') $op='f'; elseif($style=='FD' or $style=='DF') $op='B'; else $op='S'; $lx=4/3*(M_SQRT2-1)*$rx; $ly=4/3*(M_SQRT2-1)*$ry; $k=$this->k; $h=$this->h; $this->_out(sprintf('%.2f %.2f m %.2f %.2f %.2f %.2f %.2f %.2f c', ($x+$rx)*$k,($h-$y)*$k, ($x+$rx)*$k,($h-($y-$ly))*$k, ($x+$lx)*$k,($h-($y-$ry))*$k, $x*$k,($h-($y-$ry))*$k)); $this->_out(sprintf('%.2f %.2f %.2f %.2f %.2f %.2f c', ($x-$lx)*$k,($h-($y-$ry))*$k, ($x-$rx)*$k,($h-($y-$ly))*$k, ($x-$rx)*$k,($h-$y)*$k)); $this->_out(sprintf('%.2f %.2f %.2f %.2f %.2f %.2f c', ($x-$rx)*$k,($h-($y+$ly))*$k, ($x-$lx)*$k,($h-($y+$ry))*$k, $x*$k,($h-($y+$ry))*$k)); $this->_out(sprintf('%.2f %.2f %.2f %.2f %.2f %.2f c %s', ($x+$lx)*$k,($h-($y+$ry))*$k, ($x+$rx)*$k,($h-($y+$ly))*$k, ($x+$rx)*$k,($h-$y)*$k, $op)); } function Image($file,$x=null,$y=null,$w=0,$h=0,$type='',$link='',$paint=true) { //Put an image on the page if(!isset($this->images[$file])) { //First use of image, get info if($type=='') { $pos=strrpos($file,'.'); if(!$pos) $this->Error('Image file has no extension and no type was specified: '.$file); $type=substr($file,$pos+1); } $type=strtolower($type); $mqr=get_magic_quotes_runtime(); set_magic_quotes_runtime(0); if($type=='jpg' or $type=='jpeg') $info=$this->_parsejpg($file); elseif($type=='png') $info=$this->_parsepng($file); elseif($type=='gif') $info=$this->_parsegif($file); //EDITEI - GIF format included else { //Allow for additional formats $mtd='_parse'.$type; if(!method_exists($this,$mtd)) $this->Error('Unsupported image type: '.$type); $info=$this->$mtd($file); } set_magic_quotes_runtime($mqr); $info['i']=count($this->images)+1; $this->images[$file]=$info; } else $info=$this->images[$file]; //Automatic width and height calculation if needed if($w==0 and $h==0) { //Put image at 72 dpi $w=$info['w']/$this->k; $h=$info['h']/$this->k; } if($w==0) $w=$h*$info['w']/$info['h']; if($h==0) $h=$w*$info['h']/$info['w']; $changedpage = false; //EDITEI //Avoid drawing out of the paper(exceeding width limits). //EDITEI if ( ($x + $w) > $this->fw ) { $x = $this->lMargin; $y += 5; } //Avoid drawing out of the page. //EDITEI if ( ($y + $h) > $this->fh ) { $this->AddPage(); $y = $tMargin + 10; // +10 to avoid drawing too close to border of page $changedpage = true; } $outstring = sprintf('q %.2f 0 0 %.2f %.2f %.2f cm /I%d Do Q',$w*$this->k,$h*$this->k,$x*$this->k,($this->h-($y+$h))*$this->k,$info['i']); if($paint) //EDITEI { $this->_out($outstring); if($link) $this->Link($x,$y,$w,$h,$link); } //Avoid writing text on top of the image. //EDITEI if ($changedpage) $this->y = $y + $h; else $this->y = $y + $h; //Return width-height array //EDITEI $sizesarray['WIDTH'] = $w; $sizesarray['HEIGHT'] = $h; $sizesarray['X'] = $x; //Position before painting image $sizesarray['Y'] = $y; //Position before painting image $sizesarray['OUTPUT'] = $outstring; return $sizesarray; } //EDITEI - Done after reading a little about PDF reference guide function DottedRect($x=100,$y=150,$w=50,$h=50) { $x *= $this->k ; $y = ($this->h-$y)*$this->k; $w *= $this->k ; $h *= $this->k ;// - h? $herex = $x; $herey = $y; //Make fillcolor == drawcolor $bak_fill = $this->FillColor; $this->FillColor = $this->DrawColor; $this->FillColor = str_replace('RG','rg',$this->FillColor); $this->_out($this->FillColor); while ($herex < ($x + $w)) //draw from upper left to upper right { $this->DrawDot($herex,$herey); $herex += (3*$this->k); } $herex = $x + $w; while ($herey > ($y - $h)) //draw from upper right to lower right { $this->DrawDot($herex,$herey); $herey -= (3*$this->k); } $herey = $y - $h; while ($herex > $x) //draw from lower right to lower left { $this->DrawDot($herex,$herey); $herex -= (3*$this->k); } $herex = $x; while ($herey < $y) //draw from lower left to upper left { $this->DrawDot($herex,$herey); $herey += (3*$this->k); } $herey = $y; $this->FillColor = $bak_fill; $this->_out($this->FillColor); //return fillcolor back to normal } //EDITEI - Done after reading a little about PDF reference guide function DrawDot($x,$y) //center x y { $op = 'B'; // draw Filled Dots //F == fill //S == stroke //B == stroke and fill $r = 0.5 * $this->k; //raio //Start Point $x1 = $x - $r; $y1 = $y; //End Point $x2 = $x + $r; $y2 = $y; //Auxiliar Point $x3 = $x; $y3 = $y + (2*$r);// 2*raio to make a round (not oval) shape //Round join and cap $s="\n".'1 J'."\n"; $s.='1 j'."\n"; //Upper circle $s.=sprintf('%.3f %.3f m'."\n",$x1,$y1); //x y start drawing $s.=sprintf('%.3f %.3f %.3f %.3f %.3f %.3f c'."\n",$x1,$y1,$x3,$y3,$x2,$y2);//Bezier curve //Lower circle $y3 = $y - (2*$r); $s.=sprintf("\n".'%.3f %.3f m'."\n",$x1,$y1); //x y start drawing $s.=sprintf('%.3f %.3f %.3f %.3f %.3f %.3f c'."\n",$x1,$y1,$x3,$y3,$x2,$y2); $s.=$op."\n"; //stroke and fill //Draw in PDF file $this->_out($s); } function SetDash($black=false,$white=false) { if($black and $white) $s=sprintf('[%.3f %.3f] 0 d',$black*$this->k,$white*$this->k); else $s='[] 0 d'; $this->_out($s); } function Bookmark($txt,$level=0,$y=0) { if($y == -1) $y = $this->GetY(); $this->outlines[]=array('t'=>$txt,'l'=>$level,'y'=>$y,'p'=>$this->PageNo()); } function DisplayPreferences($preferences) { $this->DisplayPreferences .= $preferences; } function _putbookmarks() { $nb=count($this->outlines); if($nb==0) return; $lru=array(); $level=0; foreach($this->outlines as $i=>$o) { if($o['l']>0) { $parent=$lru[$o['l']-1]; //Set parent and last pointers $this->outlines[$i]['parent']=$parent; $this->outlines[$parent]['last']=$i; if($o['l']>$level) { //Level increasing: set first pointer $this->outlines[$parent]['first']=$i; } } else $this->outlines[$i]['parent']=$nb; if($o['l']<=$level and $i>0) { //Set prev and next pointers $prev=$lru[$o['l']]; $this->outlines[$prev]['next']=$i; $this->outlines[$i]['prev']=$prev; } $lru[$o['l']]=$i; $level=$o['l']; } //Outline items $n=$this->n+1; foreach($this->outlines as $i=>$o) { $this->_newobj(); $this->_out('<_textstring($o['t'])); $this->_out('/Parent '.($n+$o['parent']).' 0 R'); if(isset($o['prev'])) $this->_out('/Prev '.($n+$o['prev']).' 0 R'); if(isset($o['next'])) $this->_out('/Next '.($n+$o['next']).' 0 R'); if(isset($o['first'])) $this->_out('/First '.($n+$o['first']).' 0 R'); if(isset($o['last'])) $this->_out('/Last '.($n+$o['last']).' 0 R'); $this->_out(sprintf('/Dest [%d 0 R /XYZ 0 %.2f null]',1+2*$o['p'],($this->h-$o['y'])*$this->k)); $this->_out('/Count 0>>'); $this->_out('endobj'); } //Outline root $this->_newobj(); $this->OutlineRoot=$this->n; $this->_out('<_out('/Last '.($n+$lru[0]).' 0 R>>'); $this->_out('endobj'); } function Ln($h='') { //Line feed; default value is last cell height $this->x=$this->lMargin; if(is_string($h)) $this->y+=$this->lasth; else $this->y+=$h; } function GetX() { //Get x position return $this->x; } function SetX($x) { //Set x position if($x >= 0) $this->x=$x; else $this->x = $this->w + $x; } function GetY() { //Get y position return $this->y; } function SetY($y) { //Set y position and reset x $this->x=$this->lMargin; if($y>=0) $this->y=$y; else $this->y=$this->h+$y; } function SetXY($x,$y) { //Set x and y positions $this->SetY($y); $this->SetX($x); } function Output($name='',$dest='') { //Output PDF to some destination global $_SERVER; //Finish document if necessary if($this->state < 3) $this->Close(); //Normalize parameters if(is_bool($dest)) $dest=$dest ? 'D' : 'F'; $dest=strtoupper($dest); if($dest=='') { if($name=='') { $name='doc.pdf'; $dest='I'; } else $dest='F'; } switch($dest) { case 'I': //Send to standard output if(isset($_SERVER['SERVER_NAME'])) { //We send to a browser Header('Content-Type: application/pdf'); if(headers_sent()) $this->Error('Some data has already been output to browser, can\'t send PDF file'); Header('Content-Length: '.strlen($this->buffer)); Header('Content-disposition: inline; filename='.$name); } echo $this->buffer; break; case 'D': //Download file if(isset($_SERVER['HTTP_USER_AGENT']) and strpos($_SERVER['HTTP_USER_AGENT'],'MSIE')) Header('Content-Type: application/force-download'); else Header('Content-Type: application/octet-stream'); if(headers_sent()) $this->Error('Some data has already been output to browser, can\'t send PDF file'); Header('Content-Length: '.strlen($this->buffer)); Header('Content-disposition: attachment; filename='.$name); echo $this->buffer; break; case 'F': //Save to local file $f=fopen($name,'wb'); if(!$f) $this->Error('Unable to create output file: '.$name); fwrite($f,$this->buffer,strlen($this->buffer)); fclose($f); break; case 'S': //Return as a string return $this->buffer; default: $this->Error('Incorrect output destination: '.$dest); } return ''; } /******************************************************************************* * * * Protected methods * * * *******************************************************************************/ function _dochecks() { //Check for locale-related bug if(1.1==1) $this->Error('Don\'t alter the locale before including class file'); //Check for decimal separator if(sprintf('%.1f',1.0)!='1.0') setlocale(LC_NUMERIC,'C'); } function _begindoc() { //Start document $this->state=1; $this->_out('%PDF-1.3'); } function _putpages() { $nb=$this->page; if(!empty($this->AliasNbPages)) { //Replace number of pages for($n=1;$n<=$nb;$n++) $this->pages[$n]=str_replace($this->AliasNbPages,$nb,$this->pages[$n]); } if($this->DefOrientation=='P') { $wPt=$this->fwPt; $hPt=$this->fhPt; } else { $wPt=$this->fhPt; $hPt=$this->fwPt; } $filter=($this->compress) ? '/Filter /FlateDecode ' : ''; for($n=1;$n<=$nb;$n++) { //Page $this->_newobj(); $this->_out('<_out('/Parent 1 0 R'); if(isset($this->OrientationChanges[$n])) $this->_out(sprintf('/MediaBox [0 0 %.2f %.2f]',$hPt,$wPt)); $this->_out('/Resources 2 0 R'); if(isset($this->PageLinks[$n])) { //Links $annots='/Annots ['; foreach($this->PageLinks[$n] as $pl) { $rect=sprintf('%.2f %.2f %.2f %.2f',$pl[0],$pl[1],$pl[0]+$pl[2],$pl[1]-$pl[3]); $annots.='<_textstring($pl[4]).'>>>>'; else { $l=$this->links[$pl[4]]; $h=isset($this->OrientationChanges[$l[0]]) ? $wPt : $hPt; $annots.=sprintf('/Dest [%d 0 R /XYZ 0 %.2f null]>>',1+2*$l[0],$h-$l[1]*$this->k); } } $this->_out($annots.']'); } $this->_out('/Contents '.($this->n+1).' 0 R>>'); $this->_out('endobj'); //Page content $p=($this->compress) ? gzcompress($this->pages[$n]) : $this->pages[$n]; $this->_newobj(); $this->_out('<<'.$filter.'/Length '.strlen($p).'>>'); $this->_putstream($p); $this->_out('endobj'); } //Pages root $this->offsets[1]=strlen($this->buffer); $this->_out('1 0 obj'); $this->_out('<_out($kids.']'); $this->_out('/Count '.$nb); $this->_out(sprintf('/MediaBox [0 0 %.2f %.2f]',$wPt,$hPt)); $this->_out('>>'); $this->_out('endobj'); } function _putfonts() { $nf=$this->n; foreach($this->diffs as $diff) { //Encodings $this->_newobj(); $this->_out('<>'); $this->_out('endobj'); } $mqr=get_magic_quotes_runtime(); set_magic_quotes_runtime(0); foreach($this->FontFiles as $file=>$info) { //Font file embedding $this->_newobj(); $this->FontFiles[$file]['n']=$this->n; if(defined('FPDF_FONTPATH')) $file=FPDF_FONTPATH.$file; $size=filesize($file); if(!$size) $this->Error('Font file not found'); $this->_out('<_out('/Filter /FlateDecode'); $this->_out('/Length1 '.$info['length1']); if(isset($info['length2'])) $this->_out('/Length2 '.$info['length2'].' /Length3 0'); $this->_out('>>'); $f=fopen($file,'rb'); $this->_putstream(fread($f,$size)); fclose($f); $this->_out('endobj'); } set_magic_quotes_runtime($mqr); foreach($this->fonts as $k=>$font) { //Font objects $this->fonts[$k]['n']=$this->n+1; $type=$font['type']; $name=$font['name']; if($type=='core') { //Standard font $this->_newobj(); $this->_out('<_out('/BaseFont /'.$name); $this->_out('/Subtype /Type1'); if($name!='Symbol' and $name!='ZapfDingbats') $this->_out('/Encoding /WinAnsiEncoding'); $this->_out('>>'); $this->_out('endobj'); } elseif($type=='Type1' or $type=='TrueType') { //Additional Type1 or TrueType font $this->_newobj(); $this->_out('<_out('/BaseFont /'.$name); $this->_out('/Subtype /'.$type); $this->_out('/FirstChar 32 /LastChar 255'); $this->_out('/Widths '.($this->n+1).' 0 R'); $this->_out('/FontDescriptor '.($this->n+2).' 0 R'); if($font['enc']) { if(isset($font['diff'])) $this->_out('/Encoding '.($nf+$font['diff']).' 0 R'); else $this->_out('/Encoding /WinAnsiEncoding'); } $this->_out('>>'); $this->_out('endobj'); //Widths $this->_newobj(); $cw=&$font['cw']; $s='['; for($i=32;$i<=255;$i++) $s.=$cw[chr($i)].' '; $this->_out($s.']'); $this->_out('endobj'); //Descriptor $this->_newobj(); $s='<$v) $s.=' /'.$k.' '.$v; $file=$font['file']; if($file) $s.=' /FontFile'.($type=='Type1' ? '' : '2').' '.$this->FontFiles[$file]['n'].' 0 R'; $this->_out($s.'>>'); $this->_out('endobj'); } else { //Allow for additional types $mtd='_put'.strtolower($type); if(!method_exists($this,$mtd)) $this->Error('Unsupported font type: '.$type); $this->$mtd($font); } } } function _putimages() { $filter=($this->compress) ? '/Filter /FlateDecode ' : ''; reset($this->images); while(list($file,$info)=each($this->images)) { $this->_newobj(); $this->images[$file]['n']=$this->n; $this->_out('<_out('/Subtype /Image'); $this->_out('/Width '.$info['w']); $this->_out('/Height '.$info['h']); if($info['cs']=='Indexed') $this->_out('/ColorSpace [/Indexed /DeviceRGB '.(strlen($info['pal'])/3-1).' '.($this->n+1).' 0 R]'); else { $this->_out('/ColorSpace /'.$info['cs']); if($info['cs']=='DeviceCMYK') $this->_out('/Decode [1 0 1 0 1 0 1 0]'); } $this->_out('/BitsPerComponent '.$info['bpc']); $this->_out('/Filter /'.$info['f']); if(isset($info['parms'])) $this->_out($info['parms']); if(isset($info['trns']) and is_array($info['trns'])) { $trns=''; for($i=0;$i_out('/Mask ['.$trns.']'); } $this->_out('/Length '.strlen($info['data']).'>>'); $this->_putstream($info['data']); unset($this->images[$file]['data']); $this->_out('endobj'); //Palette if($info['cs']=='Indexed') { $this->_newobj(); $pal=($this->compress) ? gzcompress($info['pal']) : $info['pal']; $this->_out('<<'.$filter.'/Length '.strlen($pal).'>>'); $this->_putstream($pal); $this->_out('endobj'); } } } function _putresources() { $this->_putfonts(); $this->_putimages(); //Resource dictionary $this->offsets[2]=strlen($this->buffer); $this->_out('2 0 obj'); $this->_out('<_out('/Font <<'); foreach($this->fonts as $font) $this->_out('/F'.$font['i'].' '.$font['n'].' 0 R'); $this->_out('>>'); if(count($this->images)) { $this->_out('/XObject <<'); foreach($this->images as $image) $this->_out('/I'.$image['i'].' '.$image['n'].' 0 R'); $this->_out('>>'); } $this->_out('>>'); $this->_out('endobj'); $this->_putbookmarks(); //EDITEI } function _putinfo() { $this->_out('/Producer '.$this->_textstring('FPDF '.FPDF_VERSION)); if(!empty($this->title)) $this->_out('/Title '.$this->_textstring($this->title)); if(!empty($this->subject)) $this->_out('/Subject '.$this->_textstring($this->subject)); if(!empty($this->author)) $this->_out('/Author '.$this->_textstring($this->author)); if(!empty($this->keywords)) $this->_out('/Keywords '.$this->_textstring($this->keywords)); if(!empty($this->creator)) $this->_out('/Creator '.$this->_textstring($this->creator)); $this->_out('/CreationDate '.$this->_textstring('D:'.date('YmdHis'))); } function _putcatalog() { $this->_out('/Type /Catalog'); $this->_out('/Pages 1 0 R'); if($this->ZoomMode=='fullpage') $this->_out('/OpenAction [3 0 R /Fit]'); elseif($this->ZoomMode=='fullwidth') $this->_out('/OpenAction [3 0 R /FitH null]'); elseif($this->ZoomMode=='real') $this->_out('/OpenAction [3 0 R /XYZ null null 1]'); elseif(!is_string($this->ZoomMode)) $this->_out('/OpenAction [3 0 R /XYZ null null '.($this->ZoomMode/100).']'); if($this->LayoutMode=='single') $this->_out('/PageLayout /SinglePage'); elseif($this->LayoutMode=='continuous') $this->_out('/PageLayout /OneColumn'); elseif($this->LayoutMode=='two') $this->_out('/PageLayout /TwoColumnLeft'); //EDITEI - added lines below if(count($this->outlines)>0) { $this->_out('/Outlines '.$this->OutlineRoot.' 0 R'); $this->_out('/PageMode /UseOutlines'); } if(is_int(strpos($this->DisplayPreferences,'FullScreen'))) $this->_out('/PageMode /FullScreen'); if($this->DisplayPreferences) { $this->_out('/ViewerPreferences<<'); if(is_int(strpos($this->DisplayPreferences,'HideMenubar'))) $this->_out('/HideMenubar true'); if(is_int(strpos($this->DisplayPreferences,'HideToolbar'))) $this->_out('/HideToolbar true'); if(is_int(strpos($this->DisplayPreferences,'HideWindowUI'))) $this->_out('/HideWindowUI true'); if(is_int(strpos($this->DisplayPreferences,'DisplayDocTitle'))) $this->_out('/DisplayDocTitle true'); if(is_int(strpos($this->DisplayPreferences,'CenterWindow'))) $this->_out('/CenterWindow true'); if(is_int(strpos($this->DisplayPreferences,'FitWindow'))) $this->_out('/FitWindow true'); $this->_out('>>'); } } function _puttrailer() { $this->_out('/Size '.($this->n+1)); $this->_out('/Root '.$this->n.' 0 R'); $this->_out('/Info '.($this->n-1).' 0 R'); } function _enddoc() { $this->_putpages(); $this->_putresources(); //Info $this->_newobj(); $this->_out('<<'); $this->_putinfo(); $this->_out('>>'); $this->_out('endobj'); //Catalog $this->_newobj(); $this->_out('<<'); $this->_putcatalog(); $this->_out('>>'); $this->_out('endobj'); //Cross-ref $o=strlen($this->buffer); $this->_out('xref'); $this->_out('0 '.($this->n+1)); $this->_out('0000000000 65535 f '); for($i=1; $i <= $this->n ; $i++) $this->_out(sprintf('%010d 00000 n ',$this->offsets[$i])); //Trailer $this->_out('trailer'); $this->_out('<<'); $this->_puttrailer(); $this->_out('>>'); $this->_out('startxref'); $this->_out($o); $this->_out('%%EOF'); $this->state=3; } function _beginpage($orientation) { $this->page++; $this->pages[$this->page]=''; $this->state=2; $this->x=$this->lMargin; $this->y=$this->tMargin; $this->FontFamily=''; //Page orientation if(!$orientation) $orientation=$this->DefOrientation; else { $orientation=strtoupper($orientation{0}); if($orientation!=$this->DefOrientation) $this->OrientationChanges[$this->page]=true; } if($orientation!=$this->CurOrientation) { //Change orientation if($orientation=='P') { $this->wPt=$this->fwPt; $this->hPt=$this->fhPt; $this->w=$this->fw; $this->h=$this->fh; } else { $this->wPt=$this->fhPt; $this->hPt=$this->fwPt; $this->w=$this->fh; $this->h=$this->fw; } $this->PageBreakTrigger=$this->h-$this->bMargin; $this->CurOrientation=$orientation; } } function _endpage() { //End of page contents $this->state=1; } function _newobj() { //Begin a new object $this->n++; $this->offsets[$this->n]=strlen($this->buffer); $this->_out($this->n.' 0 obj'); } function _dounderline($x,$y,$txt) { //Underline text $up=$this->CurrentFont['up']; $ut=$this->CurrentFont['ut']; $w=$this->GetStringWidth($txt)+$this->ws*substr_count($txt,' '); return sprintf('%.2f %.2f %.2f %.2f re f',$x*$this->k,($this->h-($y-$up/1000*$this->FontSize))*$this->k,$w*$this->k,-$ut/1000*$this->FontSizePt); } function _parsejpg($file) { //Extract info from a JPEG file $a=GetImageSize($file); if(!$a) $this->Error('Missing or incorrect image file: '.$file); if($a[2]!=2) $this->Error('Not a JPEG file: '.$file); if(!isset($a['channels']) or $a['channels']==3) $colspace='DeviceRGB'; elseif($a['channels']==4) $colspace='DeviceCMYK'; else $colspace='DeviceGray'; $bpc=isset($a['bits']) ? $a['bits'] : 8; //Read whole file $f=fopen($file,'rb'); $data=''; while(!feof($f)) $data.=fread($f,4096); fclose($f); return array('w'=>$a[0],'h'=>$a[1],'cs'=>$colspace,'bpc'=>$bpc,'f'=>'DCTDecode','data'=>$data); } function _parsepng($file) { //Extract info from a PNG file $f=fopen($file,'rb'); //Extract info from a PNG file if(!$f) $this->Error('Can\'t open image file: '.$file); //Check signature if(fread($f,8)!=chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10)) $this->Error('Not a PNG file: '.$file); //Read header chunk fread($f,4); if(fread($f,4)!='IHDR') $this->Error('Incorrect PNG file: '.$file); $w=$this->_freadint($f); $h=$this->_freadint($f); $bpc=ord(fread($f,1)); if($bpc>8) $this->Error('16-bit depth not supported: '.$file); $ct=ord(fread($f,1)); if($ct==0) $colspace='DeviceGray'; elseif($ct==2) $colspace='DeviceRGB'; elseif($ct==3) $colspace='Indexed'; else $this->Error('Alpha channel not supported: '.$file); if(ord(fread($f,1))!=0) $this->Error('Unknown compression method: '.$file); if(ord(fread($f,1))!=0) $this->Error('Unknown filter method: '.$file); if(ord(fread($f,1))!=0) $this->Error('Interlacing not supported: '.$file); fread($f,4); $parms='/DecodeParms <>'; //Scan chunks looking for palette, transparency and image data $pal=''; $trns=''; $data=''; do { $n=$this->_freadint($f); $type=fread($f,4); if($type=='PLTE') { //Read palette $pal=fread($f,$n); fread($f,4); } elseif($type=='tRNS') { //Read transparency info $t=fread($f,$n); if($ct==0) $trns=array(ord(substr($t,1,1))); elseif($ct==2) $trns=array(ord(substr($t,1,1)),ord(substr($t,3,1)),ord(substr($t,5,1))); else { $pos=strpos($t,chr(0)); if(is_int($pos)) $trns=array($pos); } fread($f,4); } elseif($type=='IDAT') { //Read image data block $data.=fread($f,$n); fread($f,4); } elseif($type=='IEND') break; else fread($f,$n+4); } while($n); if($colspace=='Indexed' and empty($pal)) $this->Error('Missing palette in '.$file); fclose($f); return array('w'=>$w,'h'=>$h,'cs'=>$colspace,'bpc'=>$bpc,'f'=>'FlateDecode','parms'=>$parms,'pal'=>$pal,'trns'=>$trns,'data'=>$data); } function _parsegif($file) //EDITEI - GIF support is now included { //Function by J�r�me Fenal require_once(RELATIVE_PATH.'gif.php'); //GIF class in pure PHP from Yamasoft (http://www.yamasoft.com/php-gif.zip) $h=0; $w=0; $gif=new CGIF(); if (!$gif->loadFile($file, 0)) $this->Error("GIF parser: unable to open file $file"); if($gif->m_img->m_gih->m_bLocalClr) { $nColors = $gif->m_img->m_gih->m_nTableSize; $pal = $gif->m_img->m_gih->m_colorTable->toString(); if($bgColor != -1) { $bgColor = $this->m_img->m_gih->m_colorTable->colorIndex($bgColor); } $colspace='Indexed'; } elseif($gif->m_gfh->m_bGlobalClr) { $nColors = $gif->m_gfh->m_nTableSize; $pal = $gif->m_gfh->m_colorTable->toString(); if((isset($bgColor)) and $bgColor != -1) { $bgColor = $gif->m_gfh->m_colorTable->colorIndex($bgColor); } $colspace='Indexed'; } else { $nColors = 0; $bgColor = -1; $colspace='DeviceGray'; $pal=''; } $trns=''; if($gif->m_img->m_bTrans && ($nColors > 0)) { $trns=array($gif->m_img->m_nTrans); } $data=$gif->m_img->m_data; $w=$gif->m_gfh->m_nWidth; $h=$gif->m_gfh->m_nHeight; if($colspace=='Indexed' and empty($pal)) $this->Error('Missing palette in '.$file); if ($this->compress) { $data=gzcompress($data); return array( 'w'=>$w, 'h'=>$h, 'cs'=>$colspace, 'bpc'=>8, 'f'=>'FlateDecode', 'pal'=>$pal, 'trns'=>$trns, 'data'=>$data); } else { return array( 'w'=>$w, 'h'=>$h, 'cs'=>$colspace, 'bpc'=>8, 'pal'=>$pal, 'trns'=>$trns, 'data'=>$data); } } function _freadint($f) { //Read a 4-byte integer from file $i=ord(fread($f,1))<<24; $i+=ord(fread($f,1))<<16; $i+=ord(fread($f,1))<<8; $i+=ord(fread($f,1)); return $i; } function _textstring($s) { //Format a text string return '('.$this->_escape($s).')'; } function _escape($s) { //Add \ before \, ( and ) return str_replace(')','\\)',str_replace('(','\\(',str_replace('\\','\\\\',$s))); } function _putstream($s) { $this->_out('stream'); $this->_out($s); $this->_out('endstream'); } function _out($s) { //Add a line to the document if($this->state==2) $this->pages[$this->page] .= $s."\n"; else $this->buffer .= $s."\n"; } }//End of class //Handle special IE contype request if(isset($_SERVER['HTTP_USER_AGENT']) and $_SERVER['HTTP_USER_AGENT']=='contype') { Header('Content-Type: application/pdf'); exit; } } //end of 'if(!class_exists('FPDF'))'' ?>administrator/components/com_virtuemart/classes/pdf/gif.php100644 0 0 66102 10764537560 22040 0ustar 0 0 = gif_loadFile(filename, [index]) // = gif_getSize( or filename, &width, &height) // = gif_outputAsPng(, filename, [bgColor]) // = gif_outputAsBmp(, filename, [bgcolor]) // = gif_outputAsJpeg(, filename, [bgcolor]) - Requires cjpeg /////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////// function gif_loadFile($lpszFileName, $iIndex = 0) { $gif = new CGIF(); if(!$gif->loadFile($lpszFileName, $iIndex)) { return false; } return $gif; } /////////////////////////////////////////////////////////////////////////////////////////////////// function gif_outputAsBmp($gif, $lpszFileName, $bgColor = -1) { if(!isSet($gif) || (@get_class($gif) <> "cgif") || !$gif->loaded() || ($lpszFileName == "")) { return false; } $fd = $gif->getBmp($bgColor); if(strlen($fd) <= 0) { return false; } if(!($fh = @fOpen($lpszFileName, "wb"))) { return false; } @fWrite($fh, $fd, strlen($fd)); @fFlush($fh); @fClose($fh); return true; } /////////////////////////////////////////////////////////////////////////////////////////////////// function gif_outputAsPng($gif, $lpszFileName, $bgColor = -1) { if(!isSet($gif) || (@get_class($gif) <> "cgif") || !$gif->loaded() || ($lpszFileName == "")) { return false; } $fd = $gif->getPng($bgColor); if(strlen($fd) <= 0) { return false; } if(!($fh = @fOpen($lpszFileName, "wb"))) { return false; } @fWrite($fh, $fd, strlen($fd)); @fFlush($fh); @fClose($fh); return true; } /////////////////////////////////////////////////////////////////////////////////////////////////// function gif_outputAsJpeg($gif, $lpszFileName, $bgColor = -1) { if(gif_outputAsBmp($gif, "$lpszFileName.bmp", $gbColor)) { exec("cjpeg $lpszFileName.bmp >$lpszFileName 2>/dev/null"); @unLink("$lpszFileName.bmp"); if(@file_exists($lpszFileName)) { if(@fileSize($lpszFileName) > 0) { return true; } @unLink($lpszFileName); } } return false; } /////////////////////////////////////////////////////////////////////////////////////////////////// function gif_getSize($gif, &$width, &$height) { if(isSet($gif) && (@get_class($gif) == "cgif") && $gif->loaded()) { $width = $gif->width(); $height = $gif->height(); } else if(@file_exists($gif)) { $myGIF = new CGIF(); if(!$myGIF->getSize($gif, $width, $height)) { return false; } } else { return false; } return true; } /////////////////////////////////////////////////////////////////////////////////////////////////// class CGIFLZW { var $MAX_LZW_BITS; var $Fresh, $CodeSize, $SetCodeSize, $MaxCode, $MaxCodeSize, $FirstCode, $OldCode; var $ClearCode, $EndCode, $Next, $Vals, $Stack, $sp, $Buf, $CurBit, $LastBit, $Done, $LastByte; /////////////////////////////////////////////////////////////////////////// // CONSTRUCTOR function CGIFLZW() { $this->MAX_LZW_BITS = 12; unSet($this->Next); unSet($this->Vals); unSet($this->Stack); unSet($this->Buf); $this->Next = range(0, (1 << $this->MAX_LZW_BITS) - 1); $this->Vals = range(0, (1 << $this->MAX_LZW_BITS) - 1); $this->Stack = range(0, (1 << ($this->MAX_LZW_BITS + 1)) - 1); $this->Buf = range(0, 279); } /////////////////////////////////////////////////////////////////////////// function deCompress($data, &$datLen) { $stLen = strlen($data); $datLen = 0; $ret = ""; // INITIALIZATION $this->LZWCommand($data, true); while(($iIndex = $this->LZWCommand($data, false)) >= 0) { $ret .= chr($iIndex); } $datLen = $stLen - strlen($data); if($iIndex != -2) { return false; } return $ret; } /////////////////////////////////////////////////////////////////////////// function LZWCommand(&$data, $bInit) { if($bInit) { $this->SetCodeSize = ord($data{0}); $data = substr($data, 1); $this->CodeSize = $this->SetCodeSize + 1; $this->ClearCode = 1 << $this->SetCodeSize; $this->EndCode = $this->ClearCode + 1; $this->MaxCode = $this->ClearCode + 2; $this->MaxCodeSize = $this->ClearCode << 1; $this->GetCode($data, $bInit); $this->Fresh = 1; for($i = 0; $i < $this->ClearCode; $i++) { $this->Next[$i] = 0; $this->Vals[$i] = $i; } for(; $i < (1 << $this->MAX_LZW_BITS); $i++) { $this->Next[$i] = 0; $this->Vals[$i] = 0; } $this->sp = 0; return 1; } if($this->Fresh) { $this->Fresh = 0; do { $this->FirstCode = $this->GetCode($data, $bInit); $this->OldCode = $this->FirstCode; } while($this->FirstCode == $this->ClearCode); return $this->FirstCode; } if($this->sp > 0) { $this->sp--; return $this->Stack[$this->sp]; } while(($Code = $this->GetCode($data, $bInit)) >= 0) { if($Code == $this->ClearCode) { for($i = 0; $i < $this->ClearCode; $i++) { $this->Next[$i] = 0; $this->Vals[$i] = $i; } for(; $i < (1 << $this->MAX_LZW_BITS); $i++) { $this->Next[$i] = 0; $this->Vals[$i] = 0; } $this->CodeSize = $this->SetCodeSize + 1; $this->MaxCodeSize = $this->ClearCode << 1; $this->MaxCode = $this->ClearCode + 2; $this->sp = 0; $this->FirstCode = $this->GetCode($data, $bInit); $this->OldCode = $this->FirstCode; return $this->FirstCode; } if($Code == $this->EndCode) { return -2; } $InCode = $Code; if($Code >= $this->MaxCode) { $this->Stack[$this->sp] = $this->FirstCode; $this->sp++; $Code = $this->OldCode; } while($Code >= $this->ClearCode) { $this->Stack[$this->sp] = $this->Vals[$Code]; $this->sp++; if($Code == $this->Next[$Code]) // Circular table entry, big GIF Error! return -1; $Code = $this->Next[$Code]; } $this->FirstCode = $this->Vals[$Code]; $this->Stack[$this->sp] = $this->FirstCode; $this->sp++; if(($Code = $this->MaxCode) < (1 << $this->MAX_LZW_BITS)) { $this->Next[$Code] = $this->OldCode; $this->Vals[$Code] = $this->FirstCode; $this->MaxCode++; if(($this->MaxCode >= $this->MaxCodeSize) && ($this->MaxCodeSize < (1 << $this->MAX_LZW_BITS))) { $this->MaxCodeSize *= 2; $this->CodeSize++; } } $this->OldCode = $InCode; if($this->sp > 0) { $this->sp--; return $this->Stack[$this->sp]; } } return $Code; } /////////////////////////////////////////////////////////////////////////// function GetCode(&$data, $bInit) { if($bInit) { $this->CurBit = 0; $this->LastBit = 0; $this->Done = 0; $this->LastByte = 2; return 1; } if(($this->CurBit + $this->CodeSize) >= $this->LastBit) { if($this->Done) { if($this->CurBit >= $this->LastBit) { // Ran off the end of my bits return 0; } return -1; } $this->Buf[0] = $this->Buf[$this->LastByte - 2]; $this->Buf[1] = $this->Buf[$this->LastByte - 1]; $Count = ord($data{0}); $data = substr($data, 1); if($Count) { for($i = 0; $i < $Count; $i++) { $this->Buf[2 + $i] = ord($data{$i}); } $data = substr($data, $Count); } else { $this->Done = 1; } $this->LastByte = 2 + $Count; $this->CurBit = ($this->CurBit - $this->LastBit) + 16; $this->LastBit = (2 + $Count) << 3; } $iRet = 0; for($i = $this->CurBit, $j = 0; $j < $this->CodeSize; $i++, $j++) { $iRet |= (($this->Buf[intval($i / 8)] & (1 << ($i % 8))) != 0) << $j; } $this->CurBit += $this->CodeSize; return $iRet; } } /////////////////////////////////////////////////////////////////////////////////////////////////// class CGIFCOLORTABLE { var $m_nColors; var $m_arColors; /////////////////////////////////////////////////////////////////////////// // CONSTRUCTOR function CGIFCOLORTABLE() { unSet($this->m_nColors); unSet($this->m_arColors); } /////////////////////////////////////////////////////////////////////////// function load($lpData, $num) { $this->m_nColors = 0; $this->m_arColors = array(); for($i = 0; $i < $num; $i++) { $rgb = substr($lpData, $i * 3, 3); if(strlen($rgb) < 3) { return false; } $this->m_arColors[] = (ord($rgb{2}) << 16) + (ord($rgb{1}) << 8) + ord($rgb{0}); $this->m_nColors++; } return true; } /////////////////////////////////////////////////////////////////////////// function toString() { $ret = ""; for($i = 0; $i < $this->m_nColors; $i++) { $ret .= chr(($this->m_arColors[$i] & 0x000000FF)) . // R chr(($this->m_arColors[$i] & 0x0000FF00) >> 8) . // G chr(($this->m_arColors[$i] & 0x00FF0000) >> 16); // B } return $ret; } /////////////////////////////////////////////////////////////////////////// function toRGBQuad() { $ret = ""; for($i = 0; $i < $this->m_nColors; $i++) { $ret .= chr(($this->m_arColors[$i] & 0x00FF0000) >> 16) . // B chr(($this->m_arColors[$i] & 0x0000FF00) >> 8) . // G chr(($this->m_arColors[$i] & 0x000000FF)) . // R "\x00"; } return $ret; } /////////////////////////////////////////////////////////////////////////// function colorIndex($rgb) { $rgb = intval($rgb) & 0xFFFFFF; $r1 = ($rgb & 0x0000FF); $g1 = ($rgb & 0x00FF00) >> 8; $b1 = ($rgb & 0xFF0000) >> 16; $idx = -1; for($i = 0; $i < $this->m_nColors; $i++) { $r2 = ($this->m_arColors[$i] & 0x000000FF); $g2 = ($this->m_arColors[$i] & 0x0000FF00) >> 8; $b2 = ($this->m_arColors[$i] & 0x00FF0000) >> 16; $d = abs($r2 - $r1) + abs($g2 - $g1) + abs($b2 - $b1); if(($idx == -1) || ($d < $dif)) { $idx = $i; $dif = $d; } } return $idx; } } /////////////////////////////////////////////////////////////////////////////////////////////////// class CGIFFILEHEADER { var $m_lpVer; var $m_nWidth; var $m_nHeight; var $m_bGlobalClr; var $m_nColorRes; var $m_bSorted; var $m_nTableSize; var $m_nBgColor; var $m_nPixelRatio; var $m_colorTable; /////////////////////////////////////////////////////////////////////////// // CONSTRUCTOR function CGIFFILEHEADER() { unSet($this->m_lpVer); unSet($this->m_nWidth); unSet($this->m_nHeight); unSet($this->m_bGlobalClr); unSet($this->m_nColorRes); unSet($this->m_bSorted); unSet($this->m_nTableSize); unSet($this->m_nBgColor); unSet($this->m_nPixelRatio); unSet($this->m_colorTable); } /////////////////////////////////////////////////////////////////////////// function load($lpData, &$hdrLen) { $hdrLen = 0; $this->m_lpVer = substr($lpData, 0, 6); if(($this->m_lpVer <> "GIF87a") && ($this->m_lpVer <> "GIF89a")) { return false; } $this->m_nWidth = $this->w2i(substr($lpData, 6, 2)); $this->m_nHeight = $this->w2i(substr($lpData, 8, 2)); if(!$this->m_nWidth || !$this->m_nHeight) { return false; } $b = ord(substr($lpData, 10, 1)); $this->m_bGlobalClr = ($b & 0x80) ? true : false; $this->m_nColorRes = ($b & 0x70) >> 4; $this->m_bSorted = ($b & 0x08) ? true : false; $this->m_nTableSize = 2 << ($b & 0x07); $this->m_nBgColor = ord(substr($lpData, 11, 1)); $this->m_nPixelRatio = ord(substr($lpData, 12, 1)); $hdrLen = 13; if($this->m_bGlobalClr) { $this->m_colorTable = new CGIFCOLORTABLE(); if(!$this->m_colorTable->load(substr($lpData, $hdrLen), $this->m_nTableSize)) { return false; } $hdrLen += 3 * $this->m_nTableSize; } return true; } /////////////////////////////////////////////////////////////////////////// function w2i($str) { return ord(substr($str, 0, 1)) + (ord(substr($str, 1, 1)) << 8); } } /////////////////////////////////////////////////////////////////////////////////////////////////// class CGIFIMAGEHEADER { var $m_nLeft; var $m_nTop; var $m_nWidth; var $m_nHeight; var $m_bLocalClr; var $m_bInterlace; var $m_bSorted; var $m_nTableSize; var $m_colorTable; /////////////////////////////////////////////////////////////////////////// // CONSTRUCTOR function CGIFIMAGEHEADER() { unSet($this->m_nLeft); unSet($this->m_nTop); unSet($this->m_nWidth); unSet($this->m_nHeight); unSet($this->m_bLocalClr); unSet($this->m_bInterlace); unSet($this->m_bSorted); unSet($this->m_nTableSize); unSet($this->m_colorTable); } /////////////////////////////////////////////////////////////////////////// function load($lpData, &$hdrLen) { $hdrLen = 0; $this->m_nLeft = $this->w2i(substr($lpData, 0, 2)); $this->m_nTop = $this->w2i(substr($lpData, 2, 2)); $this->m_nWidth = $this->w2i(substr($lpData, 4, 2)); $this->m_nHeight = $this->w2i(substr($lpData, 6, 2)); if(!$this->m_nWidth || !$this->m_nHeight) { return false; } $b = ord($lpData{8}); $this->m_bLocalClr = ($b & 0x80) ? true : false; $this->m_bInterlace = ($b & 0x40) ? true : false; $this->m_bSorted = ($b & 0x20) ? true : false; $this->m_nTableSize = 2 << ($b & 0x07); $hdrLen = 9; if($this->m_bLocalClr) { $this->m_colorTable = new CGIFCOLORTABLE(); if(!$this->m_colorTable->load(substr($lpData, $hdrLen), $this->m_nTableSize)) { return false; } $hdrLen += 3 * $this->m_nTableSize; } return true; } /////////////////////////////////////////////////////////////////////////// function w2i($str) { return ord(substr($str, 0, 1)) + (ord(substr($str, 1, 1)) << 8); } } /////////////////////////////////////////////////////////////////////////////////////////////////// class CGIFIMAGE { var $m_disp; var $m_bUser; var $m_bTrans; var $m_nDelay; var $m_nTrans; var $m_lpComm; var $m_gih; var $m_data; var $m_lzw; /////////////////////////////////////////////////////////////////////////// function CGIFIMAGE() { unSet($this->m_disp); unSet($this->m_bUser); unSet($this->m_bTrans); unSet($this->m_nDelay); unSet($this->m_nTrans); unSet($this->m_lpComm); unSet($this->m_data); $this->m_gih = new CGIFIMAGEHEADER(); $this->m_lzw = new CGIFLZW(); } /////////////////////////////////////////////////////////////////////////// function load($data, &$datLen) { $datLen = 0; while(true) { $b = ord($data{0}); $data = substr($data, 1); $datLen++; switch($b) { case 0x21: // Extension $len = 0; if(!$this->skipExt($data, $len)) { return false; } $datLen += $len; break; case 0x2C: // Image // LOAD HEADER & COLOR TABLE $len = 0; if(!$this->m_gih->load($data, $len)) { return false; } $data = substr($data, $len); $datLen += $len; // ALLOC BUFFER $len = 0; if(!($this->m_data = $this->m_lzw->deCompress($data, $len))) { return false; } $data = substr($data, $len); $datLen += $len; if($this->m_gih->m_bInterlace) { $this->deInterlace(); } return true; case 0x3B: // EOF default: return false; } } return false; } /////////////////////////////////////////////////////////////////////////// function skipExt(&$data, &$extLen) { $extLen = 0; $b = ord($data{0}); $data = substr($data, 1); $extLen++; switch($b) { case 0xF9: // Graphic Control $b = ord($data{1}); $this->m_disp = ($b & 0x1C) >> 2; $this->m_bUser = ($b & 0x02) ? true : false; $this->m_bTrans = ($b & 0x01) ? true : false; $this->m_nDelay = $this->w2i(substr($data, 2, 2)); $this->m_nTrans = ord($data{4}); break; case 0xFE: // Comment $this->m_lpComm = substr($data, 1, ord($data{0})); break; case 0x01: // Plain text break; case 0xFF: // Application break; } // SKIP DEFAULT AS DEFS MAY CHANGE $b = ord($data{0}); $data = substr($data, 1); $extLen++; while($b > 0) { $data = substr($data, $b); $extLen += $b; $b = ord($data{0}); $data = substr($data, 1); $extLen++; } return true; } /////////////////////////////////////////////////////////////////////////// function w2i($str) { return ord(substr($str, 0, 1)) + (ord(substr($str, 1, 1)) << 8); } /////////////////////////////////////////////////////////////////////////// function deInterlace() { $data = $this->m_data; for($i = 0; $i < 4; $i++) { switch($i) { case 0: $s = 8; $y = 0; break; case 1: $s = 8; $y = 4; break; case 2: $s = 4; $y = 2; break; case 3: $s = 2; $y = 1; break; } for(; $y < $this->m_gih->m_nHeight; $y += $s) { $lne = substr($this->m_data, 0, $this->m_gih->m_nWidth); $this->m_data = substr($this->m_data, $this->m_gih->m_nWidth); $data = substr($data, 0, $y * $this->m_gih->m_nWidth) . $lne . substr($data, ($y + 1) * $this->m_gih->m_nWidth); } } $this->m_data = $data; } } /////////////////////////////////////////////////////////////////////////////////////////////////// class CGIF { var $m_gfh; var $m_lpData; var $m_img; var $m_bLoaded; /////////////////////////////////////////////////////////////////////////// // CONSTRUCTOR function CGIF() { $this->m_gfh = new CGIFFILEHEADER(); $this->m_img = new CGIFIMAGE(); $this->m_lpData = ""; $this->m_bLoaded = false; } /////////////////////////////////////////////////////////////////////////// function loadFile($lpszFileName, $iIndex) { if($iIndex < 0) { return false; } // READ FILE if(!($fh = @fOpen($lpszFileName, "rb"))) { return false; } //EDITEI - in order to read remote files (HTTP(s) and FTP protocols) if ( strpos($lpszFileName,"http") !== false or strpos($lpszFileName,"ftp") !== false ) { $contents = ''; while (!feof($fh)) $contents .= @fread($fh, 8192); } else { $contents = @fread($fh,@filesize($lpszFileName) ); } $this->m_lpData = $contents; // $this->m_lpData = @fRead($fh, @fileSize($lpszFileName)); fClose($fh); // GET FILE HEADER $len = 0; if(!$this->m_gfh->load($this->m_lpData, $len)) { return false; } $this->m_lpData = substr($this->m_lpData, $len); do { $imgLen = 0; if(!$this->m_img->load($this->m_lpData, $imgLen)) { return false; } $this->m_lpData = substr($this->m_lpData, $imgLen); } while($iIndex-- > 0); $this->m_bLoaded = true; return true; } /////////////////////////////////////////////////////////////////////////// function getSize($lpszFileName, &$width, &$height) { if(!($fh = @fOpen($lpszFileName, "rb"))) { return false; } $data = @fRead($fh, @fileSize($lpszFileName)); @fClose($fh); $gfh = new CGIFFILEHEADER(); $len = 0; if(!$gfh->load($data, $len)) { return false; } $width = $gfh->m_nWidth; $height = $gfh->m_nHeight; return true; } /////////////////////////////////////////////////////////////////////////// function getBmp($bgColor) { $out = ""; if(!$this->m_bLoaded) { return false; } // PREPARE COLOR TABLE (RGBQUADs) if($this->m_img->m_gih->m_bLocalClr) { $nColors = $this->m_img->m_gih->m_nTableSize; $rgbq = $this->m_img->m_gih->m_colorTable->toRGBQuad(); if($bgColor != -1) { $bgColor = $this->m_img->m_gih->m_colorTable->colorIndex($bgColor); } } else if($this->m_gfh->m_bGlobalClr) { $nColors = $this->m_gfh->m_nTableSize; $rgbq = $this->m_gfh->m_colorTable->toRGBQuad(); if($bgColor != -1) { $bgColor = $this->m_gfh->m_colorTable->colorIndex($bgColor); } } else { $nColors = 0; $bgColor = -1; } // PREPARE BITMAP BITS $data = $this->m_img->m_data; $nPxl = ($this->m_gfh->m_nHeight - 1) * $this->m_gfh->m_nWidth; $bmp = ""; $nPad = ($this->m_gfh->m_nWidth % 4) ? 4 - ($this->m_gfh->m_nWidth % 4) : 0; for($y = 0; $y < $this->m_gfh->m_nHeight; $y++) { for($x = 0; $x < $this->m_gfh->m_nWidth; $x++, $nPxl++) { if( ($x >= $this->m_img->m_gih->m_nLeft) && ($y >= $this->m_img->m_gih->m_nTop) && ($x < ($this->m_img->m_gih->m_nLeft + $this->m_img->m_gih->m_nWidth)) && ($y < ($this->m_img->m_gih->m_nTop + $this->m_img->m_gih->m_nHeight))) { // PART OF IMAGE if($this->m_img->m_bTrans && (ord($data{$nPxl}) == $this->m_img->m_nTrans)) { // TRANSPARENT -> BACKGROUND if($bgColor == -1) { $bmp .= chr($this->m_gfh->m_nBgColor); } else { $bmp .= chr($bgColor); } } else { $bmp .= $data{$nPxl}; } } else { // BACKGROUND if($bgColor == -1) { $bmp .= chr($this->m_gfh->m_nBgColor); } else { $bmp .= chr($bgColor); } } } $nPxl -= $this->m_gfh->m_nWidth << 1; // ADD PADDING for($x = 0; $x < $nPad; $x++) { $bmp .= "\x00"; } } // BITMAPFILEHEADER $out .= "BM"; $out .= $this->dword(14 + 40 + ($nColors << 2) + strlen($bmp)); $out .= "\x00\x00"; $out .= "\x00\x00"; $out .= $this->dword(14 + 40 + ($nColors << 2)); // BITMAPINFOHEADER $out .= $this->dword(40); $out .= $this->dword($this->m_gfh->m_nWidth); $out .= $this->dword($this->m_gfh->m_nHeight); $out .= "\x01\x00"; $out .= "\x08\x00"; $out .= "\x00\x00\x00\x00"; $out .= "\x00\x00\x00\x00"; $out .= "\x12\x0B\x00\x00"; $out .= "\x12\x0B\x00\x00"; $out .= $this->dword($nColors % 256); $out .= "\x00\x00\x00\x00"; // COLOR TABLE if($nColors > 0) { $out .= $rgbq; } // DATA $out .= $bmp; return $out; } /////////////////////////////////////////////////////////////////////////// function getPng($bgColor) { $out = ""; if(!$this->m_bLoaded) { return false; } // PREPARE COLOR TABLE (RGBQUADs) if($this->m_img->m_gih->m_bLocalClr) { $nColors = $this->m_img->m_gih->m_nTableSize; $pal = $this->m_img->m_gih->m_colorTable->toString(); if($bgColor != -1) { $bgColor = $this->m_img->m_gih->m_colorTable->colorIndex($bgColor); } } else if($this->m_gfh->m_bGlobalClr) { $nColors = $this->m_gfh->m_nTableSize; $pal = $this->m_gfh->m_colorTable->toString(); if($bgColor != -1) { $bgColor = $this->m_gfh->m_colorTable->colorIndex($bgColor); } } else { $nColors = 0; $bgColor = -1; } // PREPARE BITMAP BITS $data = $this->m_img->m_data; $nPxl = 0; $bmp = ""; for($y = 0; $y < $this->m_gfh->m_nHeight; $y++) { $bmp .= "\x00"; for($x = 0; $x < $this->m_gfh->m_nWidth; $x++, $nPxl++) { if( ($x >= $this->m_img->m_gih->m_nLeft) && ($y >= $this->m_img->m_gih->m_nTop) && ($x < ($this->m_img->m_gih->m_nLeft + $this->m_img->m_gih->m_nWidth)) && ($y < ($this->m_img->m_gih->m_nTop + $this->m_img->m_gih->m_nHeight))) { // PART OF IMAGE $bmp .= $data{$nPxl}; } else { // BACKGROUND if($bgColor == -1) { $bmp .= chr($this->m_gfh->m_nBgColor); } else { $bmp .= chr($bgColor); } } } } $bmp = gzcompress($bmp, 9); /////////////////////////////////////////////////////////////////////// // SIGNATURE $out .= "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A"; /////////////////////////////////////////////////////////////////////// // HEADER $out .= "\x00\x00\x00\x0D"; $tmp = "IHDR"; $tmp .= $this->ndword($this->m_gfh->m_nWidth); $tmp .= $this->ndword($this->m_gfh->m_nHeight); $tmp .= "\x08\x03\x00\x00\x00"; $out .= $tmp; $out .= $this->ndword(crc32($tmp)); /////////////////////////////////////////////////////////////////////// // PALETTE if($nColors > 0) { $out .= $this->ndword($nColors * 3); $tmp = "PLTE"; $tmp .= $pal; $out .= $tmp; $out .= $this->ndword(crc32($tmp)); } /////////////////////////////////////////////////////////////////////// // TRANSPARENCY if($this->m_img->m_bTrans && ($nColors > 0)) { $out .= $this->ndword($nColors); $tmp = "tRNS"; for($i = 0; $i < $nColors; $i++) { $tmp .= ($i == $this->m_img->m_nTrans) ? "\x00" : "\xFF"; } $out .= $tmp; $out .= $this->ndword(crc32($tmp)); } /////////////////////////////////////////////////////////////////////// // DATA BITS $out .= $this->ndword(strlen($bmp)); $tmp = "IDAT"; $tmp .= $bmp; $out .= $tmp; $out .= $this->ndword(crc32($tmp)); /////////////////////////////////////////////////////////////////////// // END OF FILE $out .= "\x00\x00\x00\x00IEND\xAE\x42\x60\x82"; return $out; } /////////////////////////////////////////////////////////////////////////// function dword($val) { $val = intval($val); return chr($val & 0xFF).chr(($val & 0xFF00) >> 8).chr(($val & 0xFF0000) >> 16).chr(($val & 0xFF000000) >> 24); } /////////////////////////////////////////////////////////////////////////// function ndword($val) { $val = intval($val); return chr(($val & 0xFF000000) >> 24).chr(($val & 0xFF0000) >> 16).chr(($val & 0xFF00) >> 8).chr($val & 0xFF); } /////////////////////////////////////////////////////////////////////////// function width() { return $this->m_gfh->m_nWidth; } /////////////////////////////////////////////////////////////////////////// function height() { return $this->m_gfh->m_nHeight; } /////////////////////////////////////////////////////////////////////////// function comment() { return $this->m_img->m_lpComm; } /////////////////////////////////////////////////////////////////////////// function loaded() { return $this->m_bLoaded; } } /////////////////////////////////////////////////////////////////////////////////////////////////// ?> administrator/components/com_virtuemart/classes/pdf/html2fpdf.php100644 0 0 365344 11220612113 23163 0ustar 0 0 currentfont - mine . $this->CurrentFont - fpdf's TODO (in the future...): - Make font-family, font-size, lineheight customizable - Increase number of HTML/CSS tags/properties, Image/Font Types, recognized/supported - allow BMP support? (tried with http://phpthumb.sourceforge.net/ but failed) - Improve CSS support - support image side-by-side or one-below-another or both? - Improve code clarity even more (modularize and get better var names like on textbuffer array's indexes for example) ////////////////////////////////////////////////////////////////////////////// //////////////DO NOT MODIFY THE CONTENTS OF THIS BOX////////////////////////// ////////////////////////////////////////////////////////////////////////////// // // // HTML2FPDF is a php script to read a HTML text and generate a PDF file. // // Copyright (C) 2004-2005 Renato Coelho // // This script may be distributed as long as the following files are kept // // together: // // // // fpdf.php, html2fpdf.php, gif.php,htmltoolkit.php,license.txt,credits.txt // // // ////////////////////////////////////////////////////////////////////////////// Misc. Observations: - CSS + align = bug! (?) OBS1: para textos de mais de 1 p?gina, talvez tenha que juntar varios $texto_artigo antes de mandar gerar o PDF, para que o PDF gerado seja completo. OBS2: there are 2 types of spaces 32 and 160 (ascii values) OBS3: //! is a special comment to be used with source2doc.php, a script I created in order to generate the doc on the site html2fpdf.sf.net OBS4: var $LineWidth; // line width in user unit - use this to make css thin/medium/thick work OBS5: Images and Textareas: when they are inserted you can only type below them (==display:block) OBS6: Optimized to 'A4' paper (default font: Arial , normal , size 11 ) OBS7: Regexp + Perl ([preg]accepts non-greedy quantifiers while PHP[ereg] does not) Perl: '/regexp/x' where x == option ( x = i:ignore case , x = s: DOT gets \n as well) ========================END OF INITIAL COMMENTS================================= */ define('HTML2FPDF_VERSION','3.0(beta)'); if (!defined('RELATIVE_PATH')) define('RELATIVE_PATH',''); if (!defined('FPDF_FONTPATH')) define('FPDF_FONTPATH','font/'); require_once(RELATIVE_PATH.'fpdf.php'); require_once(RELATIVE_PATH.'htmltoolkit.php'); class HTML2FPDF extends FPDF { //internal attributes var $HREF; //! string var $pgwidth; //! float var $fontlist; //! array var $issetfont; //! bool var $issetcolor; //! bool var $titulo; //! string var $oldx; //! float var $oldy; //! float var $B; //! int var $U; //! int var $I; //! int var $tablestart; //! bool var $tdbegin; //! bool var $table; //! array var $cell; //! array var $col; //! int var $row; //! int var $divbegin; //! bool var $divalign; //! char var $divwidth; //! float var $divheight; //! float var $divbgcolor; //! bool var $divcolor; //! bool var $divborder; //! int var $divrevert; //! bool var $listlvl; //! int var $listnum; //! int var $listtype; //! string //array(lvl,# of occurrences) var $listoccur; //! array //array(lvl,occurrence,type,maxnum) var $listlist; //! array //array(lvl,num,content,type) var $listitem; //! array var $buffer_on; //! bool var $pbegin; //! bool var $pjustfinished; //! bool var $blockjustfinished; //! bool var $SUP; //! bool var $SUB; //! bool var $toupper; //! bool var $tolower; //! bool var $dash_on; //! bool var $dotted_on; //! bool var $strike; //! bool var $CSS; //! array var $cssbegin; //! bool var $backupcss; //! array var $textbuffer; //! array var $currentstyle; //! string var $currentfont; //! string var $colorarray; //! array var $bgcolorarray; //! array var $internallink; //! array var $enabledtags; //! string var $lineheight; //! int var $basepath; //! string // array('COLOR','WIDTH','OLDWIDTH') var $outlineparam; //! array var $outline_on; //! bool var $specialcontent; //! string var $selectoption; //! array //options attributes var $usecss; //! bool var $usepre; //! bool var $usetableheader; //! bool var $shownoimg; //! bool function HTML2FPDF($orientation='P',$unit='mm',$format='A4') { //! @desc Constructor //! @return An object (a class instance) //Call parent constructor $this->FPDF($orientation,$unit,$format); //To make the function Footer() work properly $this->AliasNbPages(); //Enable all tags as default $this->DisableTags(); //Set default display preferences $this->DisplayPreferences(''); //Initialization of the attributes $this->SetFont('Arial','',11); // Changeable?(not yet...) $this->lineheight = 5; // Related to FontSizePt == 11 $this->pgwidth = $this->fw - $this->lMargin - $this->rMargin ; $this->SetFillColor(255); $this->HREF=''; $this->titulo=''; $this->oldx=-1; $this->oldy=-1; $this->B=0; $this->U=0; $this->I=0; $this->listlvl=0; $this->listnum=0; $this->listtype=''; $this->listoccur=array(); $this->listlist=array(); $this->listitem=array(); $this->tablestart=false; $this->tdbegin=false; $this->table=array(); $this->cell=array(); $this->col=-1; $this->row=-1; $this->divbegin=false; $this->divalign="L"; $this->divwidth=0; $this->divheight=0; $this->divbgcolor=false; $this->divcolor=false; $this->divborder=0; $this->divrevert=false; $this->fontlist=array("arial","times","courier","helvetica","symbol","monospace","serif","sans"); $this->issetfont=false; $this->issetcolor=false; $this->pbegin=false; $this->pjustfinished=false; $this->blockjustfinished = true; //in order to eliminate exceeding left-side spaces $this->toupper=false; $this->tolower=false; $this->dash_on=false; $this->dotted_on=false; $this->SUP=false; $this->SUB=false; $this->buffer_on=false; $this->strike=false; $this->currentfont=''; $this->currentstyle=''; $this->colorarray=array(); $this->bgcolorarray=array(); $this->cssbegin=false; $this->textbuffer=array(); $this->CSS=array(); $this->backupcss=array(); $this->internallink=array(); $this->basepath = ""; $this->outlineparam = array(); $this->outline_on = false; $this->specialcontent = ''; $this->selectoption = array(); $this->shownoimg=false; $this->usetableheader=false; $this->usecss=true; $this->usepre=true; } function setBasePath($str) { //! @desc Inform the script where the html file is (full path - e.g. http://www.google.com/dir1/dir2/dir3/file.html ) in order to adjust HREF and SRC links. No-Parameter: The directory where this script is. //! @return void $this->basepath = dirname($str) . "/"; $this->basepath = str_replace("\\","/",$this->basepath); //If on Windows } function ShowNOIMG_GIF($opt=true) { //! @desc Enable/Disable Displaying the no_img.gif when an image is not found. No-Parameter: Enable //! @return void $this->shownoimg=$opt; } function UseCSS($opt=true) { //! @desc Enable/Disable CSS recognition. No-Parameter: Enable //! @return void $this->usecss=$opt; } function UseTableHeader($opt=true) { //! @desc Enable/Disable Table Header to appear every new page. No-Parameter: Enable //! @return void $this->usetableheader=$opt; } function UsePRE($opt=true) { //! @desc Enable/Disable pre tag recognition. No-Parameter: Enable //! @return void $this->usepre=$opt; } //Page header function Header($content='') { //! @return void //! @desc The header is printed in every page. if($this->usetableheader and $content != '') { $y = $this->y; foreach($content as $tableheader) { $this->y = $y; //Set some cell values $x = $tableheader['x']; $w = $tableheader['w']; $h = $tableheader['h']; $va = $tableheader['va']; $mih = $tableheader['mih']; $fill = $tableheader['bgcolor']; $border = $tableheader['border']; $align = $tableheader['a']; //Align $this->divalign=$align; $this->x = $x; //Vertical align if (!isset($va) || $va=='M') $this->y += ($h-$mih)/2; elseif (isset($va) && $va=='B') $this->y += $h-$mih; if ($fill) { $color = ConvertColor($fill); $this->SetFillColor($color['R'],$color['G'],$color['B']); $this->Rect($x, $y, $w, $h, 'F'); } //Border if (isset($border) and $border != 'all') $this->_tableRect($x, $y, $w, $h, $border); elseif (isset($border) && $border == 'all') $this->Rect($x, $y, $w, $h); //Print cell content $this->divwidth = $w-2; $this->divheight = 1.1*$this->lineheight; $textbuffer = $tableheader['textbuffer']; if (!empty($textbuffer)) $this->printbuffer($textbuffer,false,true/*inside a table*/); $textbuffer = array(); } $this->y = $y + $h; //Update y coordinate }//end of 'if usetableheader ...' } //Page footer function Footer() { //! @return void //! @desc The footer is printed in every page! //Position at 1.0 cm from bottom $this->SetY(-10); //Copyright //especial para esta vers?o $this->SetFont('Arial','B',9); $this->SetTextColor(0); //Arial italic 9 $this->SetFont('Arial','I',9); //Page number $this->Cell(0,10,$this->PageNo().'/{nb}',0,0,'C'); //Return Font to normal $this->SetFont('Arial','',11); } /////////////////// /// HTML parser /// /////////////////// function WriteHTML($html) { //! @desc HTML parser //! @return void /* $e == content */ $this->ReadMetaTags($html); $html = AdjustHTML($html,$this->usepre); //Try to make HTML look more like XHTML if ($this->usecss) $html = $this->ReadCSS($html); //Add new supported tags in the DisableTags function $html=str_replace('enabledtags); //remove all unsupported tags, but the ones inside the 'enabledtags' string //Explode the string in order to parse the HTML code $a=preg_split('/<(.*?)>/ms',$html,-1,PREG_SPLIT_DELIM_CAPTURE); foreach($a as $i => $e) { if($i%2==0) { //TEXT //Adjust lineheight // $this->lineheight = (5*$this->FontSizePt)/11; //should be inside printbuffer? //Adjust text, if needed if (strpos($e,"&") !== false) //HTML-ENTITIES decoding { if (strpos($e,"#") !== false) $e = value_entity_decode($e); // Decode value entities //Avoid crashing the script on PHP 4.0 $version = phpversion(); $version = str_replace('.','',$version); if ($version >= 430) $e = html_entity_decode($e,ENT_QUOTES,'cp1252'); // changes   and the like by their respective char else $e = lesser_entity_decode($e); } $e = str_replace(chr(160),chr(32),$e); //unify ascii code of spaces (in order to recognize all of them correctly) if (strlen($e) == 0) continue; if ($this->divrevert) $e = strrev($e); if ($this->toupper) $e = strtoupper($e); if ($this->tolower) $e = strtolower($e); //Start of 'if/elseif's if($this->titulo) $this->SetTitle($e); elseif($this->specialcontent) { if ($this->specialcontent == "type=select" and $this->selectoption['ACTIVE'] == true) //SELECT tag (form element) { $stringwidth = $this->GetStringWidth($e); if (!isset($this->selectoption['MAXWIDTH']) or $stringwidth > $this->selectoption['MAXWIDTH']) $this->selectoption['MAXWIDTH'] = $stringwidth; if (!isset($this->selectoption['SELECTED']) or $this->selectoption['SELECTED'] == '') $this->selectoption['SELECTED'] = $e; } else $this->textbuffer[] = array("???"/*identifier*/.$this->specialcontent."???".$e); } elseif($this->tablestart) { if($this->tdbegin) { $this->cell[$this->row][$this->col]['textbuffer'][] = array($e,$this->HREF,$this->currentstyle,$this->colorarray,$this->currentfont,$this->SUP,$this->SUB,''/*internal link*/,$this->strike,$this->outlineparam,$this->bgcolorarray); $this->cell[$this->row][$this->col]['text'][] = $e; $this->cell[$this->row][$this->col]['s'] += $this->GetStringWidth($e); } //Ignore content between , and a
    tag (this content is usually only a bunch of spaces) } elseif($this->pbegin or $this->HREF or $this->divbegin or $this->SUP or $this->SUB or $this->strike or $this->buffer_on) $this->textbuffer[] = array($e,$this->HREF,$this->currentstyle,$this->colorarray,$this->currentfont,$this->SUP,$this->SUB,''/*internal link*/,$this->strike,$this->outlineparam,$this->bgcolorarray); //Accumulate text on buffer else { if ($this->blockjustfinished) $e = ltrim($e); if ($e != '') { $this->Write($this->lineheight,$e); //Write text directly in the PDF if ($this->pjustfinished) $this->pjustfinished = false; } } } else { //Tag if($e{0}=='/') $this->CloseTag(strtoupper(substr($e,1))); else { $regexp = '|=\'(.*?)\'|s'; // eliminate single quotes, if any $e = preg_replace($regexp,"=\"\$1\"",$e); $regexp = '| (\\w+?)=([^\\s>"]+)|si'; // changes anykey=anyvalue to anykey="anyvalue" (only do this when this happens inside tags) $e = preg_replace($regexp," \$1=\"\$2\"",$e); //Fix path values, if needed if ((stristr($e,"href=") !== false) or (stristr($e,"src=") !== false) ) { $regexp = '/ (href|src)="(.*?)"/i'; preg_match($regexp,$e,$auxiliararray); $path = $auxiliararray[2]; $path = str_replace("\\","/",$path); //If on Windows //Get link info and obtain its absolute path $regexp = '|^./|'; $path = preg_replace($regexp,'',$path); if($path{0} != '#') //It is not an Internal Link { if (strpos($path,"../") !== false ) //It is a Relative Link { $backtrackamount = substr_count($path,"../"); $maxbacktrack = substr_count($this->basepath,"/") - 1; $filepath = str_replace("../",'',$path); $path = $this->basepath; //If it is an invalid relative link, then make it go to directory root if ($backtrackamount > $maxbacktrack) $backtrackamount = $maxbacktrack; //Backtrack some directories for( $i = 0 ; $i < $backtrackamount + 1 ; $i++ ) $path = substr( $path, 0 , strrpos($path,"/") ); $path = $path . "/" . $filepath; //Make it an absolute path } elseif( strpos($path,":/") === false) //It is a Local Link { $path = $this->basepath . $path; } //Do nothing if it is an Absolute Link } $regexp = '/ (href|src)="(.*?)"/i'; $e = preg_replace($regexp,' \\1="'.$path.'"',$e); }//END of Fix path values //Extract attributes $contents=array(); preg_match_all('/\\S*=["\'][^"\']*["\']/',$e,$contents); preg_match('/\\S+/',$e,$a2); $tag=strtoupper($a2[0]); $attr=array(); if (!empty($contents)) { foreach($contents[0] as $v) { if(ereg('^([^=]*)=["\']?([^"\']*)["\']?$',$v,$a3)) { $attr[strtoupper($a3[1])]=$a3[2]; } } } $this->OpenTag($tag,$attr); } } }//end of foreach($a as $i=>$e) //Create Internal Links, if needed if (!empty($this->internallink) ) { foreach($this->internallink as $k=>$v) { if (strpos($k,"#") !== false ) continue; //ignore $ypos = $v['Y']; $pagenum = $v['PAGE']; $sharp = "#"; while (array_key_exists($sharp.$k,$this->internallink)) { $internallink = $this->internallink[$sharp.$k]; $this->SetLink($internallink,$ypos,$pagenum); $sharp .= "#"; } } } } function OpenTag($tag,$attr) { //! @return void // What this gets: < $tag $attr['WIDTH']="90px" > does not get content here $align = array('left'=>'L','center'=>'C','right'=>'R','top'=>'T','middle'=>'M','bottom'=>'B','justify'=>'J'); $this->blockjustfinished=false; //Opening tag switch($tag){ case 'PAGE_BREAK': //custom-tag case 'NEWPAGE': //custom-tag $this->blockjustfinished = true; $this->AddPage(); break; case 'OUTLINE': //custom-tag (CSS2 property - browsers don't support it yet - Jan2005) //Usage: (default: width=normal color=white) //Text //Mix this tag with the tag to get mixed colors on outlined text! $this->buffer_on = true; if (isset($attr['COLOR'])) $this->outlineparam['COLOR'] = ConvertColor($attr['COLOR']); else $this->outlineparam['COLOR'] = array('R'=>255,'G'=>255,'B'=>255); //white $this->outlineparam['OLDWIDTH'] = $this->LineWidth; if (isset($attr['WIDTH'])) { switch(strtoupper($attr['WIDTH'])) { case 'THIN': $this->outlineparam['WIDTH'] = 0.75*$this->LineWidth; break; case 'MEDIUM': $this->outlineparam['WIDTH'] = $this->LineWidth; break; case 'THICK': $this->outlineparam['WIDTH'] = 1.75*$this->LineWidth; break; } } else $this->outlineparam['WIDTH'] = $this->LineWidth; //width == oldwidth break; case 'BDO': if (isset($attr['DIR']) and (strtoupper($attr['DIR']) == 'RTL' )) $this->divrevert = true; break; case 'S': case 'STRIKE': case 'DEL': $this->strike=true; break; case 'SUB': $this->SUB=true; break; case 'SUP': $this->SUP=true; break; case 'CENTER': $this->buffer_on = true; if ($this->tdbegin) $this->cell[$this->row][$this->col]['a'] = $align['center']; else { $this->divalign = $align['center']; if ($this->x != $this->lMargin) $this->Ln($this->lineheight); } break; case 'ADDRESS': $this->buffer_on = true; $this->SetStyle('I',true); if (!$this->tdbegin and $this->x != $this->lMargin) $this->Ln($this->lineheight); break; case 'TABLE': // TABLE-BEGIN if ($this->x != $this->lMargin) $this->Ln($this->lineheight); $this->tablestart = true; $this->table['nc'] = $this->table['nr'] = 0; if (isset($attr['REPEAT_HEADER']) and $attr['REPEAT_HEADER'] == true) $this->UseTableHeader(true); if (isset($attr['WIDTH'])) $this->table['w'] = ConvertSize($attr['WIDTH'],$this->pgwidth); if (isset($attr['HEIGHT'])) $this->table['h'] = ConvertSize($attr['HEIGHT'],$this->pgwidth); if (isset($attr['ALIGN'])) $this->table['a'] = $align[strtolower($attr['ALIGN'])]; if (isset($attr['BORDER'])) $this->table['border'] = $attr['BORDER']; if (isset($attr['BGCOLOR'])) $this->table['bgcolor'][-1] = $attr['BGCOLOR']; break; case 'TR': $this->row++; $this->table['nr']++; $this->col = -1; if (isset($attr['BGCOLOR']))$this->table['bgcolor'][$this->row] = $attr['BGCOLOR']; break; case 'TH': $this->SetStyle('B',true); if (!isset($attr['ALIGN'])) $attr['ALIGN'] = "center"; case 'TD': $this->tdbegin = true; $this->col++; while (isset($this->cell[$this->row][$this->col])) $this->col++; //Update number column if ($this->table['nc'] < $this->col+1) $this->table['nc'] = $this->col+1; $this->cell[$this->row][$this->col] = array(); $this->cell[$this->row][$this->col]['text'] = array(); $this->cell[$this->row][$this->col]['s'] = 3; if (isset($attr['WIDTH'])) $this->cell[$this->row][$this->col]['w'] = ConvertSize($attr['WIDTH'],$this->pgwidth); if (isset($attr['HEIGHT'])) $this->cell[$this->row][$this->col]['h'] = ConvertSize($attr['HEIGHT'],$this->pgwidth); if (isset($attr['ALIGN'])) $this->cell[$this->row][$this->col]['a'] = $align[strtolower($attr['ALIGN'])]; if (isset($attr['VALIGN'])) $this->cell[$this->row][$this->col]['va'] = $align[strtolower($attr['VALIGN'])]; if (isset($attr['BORDER'])) $this->cell[$this->row][$this->col]['border'] = $attr['BORDER']; if (isset($attr['BGCOLOR'])) $this->cell[$this->row][$this->col]['bgcolor'] = $attr['BGCOLOR']; $cs = $rs = 1; if (isset($attr['COLSPAN']) && $attr['COLSPAN']>1) $cs = $this->cell[$this->row][$this->col]['colspan'] = $attr['COLSPAN']; if (isset($attr['ROWSPAN']) && $attr['ROWSPAN']>1) $rs = $this->cell[$this->row][$this->col]['rowspan'] = $attr['ROWSPAN']; //Chiem dung vi tri de danh cho cell span (?mais hein?) for ($k=$this->row ; $k < $this->row+$rs ;$k++) for($l=$this->col; $l < $this->col+$cs ;$l++) { if ($k-$this->row || $l-$this->col) $this->cell[$k][$l] = 0; } if (isset($attr['NOWRAP'])) $this->cell[$this->row][$this->col]['nowrap']= 1; break; case 'OL': if ( !isset($attr['TYPE']) or $attr['TYPE'] == '' ) $this->listtype = '1'; //OL default == '1' else $this->listtype = $attr['TYPE']; // ol and ul types are mixed here case 'UL': if ( (!isset($attr['TYPE']) or $attr['TYPE'] == '') and $tag=='UL') { //Insert UL defaults if ($this->listlvl == 0) $this->listtype = 'disc'; elseif ($this->listlvl == 1) $this->listtype = 'circle'; else $this->listtype = 'square'; } elseif (isset($attr['TYPE']) and $tag=='UL') $this->listtype = $attr['TYPE']; $this->buffer_on = false; if ($this->listlvl == 0) { //First of all, skip a line if (!$this->pjustfinished) { if ($this->x != $this->lMargin) $this->Ln($this->lineheight); $this->Ln($this->lineheight); } $this->oldx = $this->x; $this->listlvl++; // first depth level $this->listnum = 0; // reset $this->listoccur[$this->listlvl] = 1; $this->listlist[$this->listlvl][1] = array('TYPE'=>$this->listtype,'MAXNUM'=>$this->listnum); } else { if (!empty($this->textbuffer)) { $this->listitem[] = array($this->listlvl,$this->listnum,$this->textbuffer,$this->listoccur[$this->listlvl]); $this->listnum++; } $this->textbuffer = array(); $occur = $this->listoccur[$this->listlvl]; $this->listlist[$this->listlvl][$occur]['MAXNUM'] = $this->listnum; //save previous lvl's maxnum $this->listlvl++; $this->listnum = 0; // reset if ($this->listoccur[$this->listlvl] == 0) $this->listoccur[$this->listlvl] = 1; else $this->listoccur[$this->listlvl]++; $occur = $this->listoccur[$this->listlvl]; $this->listlist[$this->listlvl][$occur] = array('TYPE'=>$this->listtype,'MAXNUM'=>$this->listnum); } break; case 'LI': //Observation: is ignored if ($this->listlvl == 0) //in case of malformed HTML code. Example:(...)

  • Content
  • Paragraph1

    (...) { //First of all, skip a line if (!$this->pjustfinished and $this->x != $this->lMargin) $this->Ln(2*$this->lineheight); $this->oldx = $this->x; $this->listlvl++; // first depth level $this->listnum = 0; // reset $this->listoccur[$this->listlvl] = 1; $this->listlist[$this->listlvl][1] = array('TYPE'=>'disc','MAXNUM'=>$this->listnum); } if ($this->listnum == 0) { $this->buffer_on = true; //activate list 'bufferization' $this->listnum++; $this->textbuffer = array(); } else { $this->buffer_on = true; //activate list 'bufferization' if (!empty($this->textbuffer)) { $this->listitem[] = array($this->listlvl,$this->listnum,$this->textbuffer,$this->listoccur[$this->listlvl]); $this->listnum++; } $this->textbuffer = array(); } break; case 'H1': // 2 * fontsize case 'H2': // 1.5 * fontsize case 'H3': // 1.17 * fontsize case 'H4': // 1 * fontsize case 'H5': // 0.83 * fontsize case 'H6': // 0.67 * fontsize //Values obtained from: http://www.w3.org/TR/REC-CSS2/sample.html if(isset($attr['ALIGN'])) $this->divalign = $align[strtolower($attr['ALIGN'])]; $this->buffer_on = true; if ($this->x != $this->lMargin) $this->Ln(2*$this->lineheight); elseif (!$this->pjustfinished) $this->Ln($this->lineheight); $this->SetStyle('B',true); switch($tag) { case 'H1': $this->SetFontSize(2*$this->FontSizePt); $this->lineheight *= 2; break; case 'H2': $this->SetFontSize(1.5*$this->FontSizePt); $this->lineheight *= 1.5; break; case 'H3': $this->SetFontSize(1.17*$this->FontSizePt); $this->lineheight *= 1.17; break; case 'H4': $this->SetFontSize($this->FontSizePt); break; case 'H5': $this->SetFontSize(0.83*$this->FontSizePt); $this->lineheight *= 0.83; break; case 'H6': $this->SetFontSize(0.67*$this->FontSizePt); $this->lineheight *= 0.67; break; } break; case 'HR': //Default values: width=100% align=center color=gray //Skip a line, if needed if ($this->x != $this->lMargin) $this->Ln($this->lineheight); $this->Ln(0.2*$this->lineheight); $hrwidth = $this->pgwidth; $hralign = 'C'; $hrcolor = array('R'=>200,'G'=>200,'B'=>200); if($attr['WIDTH'] != '') $hrwidth = ConvertSize($attr['WIDTH'],$this->pgwidth); if($attr['ALIGN'] != '') $hralign = $align[strtolower($attr['ALIGN'])]; if($attr['COLOR'] != '') $hrcolor = ConvertColor($attr['COLOR']); $this->SetDrawColor($hrcolor['R'],$hrcolor['G'],$hrcolor['B']); $x = $this->x; $y = $this->y; switch($hralign) { case 'L': case 'J': break; case 'C': $empty = $this->pgwidth - $hrwidth; $empty /= 2; $x += $empty; break; case 'R': $empty = $this->pgwidth - $hrwidth; $x += $empty; break; } $oldlinewidth = $this->LineWidth; $this->SetLineWidth(0.3); $this->Line($x,$y,$x+$hrwidth,$y); $this->SetLineWidth($oldlinewidth); $this->Ln(0.2*$this->lineheight); $this->SetDrawColor(0); $this->blockjustfinished = true; //Eliminate exceeding left-side spaces break; case 'INS': $this->SetStyle('U',true); break; case 'SMALL': $newsize = $this->FontSizePt - 1; $this->SetFontSize($newsize); break; case 'BIG': $newsize = $this->FontSizePt + 1; $this->SetFontSize($newsize); case 'STRONG': $this->SetStyle('B',true); break; case 'CITE': case 'EM': $this->SetStyle('I',true); break; case 'TITLE': $this->titulo = true; break; case 'B': case 'I': case 'U': if( isset($attr['CLASS']) or isset($attr['ID']) or isset($attr['STYLE']) ) { $this->cssbegin=true; if (isset($attr['CLASS'])) $properties = $this->CSS[$attr['CLASS']]; elseif (isset($attr['ID'])) $properties = $this->CSS[$attr['ID']]; //Read Inline CSS if (isset($attr['STYLE'])) $properties = $this->readInlineCSS($attr['STYLE']); //Look for name in the $this->CSS array $this->backupcss = $properties; if (!empty($properties)) $this->setCSS($properties); //name found in the CSS array! } $this->SetStyle($tag,true); break; case 'A': if (isset($attr['NAME']) and $attr['NAME'] != '') $this->textbuffer[] = array('','','',array(),'',false,false,$attr['NAME']); //an internal link (adds a space for recognition) if (isset($attr['HREF'])) $this->HREF=$attr['HREF']; break; case 'DIV': //in case of malformed HTML code. Example:(...)
  • Content
  • DIV1
    (...) if ($this->listlvl > 0) // We are closing (omitted) OL/UL tag(s) { $this->buffer_on = false; if (!empty($this->textbuffer)) $this->listitem[] = array($this->listlvl,$this->listnum,$this->textbuffer,$this->listoccur[$this->listlvl]); $this->textbuffer = array(); $this->listlvl--; $this->printlistbuffer(); $this->pjustfinished = true; //act as if a paragraph just ended } $this->divbegin=true; if ($this->x != $this->lMargin) $this->Ln($this->lineheight); if( isset($attr['ALIGN']) and $attr['ALIGN'] != '' ) $this->divalign = $align[strtolower($attr['ALIGN'])]; if( isset($attr['CLASS']) or isset($attr['ID']) or isset($attr['STYLE']) ) { $this->cssbegin=true; if (isset($attr['CLASS'])) $properties = $this->CSS[$attr['CLASS']]; elseif (isset($attr['ID'])) $properties = $this->CSS[$attr['ID']]; //Read Inline CSS if (isset($attr['STYLE'])) $properties = $this->readInlineCSS($attr['STYLE']); //Look for name in the $this->CSS array if (!empty($properties)) $this->setCSS($properties); //name found in the CSS array! } break; case 'IMG': if(!empty($this->textbuffer) and !$this->tablestart) { //Output previously buffered content and output image below //Set some default values $olddivwidth = $this->divwidth; $olddivheight = $this->divheight; if ( $this->divwidth == 0) $this->divwidth = $this->pgwidth - $x + $this->lMargin; if ( $this->divheight == 0) $this->divheight = $this->lineheight; //Print content $this->printbuffer($this->textbuffer,true/*is out of a block (e.g. DIV,P etc.)*/); $this->textbuffer=array(); //Reset values $this->divwidth = $olddivwidth; $this->divheight = $olddivheight; $this->textbuffer=array(); $this->Ln($this->lineheight); } if(isset($attr['SRC'])) { $srcpath = $attr['SRC']; $srcpath = str_replace ("resized%2F", "", $srcpath); if(!isset($attr['WIDTH'])) $attr['WIDTH'] = 0; else $attr['WIDTH'] = ConvertSize($attr['WIDTH'],$this->pgwidth);//$attr['WIDTH'] /= 4; if(!isset($attr['HEIGHT'])) $attr['HEIGHT'] = 0; else $attr['HEIGHT'] = ConvertSize($attr['HEIGHT'],$this->pgwidth);//$attr['HEIGHT'] /= 4; if ($this->tdbegin) { $bak_x = $this->x; $bak_y = $this->y; //Check whether image exists locally or on the URL $f_exists = @fopen($srcpath,"rb"); if (!$f_exists) //Show 'image not found' icon instead { if(!$this->shownoimg) break; $srcpath = str_replace("\\","/",dirname(__FILE__)) . "/"; $srcpath .= 'no_img.gif'; } $sizesarray = $this->Image($srcpath, $this->GetX(), $this->GetY(), $attr['WIDTH'], $attr['HEIGHT'],'','',false); $this->y = $bak_y; $this->x = $bak_x; } elseif($this->pbegin or $this->divbegin) { //In order to support
    $ypos = 0; $bak_x = $this->x; $bak_y = $this->y; //Check whether image exists locally or on the URL $f_exists = @fopen($srcpath,"rb"); if (!$f_exists) //Show 'image not found' icon instead { if(!$this->shownoimg) break; $srcpath = str_replace("\\","/",dirname(__FILE__)) . "/"; $srcpath .= 'no_img.gif'; } $sizesarray = $this->Image($srcpath, $this->GetX(), $this->GetY(), $attr['WIDTH'], $attr['HEIGHT'],'','',false); $this->y = $bak_y; $this->x = $bak_x; $xpos = ''; switch($this->divalign) { case "C": $spacesize = $this->CurrentFont[ 'cw' ][ ' ' ] * ( $this->FontSizePt / 1000 ); $empty = ($this->pgwidth - $sizesarray['WIDTH'])/2; $xpos = 'xpos='.$empty.','; break; case "R": $spacesize = $this->CurrentFont[ 'cw' ][ ' ' ] * ( $this->FontSizePt / 1000 ); $empty = ($this->pgwidth - $sizesarray['WIDTH']); $xpos = 'xpos='.$empty.','; break; default: break; } $numberoflines = (integer)ceil($sizesarray['HEIGHT']/$this->lineheight) ; $ypos = $numberoflines * $this->lineheight; $this->textbuffer[] = array("???"/*identifier*/."type=image,ypos=$ypos,{$xpos}width=".$sizesarray['WIDTH'].",height=".$sizesarray['HEIGHT']."???".$sizesarray['OUTPUT']); while($numberoflines) {$this->textbuffer[] = array("\n",$this->HREF,$this->currentstyle,$this->colorarray,$this->currentfont,$this->SUP,$this->SUB,''/*internal link*/,$this->strike,$this->outlineparam,$this->bgcolorarray);$numberoflines--;} } else { $imgborder = 0; if (isset($attr['BORDER'])) $imgborder = ConvertSize($attr['BORDER'],$this->pgwidth); //Check whether image exists locally or on the URL $f_exists = @fopen($srcpath,"rb"); if (!$f_exists) //Show 'image not found' icon instead { $srcpath = str_replace("\\","/",dirname(__FILE__)) . "/"; $srcpath .= 'no_img.gif'; } $sizesarray = $this->Image($srcpath, $this->GetX(), $this->GetY(), $attr['WIDTH'], $attr['HEIGHT'],'',$this->HREF); //Output Image $ini_x = $sizesarray['X']; $ini_y = $sizesarray['Y']; if ($imgborder) { $oldlinewidth = $this->LineWidth; $this->SetLineWidth($imgborder); $this->Rect($ini_x,$ini_y,$sizesarray['WIDTH'],$sizesarray['HEIGHT']); $this->SetLineWidth($oldlinewidth); } } if ($sizesarray['X'] < $this->x) $this->x = $this->lMargin; if ($this->tablestart) { $this->cell[$this->row][$this->col]['textbuffer'][] = array("???"/*identifier*/."type=image,width=".$sizesarray['WIDTH'].",height=".$sizesarray['HEIGHT']."???".$sizesarray['OUTPUT']); $this->cell[$this->row][$this->col]['s'] += $sizesarray['WIDTH'] + 1;// +1 == margin $this->cell[$this->row][$this->col]['form'] = true; // in order to make some width adjustments later if (!isset($this->cell[$this->row][$this->col]['w'])) $this->cell[$this->row][$this->col]['w'] = $sizesarray['WIDTH'] + 3; if (!isset($this->cell[$this->row][$this->col]['h'])) $this->cell[$this->row][$this->col]['h'] = $sizesarray['HEIGHT'] + 3; } } break; case 'BLOCKQUOTE': case 'BR': if($this->tablestart) { $this->cell[$this->row][$this->col]['textbuffer'][] = array("\n",$this->HREF,$this->currentstyle,$this->colorarray,$this->currentfont,$this->SUP,$this->SUB,''/*internal link*/,$this->strike,$this->outlineparam,$this->bgcolorarray); $this->cell[$this->row][$this->col]['text'][] = "\n"; if (!isset($this->cell[$this->row][$this->col]['maxs'])) $this->cell[$this->row][$this->col]['maxs'] = $this->cell[$this->row][$this->col]['s'] +2; //+2 == margin elseif($this->cell[$this->row][$this->col]['maxs'] < $this->cell[$this->row][$this->col]['s']) $this->cell[$this->row][$this->col]['maxs'] = $this->cell[$this->row][$this->col]['s']+2;//+2 == margin $this->cell[$this->row][$this->col]['s'] = 0;// reset } elseif($this->divbegin or $this->pbegin or $this->buffer_on) $this->textbuffer[] = array("\n",$this->HREF,$this->currentstyle,$this->colorarray,$this->currentfont,$this->SUP,$this->SUB,''/*internal link*/,$this->strike,$this->outlineparam,$this->bgcolorarray); else {$this->Ln($this->lineheight);$this->blockjustfinished = true;} break; case 'P': //in case of malformed HTML code. Example:(...)

  • Content
  • Paragraph1

    (...) if ($this->listlvl > 0) // We are closing (omitted) OL/UL tag(s) { $this->buffer_on = false; if (!empty($this->textbuffer)) $this->listitem[] = array($this->listlvl,$this->listnum,$this->textbuffer,$this->listoccur[$this->listlvl]); $this->textbuffer = array(); $this->listlvl--; $this->printlistbuffer(); $this->pjustfinished = true; //act as if a paragraph just ended } if ($this->tablestart) { $this->cell[$this->row][$this->col]['textbuffer'][] = array($e,$this->HREF,$this->currentstyle,$this->colorarray,$this->currentfont,$this->SUP,$this->SUB,''/*internal link*/,$this->strike,$this->outlineparam,$this->bgcolorarray); $this->cell[$this->row][$this->col]['text'][] = "\n"; break; } $this->pbegin=true; if ($this->x != $this->lMargin) $this->Ln(2*$this->lineheight); elseif (!$this->pjustfinished) $this->Ln($this->lineheight); //Save x,y coords in case we need to print borders... $this->oldx = $this->x; $this->oldy = $this->y; if(isset($attr['ALIGN'])) $this->divalign = $align[strtolower($attr['ALIGN'])]; if(isset($attr['CLASS']) or isset($attr['ID']) or isset($attr['STYLE']) ) { $this->cssbegin=true; if (isset($attr['CLASS'])) $properties = $this->CSS[$attr['CLASS']]; elseif (isset($attr['ID'])) $properties = $this->CSS[$attr['ID']]; //Read Inline CSS if (isset($attr['STYLE'])) $properties = $this->readInlineCSS($attr['STYLE']); //Look for name in the $this->CSS array $this->backupcss = $properties; if (!empty($properties)) $this->setCSS($properties); //name(id/class/style) found in the CSS array! } break; case 'SPAN': $this->buffer_on = true; //Save x,y coords in case we need to print borders... $this->oldx = $this->x; $this->oldy = $this->y; if( isset($attr['CLASS']) or isset($attr['ID']) or isset($attr['STYLE']) ) { $this->cssbegin=true; if (isset($attr['CLASS'])) $properties = $this->CSS[$attr['CLASS']]; elseif (isset($attr['ID'])) $properties = $this->CSS[$attr['ID']]; //Read Inline CSS if (isset($attr['STYLE'])) $properties = $this->readInlineCSS($attr['STYLE']); //Look for name in the $this->CSS array $this->backupcss = $properties; if (!empty($properties)) $this->setCSS($properties); //name found in the CSS array! } break; case 'PRE': if($this->tablestart) { $this->cell[$this->row][$this->col]['textbuffer'][] = array("\n",$this->HREF,$this->currentstyle,$this->colorarray,$this->currentfont,$this->SUP,$this->SUB,''/*internal link*/,$this->strike,$this->outlineparam,$this->bgcolorarray); $this->cell[$this->row][$this->col]['text'][] = "\n"; } elseif($this->divbegin or $this->pbegin or $this->buffer_on) $this->textbuffer[] = array("\n",$this->HREF,$this->currentstyle,$this->colorarray,$this->currentfont,$this->SUP,$this->SUB,''/*internal link*/,$this->strike,$this->outlineparam,$this->bgcolorarray); else { if ($this->x != $this->lMargin) $this->Ln(2*$this->lineheight); elseif (!$this->pjustfinished) $this->Ln($this->lineheight); $this->buffer_on = true; //Save x,y coords in case we need to print borders... $this->oldx = $this->x; $this->oldy = $this->y; if(isset($attr['ALIGN'])) $this->divalign = $align[strtolower($attr['ALIGN'])]; if(isset($attr['CLASS']) or isset($attr['ID']) or isset($attr['STYLE']) ) { $this->cssbegin=true; if (isset($attr['CLASS'])) $properties = $this->CSS[$attr['CLASS']]; elseif (isset($attr['ID'])) $properties = $this->CSS[$attr['ID']]; //Read Inline CSS if (isset($attr['STYLE'])) $properties = $this->readInlineCSS($attr['STYLE']); //Look for name in the $this->CSS array $this->backupcss = $properties; if (!empty($properties)) $this->setCSS($properties); //name(id/class/style) found in the CSS array! } } case 'TT': case 'KBD': case 'SAMP': case 'CODE': $this->SetFont('courier'); $this->currentfont='courier'; break; case 'TEXTAREA': $this->buffer_on = true; $colsize = 20; //HTML default value $rowsize = 2; //HTML default value if (isset($attr['COLS'])) $colsize = $attr['COLS']; if (isset($attr['ROWS'])) $rowsize = $attr['ROWS']; if (!$this->tablestart) { if ($this->x != $this->lMargin) $this->Ln($this->lineheight); $this->col = $colsize; $this->row = $rowsize; } else //it is inside a table { $this->specialcontent = "type=textarea,lines=$rowsize,width=".((2.2*$colsize) + 3); //Activate form info in order to paint FORM elements within table $this->cell[$this->row][$this->col]['s'] += (2.2*$colsize) + 6;// +6 == margin if (!isset($this->cell[$this->row][$this->col]['h'])) $this->cell[$this->row][$this->col]['h'] = 1.1*$this->lineheight*$rowsize + 2.5; } break; case 'SELECT': $this->specialcontent = "type=select"; //Activate form info in order to paint FORM elements within table break; case 'OPTION': $this->selectoption['ACTIVE'] = true; if (empty($this->selectoption)) { $this->selectoption['MAXWIDTH'] = ''; $this->selectoption['SELECTED'] = ''; } if (isset($attr['SELECTED'])) $this->selectoption['SELECTED'] = ''; break; case 'FORM': if($this->tablestart) { $this->cell[$this->row][$this->col]['textbuffer'][] = array($e,$this->HREF,$this->currentstyle,$this->colorarray,$this->currentfont,$this->SUP,$this->SUB,''/*internal link*/,$this->strike,$this->outlineparam,$this->bgcolorarray); $this->cell[$this->row][$this->col]['text'][] = "\n"; } elseif ($this->x != $this->lMargin) $this->Ln($this->lineheight); //Skip a line, if needed break; case 'INPUT': if (!isset($attr['TYPE'])) $attr['TYPE'] == ''; //in order to allow default 'TEXT' form (in case of malformed HTML code) if (!$this->tablestart) { switch(strtoupper($attr['TYPE'])){ case 'CHECKBOX': //Draw Checkbox $checked = false; if (isset($attr['CHECKED'])) $checked = true; $this->SetFillColor(235,235,235); $this->x += 3; $this->Rect($this->x,$this->y+1,3,3,'DF'); if ($checked) { $this->Line($this->x,$this->y+1,$this->x+3,$this->y+1+3); $this->Line($this->x,$this->y+1+3,$this->x+3,$this->y+1); } $this->SetFillColor(255); $this->x += 3.5; break; case 'RADIO': //Draw Radio button $checked = false; if (isset($attr['CHECKED'])) $checked = true; $this->x += 4; $this->Circle($this->x,$this->y+2.2,1,'D'); $this->_out('0.000 g'); if ($checked) $this->Circle($this->x,$this->y+2.2,0.4,'DF'); $this->Write(5,$texto,$this->x); $this->x += 2; break; case 'BUTTON': // Draw a button case 'SUBMIT': case 'RESET': $texto=''; if (isset($attr['VALUE'])) $texto = $attr['VALUE']; $nihil = 2.5; $this->x += 2; $this->SetFillColor(190,190,190); $this->Rect($this->x,$this->y,$this->GetStringWidth($texto)+2*$nihil,4.5,'DF'); // 4.5 in order to avoid overlapping $this->x += $nihil; $this->Write(5,$texto,$this->x); $this->x += $nihil; $this->SetFillColor(255); break; case 'PASSWORD': if (isset($attr['VALUE'])) { $num_stars = strlen($attr['VALUE']); $attr['VALUE'] = str_repeat('*',$num_stars); } case 'TEXT': //Draw TextField default: //default == TEXT $texto=''; if (isset($attr['VALUE'])) $texto = $attr['VALUE']; $tamanho = 20; if (isset($attr['SIZE']) and ctype_digit($attr['SIZE']) ) $tamanho = $attr['SIZE']; $this->SetFillColor(235,235,235); $this->x += 2; $this->Rect($this->x,$this->y,2*$tamanho,4.5,'DF');// 4.5 in order to avoid overlapping if ($texto != '') { $this->x += 1; $this->Write(5,$texto,$this->x); $this->x -= $this->GetStringWidth($texto); } $this->SetFillColor(255); $this->x += 2*$tamanho; break; } } else //we are inside a table { $this->cell[$this->row][$this->col]['form'] = true; // in order to make some width adjustments later $type = ''; $text = ''; $height = 0; $width = 0; switch(strtoupper($attr['TYPE'])){ case 'CHECKBOX': //Draw Checkbox $checked = false; if (isset($attr['CHECKED'])) $checked = true; $text = $checked; $type = 'CHECKBOX'; $width = 4; $this->cell[$this->row][$this->col]['textbuffer'][] = array("???"/*identifier*/."type=input,subtype=$type,width=$width,height=$height"."???".$text); $this->cell[$this->row][$this->col]['s'] += $width; if (!isset($this->cell[$this->row][$this->col]['h'])) $this->cell[$this->row][$this->col]['h'] = $this->lineheight; break; case 'RADIO': //Draw Radio button $checked = false; if (isset($attr['CHECKED'])) $checked = true; $text = $checked; $type = 'RADIO'; $width = 3; $this->cell[$this->row][$this->col]['textbuffer'][] = array("???"/*identifier*/."type=input,subtype=$type,width=$width,height=$height"."???".$text); $this->cell[$this->row][$this->col]['s'] += $width; if (!isset($this->cell[$this->row][$this->col]['h'])) $this->cell[$this->row][$this->col]['h'] = $this->lineheight; break; case 'BUTTON': $type = 'BUTTON'; // Draw a button case 'SUBMIT': if ($type == '') $type = 'SUBMIT'; case 'RESET': if ($type == '') $type = 'RESET'; $texto=''; if (isset($attr['VALUE'])) $texto = " " . $attr['VALUE'] . " "; $text = $texto; $width = $this->GetStringWidth($texto)+3; $this->cell[$this->row][$this->col]['textbuffer'][] = array("???"/*identifier*/."type=input,subtype=$type,width=$width,height=$height"."???".$text); $this->cell[$this->row][$this->col]['s'] += $width; if (!isset($this->cell[$this->row][$this->col]['h'])) $this->cell[$this->row][$this->col]['h'] = $this->lineheight + 2; break; case 'PASSWORD': if (isset($attr['VALUE'])) { $num_stars = strlen($attr['VALUE']); $attr['VALUE'] = str_repeat('*',$num_stars); } $type = 'PASSWORD'; case 'TEXT': //Draw TextField default: //default == TEXT $texto=''; if (isset($attr['VALUE'])) $texto = $attr['VALUE']; $tamanho = 20; if (isset($attr['SIZE']) and ctype_digit($attr['SIZE']) ) $tamanho = $attr['SIZE']; $text = $texto; $width = 2*$tamanho; if ($type == '') $type = 'TEXT'; $this->cell[$this->row][$this->col]['textbuffer'][] = array("???"/*identifier*/."type=input,subtype=$type,width=$width,height=$height"."???".$text); $this->cell[$this->row][$this->col]['s'] += $width; if (!isset($this->cell[$this->row][$this->col]['h'])) $this->cell[$this->row][$this->col]['h'] = $this->lineheight + 2; break; } } break; case 'FONT': //Font size is ignored for now if (isset($attr['COLOR']) and $attr['COLOR']!='') { $cor = ConvertColor($attr['COLOR']); //If something goes wrong switch color to black $cor['R'] = (isset($cor['R'])?$cor['R']:0); $cor['G'] = (isset($cor['G'])?$cor['G']:0); $cor['B'] = (isset($cor['B'])?$cor['B']:0); $this->colorarray = $cor; $this->SetTextColor($cor['R'],$cor['G'],$cor['B']); $this->issetcolor = true; } if (isset($attr['FACE']) and in_array(strtolower($attr['FACE']), $this->fontlist)) { $this->SetFont(strtolower($attr['FACE'])); $this->issetfont=true; } //'If' disabled in this version due lack of testing (you may enable it if you want) // if (isset($attr['FACE']) and in_array(strtolower($attr['FACE']), $this->fontlist) and isset($attr['SIZE']) and $attr['SIZE']!='') { // $this->SetFont(strtolower($attr['FACE']),'',$attr['SIZE']); // $this->issetfont=true; // } break; }//end of switch $this->pjustfinished=false; } function CloseTag($tag) { //! @return void //Closing tag if($tag=='OPTION') $this->selectoption['ACTIVE'] = false; if($tag=='BDO') $this->divrevert = false; if($tag=='INS') $tag='U'; if($tag=='STRONG') $tag='B'; if($tag=='EM' or $tag=='CITE') $tag='I'; if($tag=='OUTLINE') { if(!$this->pbegin and !$this->divbegin and !$this->tablestart) { //Deactivate $this->outlineparam for its info is already stored inside $this->textbuffer //if (isset($this->outlineparam['OLDWIDTH'])) $this->SetTextOutline($this->outlineparam['OLDWIDTH']); $this->SetTextOutline(false); $this->outlineparam=array(); //Save x,y coords ??? $x = $this->x; $y = $this->y; //Set some default values $this->divwidth = $this->pgwidth - $x + $this->lMargin; //Print content $this->printbuffer($this->textbuffer,true/*is out of a block (e.g. DIV,P etc.)*/); $this->textbuffer=array(); //Reset values $this->Reset(); $this->buffer_on=false; } $this->SetTextOutline(false); $this->outlineparam=array(); } if($tag=='A') { if(!$this->pbegin and !$this->divbegin and !$this->tablestart and !$this->buffer_on) { //Deactivate $this->HREF for its info is already stored inside $this->textbuffer $this->HREF=''; //Save x,y coords ??? $x = $this->x; $y = $this->y; //Set some default values $this->divwidth = $this->pgwidth - $x + $this->lMargin; //Print content $this->printbuffer($this->textbuffer,true/*is out of a block (e.g. DIV,P etc.)*/); $this->textbuffer=array(); //Reset values $this->Reset(); } $this->HREF=''; } if($tag=='TH') $this->SetStyle('B',false); if($tag=='TH' or $tag=='TD') $this->tdbegin = false; if($tag=='SPAN') { if(!$this->pbegin and !$this->divbegin and !$this->tablestart) { if($this->cssbegin) { //Check if we have borders to print if ($this->cssbegin and ($this->divborder or $this->dash_on or $this->dotted_on or $this->divbgcolor)) { $texto=''; foreach($this->textbuffer as $vetor) $texto.=$vetor[0]; $tempx = $this->x; if($this->divbgcolor) $this->Cell($this->GetStringWidth($texto),$this->lineheight,'',$this->divborder,'','L',$this->divbgcolor); if ($this->dash_on) $this->Rect($this->oldx,$this->oldy,$this->GetStringWidth($texto),$this->lineheight); if ($this->dotted_on) $this->DottedRect($this->x - $this->GetStringWidth($texto),$this->y,$this->GetStringWidth($texto),$this->lineheight); $this->x = $tempx; $this->x -= 1; //adjust alignment } $this->cssbegin=false; $this->backupcss=array(); } //Save x,y coords ??? $x = $this->x; $y = $this->y; //Set some default values $this->divwidth = $this->pgwidth - $x + $this->lMargin; //Print content $this->printbuffer($this->textbuffer,true/*is out of a block (e.g. DIV,P etc.)*/); $this->textbuffer=array(); //Reset values $this->Reset(); } $this->buffer_on=false; } if($tag=='P' or $tag=='DIV') //CSS in BLOCK mode { $this->blockjustfinished = true; //Eliminate exceeding left-side spaces if(!$this->tablestart) { if ($this->divwidth == 0) $this->divwidth = $this->pgwidth; if ($tag=='P') { $this->pbegin=false; $this->pjustfinished=true; } else $this->divbegin=false; $content=''; foreach($this->textbuffer as $aux) $content .= $aux[0]; $numlines = $this->WordWrap($content,$this->divwidth); if ($this->divheight == 0) $this->divheight = $numlines * 5; //Print content $this->printbuffer($this->textbuffer); $this->textbuffer=array(); if ($tag=='P') $this->Ln($this->lineheight); }//end of 'if (!this->tablestart)' //Reset values $this->Reset(); $this->cssbegin=false; $this->backupcss=array(); } if($tag=='TABLE') { // TABLE-END $this->blockjustfinished = true; //Eliminate exceeding left-side spaces $this->table['cells'] = $this->cell; $this->table['wc'] = array_pad(array(),$this->table['nc'],array('miw'=>0,'maw'=>0)); $this->table['hr'] = array_pad(array(),$this->table['nr'],0); $this->_tableColumnWidth($this->table); $this->_tableWidth($this->table); $this->_tableHeight($this->table); //Output table on PDF $this->_tableWrite($this->table); //Reset values $this->tablestart=false; //bool $this->table=array(); //array $this->cell=array(); //array $this->col=-1; //int $this->row=-1; //int $this->Reset(); $this->Ln(0.5*$this->lineheight); } if(($tag=='UL') or ($tag=='OL')) { if ($this->buffer_on == false) $this->listnum--;//Adjust minor BUG (this happens when there are two together) if ($this->listlvl == 1) // We are closing the last OL/UL tag { $this->blockjustfinished = true; //Eliminate exceeding left-side spaces $this->buffer_on = false; if (!empty($this->textbuffer)) $this->listitem[] = array($this->listlvl,$this->listnum,$this->textbuffer,$this->listoccur[$this->listlvl]); $this->textbuffer = array(); $this->listlvl--; $this->printlistbuffer(); } else // returning one level { if (!empty($this->textbuffer)) $this->listitem[] = array($this->listlvl,$this->listnum,$this->textbuffer,$this->listoccur[$this->listlvl]); $this->textbuffer = array(); $occur = $this->listoccur[$this->listlvl]; $this->listlist[$this->listlvl][$occur]['MAXNUM'] = $this->listnum; //save previous lvl's maxnum $this->listlvl--; $occur = $this->listoccur[$this->listlvl]; $this->listnum = $this->listlist[$this->listlvl][$occur]['MAXNUM']; // recover previous level's number $this->listtype = $this->listlist[$this->listlvl][$occur]['TYPE']; // recover previous level's type $this->buffer_on = false; } } if($tag=='H1' or $tag=='H2' or $tag=='H3' or $tag=='H4' or $tag=='H5' or $tag=='H6') { $this->blockjustfinished = true; //Eliminate exceeding left-side spaces if(!$this->pbegin and !$this->divbegin and !$this->tablestart) { //These 2 codelines are useless? $texto=''; foreach($this->textbuffer as $vetor) $texto.=$vetor[0]; //Save x,y coords ??? $x = $this->x; $y = $this->y; //Set some default values $this->divwidth = $this->pgwidth; //Print content $this->printbuffer($this->textbuffer); $this->textbuffer=array(); if ($this->x != $this->lMargin) $this->Ln($this->lineheight); //Reset values $this->Reset(); } $this->buffer_on=false; $this->lineheight = 5; $this->Ln($this->lineheight); $this->SetFontSize(11); $this->SetStyle('B',false); } if($tag=='TITLE') {$this->titulo=false; $this->blockjustfinished = true;} if($tag=='FORM') $this->Ln($this->lineheight); if($tag=='PRE') { if(!$this->pbegin and !$this->divbegin and !$this->tablestart) { if ($this->divwidth == 0) $this->divwidth = $this->pgwidth; $content=''; foreach($this->textbuffer as $aux) $content .= $aux[0]; $numlines = $this->WordWrap($content,$this->divwidth); if ($this->divheight == 0) $this->divheight = $numlines * 5; //Print content $this->textbuffer[0][0] = ltrim($this->textbuffer[0][0]); //Remove exceeding left-side space $this->printbuffer($this->textbuffer); $this->textbuffer=array(); if ($this->x != $this->lMargin) $this->Ln($this->lineheight); //Reset values $this->Reset(); $this->Ln(1.1*$this->lineheight); } if($this->tablestart) { $this->cell[$this->row][$this->col]['textbuffer'][] = array("\n",$this->HREF,$this->currentstyle,$this->colorarray,$this->currentfont,$this->SUP,$this->SUB,''/*internal link*/,$this->strike,$this->outlineparam,$this->bgcolorarray); $this->cell[$this->row][$this->col]['text'][] = "\n"; } if($this->divbegin or $this->pbegin or $this->buffer_on) $this->textbuffer[] = array("\n",$this->HREF,$this->currentstyle,$this->colorarray,$this->currentfont,$this->SUP,$this->SUB,''/*internal link*/,$this->strike,$this->outlineparam,$this->bgcolorarray); $this->cssbegin=false; $this->backupcss=array(); $this->buffer_on = false; $this->blockjustfinished = true; //Eliminate exceeding left-side spaces $this->pjustfinished = true; //behaves the same way } if($tag=='CODE' or $tag=='PRE' or $tag=='TT' or $tag=='KBD' or $tag=='SAMP') { $this->currentfont=''; $this->SetFont('arial'); } if($tag=='B' or $tag=='I' or $tag=='U') { $this->SetStyle($tag,false); if ($this->cssbegin and !$this->divbegin and !$this->pbegin and !$this->buffer_on) { //Reset values $this->Reset(); $this->cssbegin=false; $this->backupcss=array(); } } if($tag=='TEXTAREA') { if (!$this->tablestart) //not inside a table { //Draw arrows too? $texto = ''; foreach($this->textbuffer as $v) $texto .= $v[0]; $this->SetFillColor(235,235,235); $this->SetFont('courier'); $this->x +=3; $linesneeded = $this->WordWrap($texto,($this->col*2.2)+3); if ( $linesneeded > $this->row ) //Too many words inside textarea { $textoaux = explode("\n",$texto); $texto = ''; for($i=0;$i < $this->row;$i++) { if ($i == $this->row-1) $texto .= $textoaux[$i]; else $texto .= $textoaux[$i] . "\n"; } //Inform the user that some text has been truncated $texto{strlen($texto)-1} = "."; $texto{strlen($texto)-2} = "."; $texto{strlen($texto)-3} = "."; } $backup_y = $this->y; $this->Rect($this->x,$this->y,(2.2*$this->col)+6,5*$this->row,'DF'); if ($texto != '') $this->MultiCell((2.2*$this->col)+6,$this->lineheight,$texto); $this->y = $backup_y + $this->row*$this->lineheight; $this->SetFont('arial'); } else //inside a table { $this->cell[$this->row][$this->col]['textbuffer'][] = $this->textbuffer[0]; $this->cell[$this->row][$this->col]['text'][] = $this->textbuffer[0]; $this->cell[$this->row][$this->col]['form'] = true; // in order to make some width adjustments later $this->specialcontent = ''; } $this->SetFillColor(255); $this->textbuffer=array(); $this->buffer_on = false; } if($tag=='SELECT') { $texto = ''; $tamanho = 0; if (isset($this->selectoption['MAXWIDTH'])) $tamanho = $this->selectoption['MAXWIDTH']; if ($this->tablestart) { $texto = "???".$this->specialcontent."???".$this->selectoption['SELECTED']; $aux = explode("???",$texto); $texto = $aux[2]; $texto = "???".$aux[1].",width=$tamanho,height=".($this->lineheight + 2)."???".$texto; $this->cell[$this->row][$this->col]['s'] += $tamanho + 7; // margin + arrow box $this->cell[$this->row][$this->col]['form'] = true; // in order to make some width adjustments later if (!isset($this->cell[$this->row][$this->col]['h'])) $this->cell[$this->row][$this->col]['h'] = $this->lineheight + 2; $this->cell[$this->row][$this->col]['textbuffer'][] = array($texto); $this->cell[$this->row][$this->col]['text'][] = ''; } else //not inside a table { $texto = $this->selectoption['SELECTED']; $this->SetFillColor(235,235,235); $this->x += 2; $this->Rect($this->x,$this->y,$tamanho+2,5,'DF');//+2 margin $this->x += 1; if ($texto != '') $this->Write(5,$texto,$this->x); $this->x += $tamanho - $this->GetStringWidth($texto) + 2; $this->SetFillColor(190,190,190); $this->Rect($this->x-1,$this->y,5,5,'DF'); //Arrow Box $this->SetFont('zapfdingbats'); $this->Write(5,chr(116),$this->x); //Down arrow $this->SetFont('arial'); $this->SetFillColor(255); $this->x += 1; } $this->selectoption = array(); $this->specialcontent = ''; $this->textbuffer = array(); } if($tag=='SUB' or $tag=='SUP') //subscript or superscript { if(!$this->pbegin and !$this->divbegin and !$this->tablestart and !$this->buffer_on and !$this->strike) { //Deactivate $this->SUB/SUP for its info is already stored inside $this->textbuffer $this->SUB=false; $this->SUP=false; //Save x,y coords ??? $x = $this->x; $y = $this->y; //Set some default values $this->divwidth = $this->pgwidth - $x + $this->lMargin; //Print content $this->printbuffer($this->textbuffer,true/*is out of a block (e.g. DIV,P etc.)*/); $this->textbuffer=array(); //Reset values $this->Reset(); } $this->SUB=false; $this->SUP=false; } if($tag=='S' or $tag=='STRIKE' or $tag=='DEL') { if(!$this->pbegin and !$this->divbegin and !$this->tablestart) { //Deactivate $this->strike for its info is already stored inside $this->textbuffer $this->strike=false; //Save x,y coords ??? $x = $this->x; $y = $this->y; //Set some default values $this->divwidth = $this->pgwidth - $x + $this->lMargin; //Print content $this->printbuffer($this->textbuffer,true/*is out of a block (e.g. DIV,P etc.)*/); $this->textbuffer=array(); //Reset values $this->Reset(); } $this->strike=false; } if($tag=='ADDRESS' or $tag=='CENTER') //
    or
    tag { $this->blockjustfinished = true; //Eliminate exceeding left-side spaces if(!$this->pbegin and !$this->divbegin and !$this->tablestart) { //Save x,y coords ??? $x = $this->x; $y = $this->y; //Set some default values $this->divwidth = $this->pgwidth - $x + $this->lMargin; //Print content $this->printbuffer($this->textbuffer); $this->textbuffer=array(); //Reset values $this->Reset(); } $this->buffer_on=false; if ($tag == 'ADDRESS') $this->SetStyle('I',false); } if($tag=='BIG') { $newsize = $this->FontSizePt - 1; $this->SetFontSize($newsize); $this->SetStyle('B',false); } if($tag=='SMALL') { $newsize = $this->FontSizePt + 1; $this->SetFontSize($newsize); } if($tag=='FONT') { if ($this->issetcolor == true) { $this->colorarray = array(); $this->SetTextColor(0); $this->issetcolor = false; } if ($this->issetfont) { $this->SetFont('arial'); $this->issetfont=false; } if ($this->cssbegin) { //Get some attributes back! $this->setCSS($this->backupcss); } } } function printlistbuffer() { //! @return void //! @desc Prints all list-related buffered info //Save x coordinate $x = $this->oldx; foreach($this->listitem as $item) { //Set default width & height values $this->divwidth = $this->pgwidth; $this->divheight = $this->lineheight; //Get list's buffered data $lvl = $item[0]; $num = $item[1]; $this->textbuffer = $item[2]; $occur = $item[3]; $type = $this->listlist[$lvl][$occur]['TYPE']; $maxnum = $this->listlist[$lvl][$occur]['MAXNUM']; switch($type) //Format type { case 'A': $num = dec2alpha($num,true); $maxnum = dec2alpha($maxnum,true); $type = str_pad($num,strlen($maxnum),' ',STR_PAD_LEFT) . "."; break; case 'a': $num = dec2alpha($num,false); $maxnum = dec2alpha($maxnum,false); $type = str_pad($num,strlen($maxnum),' ',STR_PAD_LEFT) . "."; break; case 'I': $num = dec2roman($num,true); $maxnum = dec2roman($maxnum,true); $type = str_pad($num,strlen($maxnum),' ',STR_PAD_LEFT) . "."; break; case 'i': $num = dec2roman($num,false); $maxnum = dec2roman($maxnum,false); $type = str_pad($num,strlen($maxnum),' ',STR_PAD_LEFT) . "."; break; case '1': $type = str_pad($num,strlen($maxnum),' ',STR_PAD_LEFT) . "."; break; case 'disc': $type = chr(149); break; case 'square': $type = chr(110); //black square on Zapfdingbats font break; case 'circle': $type = chr(186); break; default: break; } $this->x = (5*$lvl) + $x; //Indent list //Get bullet width including margins $oldsize = $this->FontSize * $this->k; if ($type == chr(110)) $this->SetFont('zapfdingbats','',5); $type .= ' '; $blt_width = $this->GetStringWidth($type)+$this->cMargin*2; //Output bullet $this->Cell($blt_width,5,$type,'','','L'); $this->SetFont('arial','',$oldsize); $this->divwidth = $this->divwidth + $this->lMargin - $this->x; //Print content $this->printbuffer($this->textbuffer); $this->textbuffer=array(); } //Reset all used values $this->listoccur = array(); $this->listitem = array(); $this->listlist = array(); $this->listlvl = 0; $this->listnum = 0; $this->listtype = ''; $this->textbuffer = array(); $this->divwidth = 0; $this->divheight = 0; $this->oldx = -1; //At last, but not least, skip a line $this->Ln($this->lineheight); } function printbuffer($arrayaux,$outofblock=false,$is_table=false) { //! @return headache //! @desc Prepares buffered text to be printed with FlowingBlock() //Save some previous parameters $save = array(); $save['strike'] = $this->strike; $save['SUP'] = $this->SUP; $save['SUB'] = $this->SUB; $save['DOTTED'] = $this->dotted_on; $save['DASHED'] = $this->dash_on; $this->SetDash(); //restore to no dash $this->dash_on = false; $this->dotted_on = false; $bak_y = $this->y; $bak_x = $this->x; $align = $this->divalign; $oldpage = $this->page; //Overall object size == $old_height //Line height == $this->divheight $old_height = $this->divheight; if ($is_table) { $this->divheight = 1.1*$this->lineheight; $fill = 0; } else { $this->divheight = $this->lineheight; if ($this->FillColor == '1.000 g') $fill = 0; //avoid useless background painting (1.000 g == white background color) else $fill = 1; } $this->newFlowingBlock( $this->divwidth,$this->divheight,$this->divborder,$align,$fill,$is_table); $array_size = count($arrayaux); for($i=0;$i < $array_size; $i++) { $vetor = $arrayaux[$i]; if ($i == 0 and $vetor[0] != "\n") $vetor[0] = ltrim($vetor[0]); if (empty($vetor[0]) and empty($vetor[7])) continue; //Ignore empty text and not carrying an internal link //Activating buffer properties if(isset($vetor[10]) and !empty($vetor[10])) //Background color { $cor = $vetor[10]; $this->SetFillColor($cor['R'],$cor['G'],$cor['B']); $this->divbgcolor = true; } if(isset($vetor[9]) and !empty($vetor[9])) // Outline parameters { $cor = $vetor[9]['COLOR']; $outlinewidth = $vetor[9]['WIDTH']; $this->SetTextOutline($outlinewidth,$cor['R'],$cor['G'],$cor['B']); $this->outline_on = true; } if(isset($vetor[8]) and $vetor[8] === true) // strike-through the text { $this->strike = true; } if(isset($vetor[7]) and $vetor[7] != '') // internal link: { $this->internallink[$vetor[7]] = array("Y"=>$this->y,"PAGE"=>$this->page ); $this->Bookmark($vetor[7]." (pg. $this->page)",0,$this->y); if (empty($vetor[0])) continue; //Ignore empty text } if(isset($vetor[6]) and $vetor[6] === true) // Subscript { $this->SUB = true; $this->SetFontSize(6); } if(isset($vetor[5]) and $vetor[5] === true) // Superscript { $this->SUP = true; $this->SetFontSize(6); } if(isset($vetor[4]) and $vetor[4] != '') $this->SetFont($vetor[4]); // Font Family if (!empty($vetor[3])) //Font Color { $cor = $vetor[3]; $this->SetTextColor($cor['R'],$cor['G'],$cor['B']); } if(isset($vetor[2]) and $vetor[2] != '') //Bold,Italic,Underline styles { if (strpos($vetor[2],"B") !== false) $this->SetStyle('B',true); if (strpos($vetor[2],"I") !== false) $this->SetStyle('I',true); if (strpos($vetor[2],"U") !== false) $this->SetStyle('U',true); } if(isset($vetor[1]) and $vetor[1] != '') //LINK { if (strpos($vetor[1],".") === false) //assuming every external link has a dot indicating extension (e.g: .html .txt .zip www.somewhere.com etc.) { //Repeated reference to same anchor? while(array_key_exists($vetor[1],$this->internallink)) $vetor[1]="#".$vetor[1]; $this->internallink[$vetor[1]] = $this->AddLink(); $vetor[1] = $this->internallink[$vetor[1]]; } $this->HREF = $vetor[1]; $this->SetTextColor(0,0,255); $this->SetStyle('U',true); } //Print-out special content if (isset($vetor[0]) and $vetor[0]{0} == '?' and $vetor[0]{1} == '?' and $vetor[0]{2} == '?') //identifier has been identified! { $content = explode("???",$vetor[0]); $texto = $content[2]; $content = explode(",",$content[1]); foreach($content as $value) { $value = explode("=",$value); $specialcontent[$value[0]] = $value[1]; } if ($this->flowingBlockAttr[ 'contentWidth' ] > 0) // Print out previously accumulated content { $width_used = $this->flowingBlockAttr[ 'contentWidth' ] / $this->k; //Restart Flowing Block $this->finishFlowingBlock($outofblock); $this->x = $bak_x + ($width_used % $this->divwidth) + 0.5;// 0.5 == margin $this->y -= ($this->lineheight + 0.5); $extrawidth = 0; //only to be used in case $specialcontent['width'] does not contain all used width (e.g. Select Box) if ($specialcontent['type'] == 'select') $extrawidth = 7; //arrow box + margin if(($this->x - $bak_x) + $specialcontent['width'] + $extrawidth > $this->divwidth ) { $this->x = $bak_x; $this->y += $this->lineheight - 1; } $this->newFlowingBlock( $this->divwidth,$this->divheight,$this->divborder,$align,$fill,$is_table ); } switch(strtoupper($specialcontent['type'])) { case 'IMAGE': //xpos and ypos used in order to support:
    $xpos = 0; $ypos = 0; if (isset($specialcontent['ypos']) and $specialcontent['ypos'] != '') $ypos = (float)$specialcontent['ypos']; if (isset($specialcontent['xpos']) and $specialcontent['xpos'] != '') $xpos = (float)$specialcontent['xpos']; $width_used = (($this->x - $bak_x) + $specialcontent['width'])*$this->k; //in order to adjust x coordinate later //Is this the best way of fixing x,y coordinates? $fix_x = ($this->x+2) * $this->k + ($xpos*$this->k); //+2 margin $fix_y = ($this->h - (($this->y+2) + $specialcontent['height'])) * $this->k;//+2 margin $imgtemp = explode(" ",$texto); $imgtemp[5]=$fix_x; // x $imgtemp[6]=$fix_y; // y $texto = implode(" ",$imgtemp); $this->_out($texto); //Readjust x coordinate in order to allow text to be placed after this form element $this->x = $bak_x; $spacesize = $this->CurrentFont[ 'cw' ][ ' ' ] * ( $this->FontSizePt / 1000 ); $spacenum = (integer)ceil(($width_used / $spacesize)); //Consider the space used so far in this line as a bunch of spaces if ($ypos != 0) $this->Ln($ypos); else $this->WriteFlowingBlock(str_repeat(' ',$spacenum)); break; case 'INPUT': switch($specialcontent['subtype']) { case 'PASSWORD': case 'TEXT': //Draw TextField $width_used = (($this->x - $bak_x) + $specialcontent['width'])*$this->k; //in order to adjust x coordinate later $this->SetFillColor(235,235,235); $this->x += 1; $this->y += 1; $this->Rect($this->x,$this->y,$specialcontent['width'],4.5,'DF');// 4.5 in order to avoid overlapping if ($texto != '') { $this->x += 1; $this->Write(5,$texto,$this->x); $this->x -= $this->GetStringWidth($texto); } $this->SetFillColor(255); $this->y -= 1; //Readjust x coordinate in order to allow text to be placed after this form element $this->x = $bak_x; $spacesize = $this->CurrentFont[ 'cw' ][ ' ' ] * ( $this->FontSizePt / 1000 ); $spacenum = (integer)ceil(($width_used / $spacesize)); //Consider the space used so far in this line as a bunch of spaces $this->WriteFlowingBlock(str_repeat(' ',$spacenum)); break; case 'CHECKBOX': //Draw Checkbox $width_used = (($this->x - $bak_x) + $specialcontent['width'])*$this->k; //in order to adjust x coordinate later $checked = $texto; $this->SetFillColor(235,235,235); $this->y += 1; $this->x += 1; $this->Rect($this->x,$this->y,3,3,'DF'); if ($checked) { $this->Line($this->x,$this->y,$this->x+3,$this->y+3); $this->Line($this->x,$this->y+3,$this->x+3,$this->y); } $this->SetFillColor(255); $this->y -= 1; //Readjust x coordinate in order to allow text to be placed after this form element $this->x = $bak_x; $spacesize = $this->CurrentFont[ 'cw' ][ ' ' ] * ( $this->FontSizePt / 1000 ); $spacenum = (integer)ceil(($width_used / $spacesize)); //Consider the space used so far in this line as a bunch of spaces $this->WriteFlowingBlock(str_repeat(' ',$spacenum)); break; case 'RADIO': //Draw Radio button $width_used = (($this->x - $bak_x) + $specialcontent['width']+0.5)*$this->k; //in order to adjust x coordinate later $checked = $texto; $this->x += 2; $this->y += 1.5; $this->Circle($this->x,$this->y+1.2,1,'D'); $this->_out('0.000 g'); if ($checked) $this->Circle($this->x,$this->y+1.2,0.4,'DF'); $this->y -= 1.5; //Readjust x coordinate in order to allow text to be placed after this form element $this->x = $bak_x; $spacesize = $this->CurrentFont[ 'cw' ][ ' ' ] * ( $this->FontSizePt / 1000 ); $spacenum = (integer)ceil(($width_used / $spacesize)); //Consider the space used so far in this line as a bunch of spaces $this->WriteFlowingBlock(str_repeat(' ',$spacenum)); break; case 'BUTTON': // Draw a button case 'SUBMIT': case 'RESET': $nihil = ($specialcontent['width']-$this->GetStringWidth($texto))/2; $this->x += 1.5; $this->y += 1; $this->SetFillColor(190,190,190); $this->Rect($this->x,$this->y,$specialcontent['width'],4.5,'DF'); // 4.5 in order to avoid overlapping $this->x += $nihil; $this->Write(5,$texto,$this->x); $this->x += $nihil; $this->SetFillColor(255); $this->y -= 1; break; default: break; } break; case 'SELECT': $width_used = (($this->x - $bak_x) + $specialcontent['width'] + 8)*$this->k; //in order to adjust x coordinate later $this->SetFillColor(235,235,235); //light gray $this->x += 1.5; $this->y += 1; $this->Rect($this->x,$this->y,$specialcontent['width']+2,$this->lineheight,'DF'); // +2 == margin $this->x += 1; if ($texto != '') $this->Write($this->lineheight,$texto,$this->x); //the combobox content $this->x += $specialcontent['width'] - $this->GetStringWidth($texto) + 2; $this->SetFillColor(190,190,190); //dark gray $this->Rect($this->x-1,$this->y,5,5,'DF'); //Arrow Box $this->SetFont('zapfdingbats'); $this->Write($this->lineheight,chr(116),$this->x); //Down arrow $this->SetFont('arial'); $this->SetFillColor(255); //Readjust x coordinate in order to allow text to be placed after this form element $this->x = $bak_x; $spacesize = $this->CurrentFont[ 'cw' ][ ' ' ] * ( $this->FontSizePt / 1000 ); $spacenum = (integer)ceil(($width_used / $spacesize)); //Consider the space used so far in this line as a bunch of spaces $this->WriteFlowingBlock(str_repeat(' ',$spacenum)); break; case 'TEXTAREA': //Setup TextArea properties $this->SetFillColor(235,235,235); $this->SetFont('courier'); $this->currentfont='courier'; $ta_lines = $specialcontent['lines']; $ta_height = 1.1*$this->lineheight*$ta_lines; $ta_width = $specialcontent['width']; //Adjust x,y coordinates $this->x += 1.5; $this->y += 1.5; $linesneeded = $this->WordWrap($texto,$ta_width); if ( $linesneeded > $ta_lines ) //Too many words inside textarea { $textoaux = explode("\n",$texto); $texto = ''; for($i=0;$i<$ta_lines;$i++) { if ($i == $ta_lines-1) $texto .= $textoaux[$i]; else $texto .= $textoaux[$i] . "\n"; } //Inform the user that some text has been truncated $texto{strlen($texto)-1} = "."; $texto{strlen($texto)-2} = "."; $texto{strlen($texto)-3} = "."; } $backup_y = $this->y; $backup_x = $this->x; $this->Rect($this->x,$this->y,$ta_width+3,$ta_height,'DF'); if ($texto != '') $this->MultiCell($ta_width+3,$this->lineheight,$texto); $this->y = $backup_y - 1.5; $this->x = $backup_x + $ta_width + 2.5; $this->SetFillColor(255); $this->SetFont('arial'); $this->currentfont=''; break; default: break; } } else //THE text { if ($vetor[0] == "\n") //We are reading a
    now turned into newline ("\n") { //Restart Flowing Block $this->finishFlowingBlock($outofblock); if($outofblock) $this->Ln($this->lineheight); $this->x = $bak_x; $this->newFlowingBlock( $this->divwidth,$this->divheight,$this->divborder,$align,$fill,$is_table ); } else $this->WriteFlowingBlock( $vetor[0] , $outofblock ); } //Check if it is the last element. If so then finish printing the block if ($i == ($array_size-1)) $this->finishFlowingBlock($outofblock); //Now we must deactivate what we have used if( (isset($vetor[1]) and $vetor[1] != '') or $this->HREF != '') { $this->SetTextColor(0); $this->SetStyle('U',false); $this->HREF = ''; } if(isset($vetor[2]) and $vetor[2] != '') { $this->SetStyle('B',false); $this->SetStyle('I',false); $this->SetStyle('U',false); } if(isset($vetor[3]) and $vetor[3] != '') { unset($cor); $this->SetTextColor(0); } if(isset($vetor[4]) and $vetor[4] != '') $this->SetFont('arial'); if(isset($vetor[5]) and $vetor[5] === true) { $this->SUP = false; $this->SetFontSize(11); } if(isset($vetor[6]) and $vetor[6] === true) { $this->SUB = false; $this->SetFontSize(11); } //vetor7-internal links if(isset($vetor[8]) and $vetor[8] === true) // strike-through the text { $this->strike = false; } if(isset($vetor[9]) and !empty($vetor[9])) // Outline parameters { $this->SetTextOutline(false); $this->outline_on = false; } if(isset($vetor[10]) and !empty($vetor[10])) //Background color { $this->SetFillColor(255); $this->divbgcolor = false; } }//end of for(i=0;istrike = $save['strike']; $this->SUP = $save['SUP']; $this->SUB = $save['SUB']; $this->dotted_on = $save['DOTTED']; $this->dash_on = $save['DASHED']; if ($this->dash_on) $this->SetDash(2,2); //Check whether we have borders to paint or not //(only works 100% if whole content spans only 1 page) if ($this->cssbegin and ($this->divborder or $this->dash_on or $this->dotted_on or $this->divbgcolor)) { if ($oldpage != $this->page) { //Only border on last page is painted (known bug) $x = $this->lMargin; $y = $this->tMargin; $old_height = $this->y - $y; } else { if ($this->oldx < 0) $x = $this->x; else $x = $this->oldx; if ($this->oldy < 0) $y = $this->y - $old_height; else $y = $this->oldy; } if ($this->divborder) $this->Rect($x,$y,$this->divwidth,$old_height); if ($this->dash_on) $this->Rect($x,$y,$this->divwidth,$old_height); if ($this->dotted_on) $this->DottedRect($x,$y,$this->divwidth,$old_height); $this->x = $bak_x; } } function Reset() { //! @return void //! @desc Resets several class attributes // if ( $this->issetcolor !== true ) // { $this->SetTextColor(0); $this->SetDrawColor(0); $this->SetFillColor(255); $this->colorarray = array(); $this->bgcolorarray = array(); $this->issetcolor = false; // } $this->HREF = ''; $this->SetTextOutline(false); //$this->strike = false; $this->SetFontSize(11); $this->SetStyle('B',false); $this->SetStyle('I',false); $this->SetStyle('U',false); $this->SetFont('arial'); $this->divwidth = 0; $this->divheight = 0; $this->divalign = "L"; $this->divrevert = false; $this->divborder = 0; $this->divbgcolor = false; $this->toupper = false; $this->tolower = false; $this->SetDash(); //restore to no dash $this->dash_on = false; $this->dotted_on = false; $this->oldx = -1; $this->oldy = -1; } function ReadMetaTags($html) { //! @return void //! @desc Pass meta tag info to PDF file properties $regexp = '/ (\\w+?)=([^\\s>"]+)/si'; // changes anykey=anyvalue to anykey="anyvalue" (only do this when this happens inside tags) $html = preg_replace($regexp," \$1=\"\$2\"",$html); $regexp = '//si'; preg_match_all($regexp,$html,$aux); $firstattr = $aux[1]; $secondattr = $aux[3]; for( $i = 0 ; $i < count($aux[0]) ; $i++) { $name = ( strtoupper($firstattr[$i]) == "NAME" )? strtoupper($aux[2][$i]) : strtoupper($aux[4][$i]); $content = ( strtoupper($firstattr[$i]) == "CONTENT" )? $aux[2][$i] : $aux[4][$i]; switch($name) { case "KEYWORDS": $this->SetKeywords($content); break; case "AUTHOR": $this->SetAuthor($content); break; case "DESCRIPTION": $this->SetSubject($content); break; } } //Comercial do Aplicativo usado (no caso um script): $this->SetCreator("HTML2FPDF >> http://html2fpdf.sf.net"); } ////////////////// /// CSS parser /// ////////////////// function ReadCSS($html) { //! @desc CSS parser //! @return string /* * This version ONLY supports: .class {...} / #id { .... } * It does NOT support: body{...} / a#hover { ... } / p.right { ... } / other mixed names * This function must read the CSS code (internal or external) and order its value inside $this->CSS. */ $match = 0; // no match for instance $regexp = ''; // This helps debugging: showing what is the REAL string being processed //CSS inside external files $regexp = '//si'; $match = preg_match_all($regexp,$html,$CSSext); $ind = 0; while($match){ //Fix path value $path = $CSSext[1][$ind]; $path = str_replace("\\","/",$path); //If on Windows //Get link info and obtain its absolute path $regexp = '|^./|'; $path = preg_replace($regexp,'',$path); if (strpos($path,"../") !== false ) //It is a Relative Link { $backtrackamount = substr_count($path,"../"); $maxbacktrack = substr_count($this->basepath,"/") - 1; $filepath = str_replace("../",'',$path); $path = $this->basepath; //If it is an invalid relative link, then make it go to directory root if ($backtrackamount > $maxbacktrack) $backtrackamount = $maxbacktrack; //Backtrack some directories for( $i = 0 ; $i < $backtrackamount + 1 ; $i++ ) $path = substr( $path, 0 , strrpos($path,"/") ); $path = $path . "/" . $filepath; //Make it an absolute path } elseif( strpos($path,":/") === false) //It is a Local Link { $path = $this->basepath . $path; } //Do nothing if it is an Absolute Link //END of fix path value $CSSextblock = file_get_contents($path); //Get class/id name and its characteristics from $CSSblock[1] $regexp = '/[.# ]([^.]+?)\\s*?\{(.+?)\}/s'; // '/s' PCRE_DOTALL including \n preg_match_all( $regexp, $CSSextblock, $extstyle); //Make CSS[Name-of-the-class] = array(key => value) $regexp = '/\\s*?(\\S+?):(.+?);/si'; for($i=0; $i < count($extstyle[1]) ; $i++) { preg_match_all( $regexp, $extstyle[2][$i], $extstyleinfo); $extproperties = $extstyleinfo[1]; $extvalues = $extstyleinfo[2]; for($j = 0; $j < count($extproperties) ; $j++) { //Array-properties and Array-values must have the SAME SIZE! $extclassproperties[strtoupper($extproperties[$j])] = trim($extvalues[$j]); } $this->CSS[$extstyle[1][$i]] = $extclassproperties; $extproperties = array(); $extvalues = array(); $extclassproperties = array(); } $match--; $ind++; } //end of match $match = 0; // reset value, if needed //CSS internal //Get content between tags and order it, using regexp $regexp = '/(.*?)<\/style>/si'; // it can be