Source Code Documentation


pro\s2member-pro\includes\classes\gateways\authnet\authnet-utilities.inc.php


  1. <?php
  2. /**
  3. * Authorize.Net® utilities.
  4. *
  5. * Copyright: © 2009-2011
  6. * {@link http://www.websharks-inc.com/ WebSharks, Inc.}
  7. * (coded in the USA)
  8. *
  9. * This WordPress® plugin (s2Member Pro) is comprised of two parts:
  10. *
  11. * o (1) Its PHP code is licensed under the GPL license, as is WordPress®.
  12. * You should have received a copy of the GNU General Public License,
  13. * along with this software. In the main directory, see: /licensing/
  14. * If not, see: {@link http://www.gnu.org/licenses/}.
  15. *
  16. * o (2) All other parts of (s2Member Pro); including, but not limited to:
  17. * the CSS code, some JavaScript code, images, and design;
  18. * are licensed according to the license purchased.
  19. * See: {@link http://www.s2member.com/prices/}
  20. *
  21. * Unless you have our prior written consent, you must NOT directly or indirectly license,
  22. * sub-license, sell, resell, or provide for free; part (2) of the s2Member Pro Module;
  23. * or make an offer to do any of these things. All of these things are strictly
  24. * prohibited with part (2) of the s2Member Pro Module.
  25. *
  26. * Your purchase of s2Member Pro includes free lifetime upgrades via s2Member.com
  27. * (i.e. new features, bug fixes, updates, improvements); along with full access
  28. * to our video tutorial library: {@link http://www.s2member.com/videos/}
  29. *
  30. * @package s2Member\AuthNet
  31. * @since 1.5
  32. */
  33. if(realpath(__FILE__) === realpath($_SERVER["SCRIPT_FILENAME"]))
  34. exit("Do not access this file directly.");
  35.  
  36. if(!class_exists("c_ws_plugin__s2member_pro_authnet_utilities"))
  37. {
  38. /**
  39. * Authorize.Net® utilities.
  40. *
  41. * @package s2Member\AuthNet
  42. * @since 1.5
  43. */
  44. class c_ws_plugin__s2member_pro_authnet_utilities
  45. {
  46. /**
  47. * Calls upon Authorize.Net® AIM, and returns the response.
  48. *
  49. * @package s2Member\AuthNet
  50. * @since 1.5
  51. *
  52. * @param array $post_vars An array of variables to send through the Authorize.Net® API call.
  53. * @return array An array of variables returned from the API call.
  54. *
  55. * @todo Continue optimizing this routine with ``empty()`` and ``isset()``.
  56. */
  57. public static function authnet_aim_response($post_vars = FALSE)
  58. {
  59. global /* For Multisite support. */ $current_site, $current_blog;
  60.  
  61. $url = "https://".(($GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["pro_authnet_sandbox"]) ? "test.authorize.net" : "secure.authorize.net")."/gateway/transact.dll";
  62.  
  63. $post_vars = (is_array($post_vars)) ? $post_vars : array(); // Must be in array format.
  64.  
  65. $post_vars["x_version"] = "3.1"; // Configure the Authorize.Net® transaction version.
  66. $post_vars["x_login"] = $GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["pro_authnet_api_login_id"];
  67. $post_vars["x_tran_key"] = $GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["pro_authnet_api_trans_key"];
  68.  
  69. $post_vars["x_delim_data"] = "true"; // Yes, return a delimited string.
  70. $post_vars["x_delim_char"] = ","; // Fields delimitation character.
  71. $post_vars["x_encap_char"] = '"'; // Field encapsulation character.
  72. $post_vars["x_relay_response"] = "false"; // Always off for AIM.
  73.  
  74. $post_vars["x_invoice_num"] = (!empty($post_vars["x_invoice_num"])) ? substr($post_vars["x_invoice_num"], 0, 20) : "";
  75. $post_vars["x_description"] = (!empty($post_vars["x_description"])) ? substr($post_vars["x_description"], 0, 255) : "";
  76. $post_vars["x_description"] = c_ws_plugin__s2member_utils_strings::strip_2_kb_chars($post_vars["x_description"]);
  77.  
  78. $input_time = date("D M j, Y g:i:s a T"); // Record input time for logging.
  79.  
  80. $csv = trim(c_ws_plugin__s2member_utils_urls::remote($url, $post_vars, array("timeout" => 20)));
  81.  
  82. $output_time = date("D M j, Y g:i:s a T"); // Now record after output time.
  83.  
  84. $response = ($csv) ? c_ws_plugin__s2member_utils_strings::trim_dq_deep(preg_split("/\",\"/", $csv)) : array();
  85. $response = c_ws_plugin__s2member_utils_strings::trim_deep(stripslashes_deep($response));
  86.  
  87. foreach(array("response_code", "response_subcode", "response_reason_code", "response_reason_text", "authorization_code", "avs_response", "transaction_id", "invoice_number", "description", "amount", "method", "transaction_type", "customer_id", "first_name", "last_name", "company", "address", "city", "state", "zipcode", "country", "phone", "fax", "email", "ship_to_first_name", "ship_to_last_name", "ship_to_company", "ship_to_address", "ship_to_city", "ship_to_state", "ship_to_zipcode", "ship_to_country", "tax", "duty", "freight", "tax_exempt", "po_number", "md5_hash", "card_code_response", "cavv_response", "card_number", "card_type", "split_tender_id", "requested_amount", "balance_on_card") as $order => $field_name)
  88. $response[$field_name] = (isset($response[$order])) ? $response[$order] : null;
  89.  
  90. if(empty($response["response_code"]) || $response["response_code"] !== "1") // A value of 1 indicates success.
  91. {
  92. if(strlen($response["response_reason_code"]) || $response["response_reason_text"])
  93. // translators: Exclude `%2$s`. This is an English error returned by Authorize.Net®. Please replace `%2$s` with: `Unable to process, please try again`, or something to that affect. Or, if you prefer, you could Filter ``$response["__error"]`` with `ws_plugin__s2member_pro_authnet_aim_response`.
  94. $response["__error"] = sprintf(_x('Error #%1$s. %2$s.', "s2member-front", "s2member"), $response["response_reason_code"], rtrim($response["response_reason_text"], "."));
  95.  
  96. else // Else, generate an error messsage - so something is reported back to the Customer.
  97. $response["__error"] = _x("Error. Please contact Support for assistance.", "s2member-front", "s2member");
  98. }
  99. /*
  100. If debugging is enabled; we need to maintain a comprehensive log file.
  101. Logging now supports Multisite Networking as well.
  102. */
  103. $logt = c_ws_plugin__s2member_utilities::time_details ();
  104. $logv = c_ws_plugin__s2member_utilities::ver_details();
  105. $logm = c_ws_plugin__s2member_utilities::mem_details();
  106. $log4 = $_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]."\nUser-Agent: ".$_SERVER["HTTP_USER_AGENT"];
  107. $log4 = (is_multisite() && !is_main_site()) ? ($_log4 = $current_blog->domain.$current_blog->path)."\n".$log4 : $log4;
  108. $log2 = (is_multisite() && !is_main_site()) ? "authnet-api-4-".trim(preg_replace("/[^a-z0-9]/i", "-", $_log4), "-").".log" : "authnet-api.log";
  109.  
  110. if(strlen($post_vars["x_card_num"]) > 4) // Only log last 4 digits for security.
  111. $post_vars["x_card_num"] = str_repeat("*", strlen($post_vars["x_card_num"]) - 4)
  112. .substr($post_vars["x_card_num"], -4); // Then display last 4 digits.
  113.  
  114. if($GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["gateway_debug_logs"])
  115. if(is_dir($logs_dir = $GLOBALS["WS_PLUGIN__"]["s2member"]["c"]["logs_dir"]))
  116. if(is_writable($logs_dir) && c_ws_plugin__s2member_utils_logs::archive_oversize_log_files())
  117. if(($log = "-------- Input vars: ( ".$input_time." ) --------\n".var_export($post_vars, true)."\n"))
  118. if(($log .= "-------- Output string/vars: ( ".$output_time." ) --------\n".$csv."\n".var_export($response, true)))
  119. file_put_contents($logs_dir."/".$log2,
  120. "LOG ENTRY: ".$logt . "\n" . $logv."\n".$logm."\n".$log4."\n".
  121. c_ws_plugin__s2member_utils_logs::conceal_private_info($log)."\n\n",
  122. FILE_APPEND);
  123.  
  124. return apply_filters("ws_plugin__s2member_pro_authnet_aim_response", c_ws_plugin__s2member_pro_authnet_utilities::_authnet_aim_response_filters($response), get_defined_vars());
  125. }
  126. /**
  127. * A sort of callback function that Filters Authorize.Net® AIM responses.
  128. *
  129. * Provides alternative explanations in some cases that require special attention.
  130. *
  131. * @package s2Member\AuthNet
  132. * @since 1.5
  133. *
  134. * @param array $response An array of response variables.
  135. * @return array An array of response variables; possibly modified by this routine.
  136. */
  137. public static function _authnet_aim_response_filters($response = FALSE)
  138. {
  139. return $response; // Nothing here yet.
  140. }
  141. /**
  142. * Calls upon Authorize.Net® ARB, and returns the response.
  143. *
  144. * @package s2Member\AuthNet
  145. * @since 1.5
  146. *
  147. * @param array $post_vars An array of variables to send through the Authorize.Net® API call.
  148. * @return array An array of variables returned from the API call.
  149. *
  150. * @todo Continue optimizing this routine with ``empty()`` and ``isset()``.
  151. */
  152. public static function authnet_arb_response($post_vars = FALSE)
  153. {
  154. global /* For Multisite support. */ $current_site, $current_blog;
  155.  
  156. $url = "https://".(($GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["pro_authnet_sandbox"]) ? "apitest.authorize.net" : "api.authorize.net")."/xml/v1/request.api";
  157.  
  158. $post_vars = (is_array($post_vars)) ? $post_vars : array(); // Must be in array format.
  159.  
  160. $post_vars["x_login"] = $GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["pro_authnet_api_login_id"];
  161. $post_vars["x_tran_key"] = $GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["pro_authnet_api_trans_key"];
  162.  
  163. $post_vars["x_invoice_num"] = (!empty($post_vars["x_invoice_num"])) ? substr($post_vars["x_invoice_num"], 0, 20) : "";
  164. $post_vars["x_description"] = (!empty($post_vars["x_description"])) ? substr($post_vars["x_description"], 0, 255) : "";
  165. $post_vars["x_description"] = c_ws_plugin__s2member_utils_strings::strip_2_kb_chars($post_vars["x_description"]);
  166.  
  167. $trial = (!empty($post_vars["x_trial_occurrences"])) ? true : false; // Indicates existence of trial.
  168.  
  169. if((int)$post_vars["x_length"] === 30 && $post_vars["x_unit"] === "days")
  170. {
  171. $post_vars["x_length"] = 1;
  172. $post_vars["x_unit"] = "months";
  173. }
  174.  
  175. if(!empty($post_vars["x_method"]) && $post_vars["x_method"] === "create")
  176. {
  177. $xml = '<?xml version="1.0" encoding="utf-8"?>';
  178.  
  179. $xml .= '<ARBCreateSubscriptionRequest xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">';
  180.  
  181. $xml .= '<merchantAuthentication>';
  182. $xml .= '<name>'.esc_html($post_vars["x_login"]).'</name>';
  183. $xml .= '<transactionKey>'.esc_html($post_vars["x_tran_key"]).'</transactionKey>';
  184. $xml .= '</merchantAuthentication>';
  185.  
  186. $xml .= '<refId>'.esc_html($post_vars["x_invoice_num"]).'</refId>';
  187.  
  188. $xml .= '<subscription>';
  189.  
  190. $xml .= '<name>'.esc_html($_SERVER["HTTP_HOST"]).'</name>';
  191.  
  192. $xml .= '<paymentSchedule>';
  193. $xml .= '<interval>';
  194. $xml .= '<length>'.esc_html($post_vars["x_length"]).'</length>';
  195. $xml .= '<unit>'.esc_html($post_vars["x_unit"]).'</unit>';
  196. $xml .= '</interval>';
  197. $xml .= '<startDate>'.esc_html($post_vars["x_start_date"]).'</startDate>';
  198. $xml .= '<totalOccurrences>'.esc_html($post_vars["x_total_occurrences"]).'</totalOccurrences>';
  199. $xml .= ($trial) ? '<trialOccurrences>'.esc_html($post_vars["x_trial_occurrences"]).'</trialOccurrences>' : '';
  200. $xml .= '</paymentSchedule>';
  201.  
  202. $xml .= '<amount>'.esc_html($post_vars["x_amount"]).'</amount>';
  203. $xml .= ($trial) ? '<trialAmount>'.esc_html($post_vars["x_trial_amount"]).'</trialAmount>' : '';
  204.  
  205. $xml .= '<payment>';
  206. $xml .= '<creditCard>';
  207. $xml .= '<cardNumber>'.esc_html($post_vars["x_card_num"]).'</cardNumber>';
  208. $xml .= '<expirationDate>'.esc_html($post_vars["x_exp_date"]).'</expirationDate>';
  209. $xml .= '<cardCode>'.esc_html($post_vars["x_card_code"]).'</cardCode>';
  210. $xml .= '</creditCard>';
  211. $xml .= '</payment>';
  212.  
  213. $xml .= '<order>';
  214. $xml .= '<invoiceNumber>'.esc_html($post_vars["x_invoice_num"]).'</invoiceNumber>';
  215. $xml .= '<description>'.esc_html($post_vars["x_description"]).'</description>';
  216. $xml .= '</order>';
  217.  
  218. $xml .= '<customer>';
  219. $xml .= '<email>'.esc_html($post_vars["x_email"]).'</email>';
  220. $xml .= '</customer>';
  221.  
  222. $xml .= '<billTo>';
  223. $xml .= '<firstName>'.esc_html(substr($post_vars["x_first_name"], 0, 50)).'</firstName>';
  224. $xml .= '<lastName>'.esc_html(substr($post_vars["x_last_name"], 0, 50)).'</lastName>';
  225. $xml .= '<address>'.esc_html(substr($post_vars["x_address"], 0, 60)).'</address>';
  226. $xml .= '<city>'.esc_html(substr($post_vars["x_city"], 0, 40)).'</city>';
  227. $xml .= '<state>'.esc_html(substr($post_vars["x_state"], 0, 2)).'</state>';
  228. $xml .= '<zip>'.esc_html(substr($post_vars["x_zip"], 0, 20)).'</zip>';
  229. $xml .= '<country>'.esc_html(substr($post_vars["x_country"], 0, 60)).'</country>';
  230. $xml .= '</billTo>';
  231.  
  232. $xml .= '</subscription>';
  233.  
  234. $xml .= '</ARBCreateSubscriptionRequest>';
  235. }
  236.  
  237. else if(!empty($post_vars["x_method"]) && $post_vars["x_method"] === "update")
  238. {
  239. $xml = '<?xml version="1.0" encoding="utf-8"?>';
  240.  
  241. $xml .= '<ARBUpdateSubscriptionRequest xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">';
  242.  
  243. $xml .= '<merchantAuthentication>';
  244. $xml .= '<name>'.esc_html($post_vars["x_login"]).'</name>';
  245. $xml .= '<transactionKey>'.esc_html($post_vars["x_tran_key"]).'</transactionKey>';
  246. $xml .= '</merchantAuthentication>';
  247.  
  248. $xml .= '<subscriptionId>'.esc_html($post_vars["x_subscription_id"]).'</subscriptionId>';
  249.  
  250. $xml .= '<subscription>';
  251.  
  252. $xml .= '<payment>';
  253. $xml .= '<creditCard>';
  254. $xml .= '<cardNumber>'.esc_html($post_vars["x_card_num"]).'</cardNumber>';
  255. $xml .= '<expirationDate>'.esc_html($post_vars["x_exp_date"]).'</expirationDate>';
  256. $xml .= '<cardCode>'.esc_html($post_vars["x_card_code"]).'</cardCode>';
  257. $xml .= '</creditCard>';
  258. $xml .= '</payment>';
  259.  
  260. $xml .= '<customer>';
  261. $xml .= '<email>'.esc_html($post_vars["x_email"]).'</email>';
  262. $xml .= '</customer>';
  263.  
  264. $xml .= '<billTo>';
  265. $xml .= '<firstName>'.esc_html($post_vars["x_first_name"]).'</firstName>';
  266. $xml .= '<lastName>'.esc_html($post_vars["x_last_name"]).'</lastName>';
  267. $xml .= '<address>'.esc_html($post_vars["x_address"]).'</address>';
  268. $xml .= '<city>'.esc_html($post_vars["x_city"]).'</city>';
  269. $xml .= '<state>'.esc_html($post_vars["x_state"]).'</state>';
  270. $xml .= '<zip>'.esc_html($post_vars["x_zip"]).'</zip>';
  271. $xml .= '<country>'.esc_html($post_vars["x_country"]).'</country>';
  272. $xml .= '</billTo>';
  273.  
  274. $xml .= '</subscription>';
  275.  
  276. $xml .= '</ARBUpdateSubscriptionRequest>';
  277. }
  278.  
  279. else if(!empty($post_vars["x_method"]) && $post_vars["x_method"] === "status")
  280. {
  281. $xml = '<?xml version="1.0" encoding="utf-8"?>';
  282.  
  283. $xml .= '<ARBGetSubscriptionStatusRequest xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">';
  284.  
  285. $xml .= '<merchantAuthentication>';
  286. $xml .= '<name>'.esc_html($post_vars["x_login"]).'</name>';
  287. $xml .= '<transactionKey>'.esc_html($post_vars["x_tran_key"]).'</transactionKey>';
  288. $xml .= '</merchantAuthentication>';
  289.  
  290. $xml .= '<subscriptionId>'.esc_html($post_vars["x_subscription_id"]).'</subscriptionId>';
  291.  
  292. $xml .= '</ARBGetSubscriptionStatusRequest>';
  293. }
  294.  
  295. else if(!empty($post_vars["x_method"]) && $post_vars["x_method"] === "cancel")
  296. {
  297. $xml = '<?xml version="1.0" encoding="utf-8"?>';
  298.  
  299. $xml .= '<ARBCancelSubscriptionRequest xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">';
  300.  
  301. $xml .= '<merchantAuthentication>';
  302. $xml .= '<name>'.esc_html($post_vars["x_login"]).'</name>';
  303. $xml .= '<transactionKey>'.esc_html($post_vars["x_tran_key"]).'</transactionKey>';
  304. $xml .= '</merchantAuthentication>';
  305.  
  306. $xml .= '<subscriptionId>'.esc_html($post_vars["x_subscription_id"]).'</subscriptionId>';
  307.  
  308. $xml .= '</ARBCancelSubscriptionRequest>';
  309. }
  310.  
  311. $req["headers"]["Accept"] = "application/xml; charset=UTF-8";
  312. $req["headers"]["Content-Type"] = "application/xml; charset=UTF-8";
  313.  
  314. $input_time = date("D M j, Y g:i:s a T"); // Record input time for logging.
  315.  
  316. $xml = trim(c_ws_plugin__s2member_utils_urls::remote($url, $xml, array_merge($req, array("timeout" => 20))));
  317.  
  318. $output_time = date("D M j, Y g:i:s a T"); // Now record after output time.
  319.  
  320. $response = c_ws_plugin__s2member_pro_authnet_utilities::_authnet_parse_arb_response($xml);
  321.  
  322. if(empty($response["response_code"]) || $response["response_code"] !== "I00001") // A value of I00001 indicates success.
  323. {
  324. if(strlen($response["response_reason_code"]) || $response["response_reason_text"])
  325. // translators: Exclude `%2$s`. This is an English error returned by Authorize.Net®. Please replace `%2$s` with: `Unable to process, please try again`, or something to that affect. Or, if you prefer, you could Filter ``$response["__error"]`` with `ws_plugin__s2member_pro_authnet_arb_response`.
  326. $response["__error"] = sprintf(_x('Error #%1$s. %2$s.', "s2member-front", "s2member"), $response["response_reason_code"], rtrim($response["response_reason_text"], "."));
  327.  
  328. else // Else, generate an error messsage - so something is reported back to the Customer.
  329. $response["__error"] = _x("Error. Please contact Support for assistance.", "s2member-front", "s2member");
  330. }
  331. /*
  332. If debugging is enabled; we need to maintain a comprehensive log file.
  333. Logging now supports Multisite Networking as well.
  334. */
  335. $logt = c_ws_plugin__s2member_utilities::time_details ();
  336. $logv = c_ws_plugin__s2member_utilities::ver_details();
  337. $logm = c_ws_plugin__s2member_utilities::mem_details();
  338. $log4 = $_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]."\nUser-Agent: ".$_SERVER["HTTP_USER_AGENT"];
  339. $log4 = (is_multisite() && !is_main_site()) ? ($_log4 = $current_blog->domain.$current_blog->path)."\n".$log4 : $log4;
  340. $log2 = (is_multisite() && !is_main_site()) ? "authnet-api-4-".trim(preg_replace("/[^a-z0-9]/i", "-", $_log4), "-").".log" : "authnet-api.log";
  341.  
  342. if(strlen($post_vars["x_card_num"]) > 4) // Only log last 4 digits for security.
  343. $post_vars["x_card_num"] = str_repeat("*", strlen($post_vars["x_card_num"]) - 4)
  344. .substr($post_vars["x_card_num"], -4); // Then display last 4 digits.
  345.  
  346. if($GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["gateway_debug_logs"])
  347. if(is_dir($logs_dir = $GLOBALS["WS_PLUGIN__"]["s2member"]["c"]["logs_dir"]))
  348. if(is_writable($logs_dir) && c_ws_plugin__s2member_utils_logs::archive_oversize_log_files())
  349. if(($log = "-------- Input vars: ( ".$input_time." ) --------\n".var_export($post_vars, true)."\n"))
  350. if(($log .= "-------- Output string/vars: ( ".$output_time." ) --------\n".$xml."\n".var_export($response, true)))
  351. file_put_contents($logs_dir."/".$log2,
  352. "LOG ENTRY: ".$logt . "\n" . $logv."\n".$logm."\n".$log4."\n".
  353. c_ws_plugin__s2member_utils_logs::conceal_private_info($log)."\n\n",
  354. FILE_APPEND);
  355.  
  356. return apply_filters("ws_plugin__s2member_pro_authnet_arb_response", c_ws_plugin__s2member_pro_authnet_utilities::_authnet_arb_response_filters($response), get_defined_vars());
  357. }
  358. /**
  359. * A sort of callback function that parses Authorize.Net® ARB responses.
  360. *
  361. * @package s2Member\AuthNet
  362. * @since 1.5
  363. *
  364. * @param str $xml XML markup returned by the ARB call.
  365. * @return array An array of response variables, parsed by s2Member.
  366. */
  367. public static function _authnet_parse_arb_response($xml = FALSE)
  368. {
  369. if($xml && preg_match("/\<(ErrorResponse).*?\>.*?\<code\>(.+?)\<\/code\>.*?\<\/\\1\>/is", $xml, $m))
  370. {
  371. $response["response_code"] = $response["response_reason_code"] = trim($m[2]);
  372.  
  373. if(preg_match("/\<(ErrorResponse).*?\>.*?\<text\>(.+?)\<\/text\>.*?\<\/\\1\>/is", $xml, $m))
  374. $response["response_text"] = $response["response_reason_text"] = trim($m[2]);
  375. }
  376. else if($xml && preg_match("/\<(ARBCreateSubscriptionResponse|ARBUpdateSubscriptionResponse|ARBGetSubscriptionStatusResponse|ARBCancelSubscriptionResponse).*?\>.*?\<code\>(.+?)\<\/code\>.*?\<\/\\1\>/is", $xml, $m))
  377. {
  378. $response["response_code"] = $response["response_reason_code"] = trim($m[2]);
  379.  
  380. if(preg_match("/\<(ARBCreateSubscriptionResponse|ARBUpdateSubscriptionResponse|ARBGetSubscriptionStatusResponse|ARBCancelSubscriptionResponse).*?\>.*?\<text\>(.+?)\<\/text\>.*?\<\/\\1\>/is", $xml, $m))
  381. $response["response_text"] = $response["response_reason_text"] = trim($m[2]);
  382.  
  383. if(preg_match("/\<(subscriptionId)\>(.+?)\<\/\\1\>/is", $xml, $m))
  384. $response["subscription_id"] = trim($m[2]);
  385.  
  386. if(preg_match("/\<(status)\>(.+?)\<\/\\1\>/is", $xml, $m))
  387. $response["subscription_status"] = trim($m[2]);
  388. }
  389.  
  390. $response = (!empty($response) && is_array($response)) ? $response : array();
  391.  
  392. return c_ws_plugin__s2member_utils_strings::trim_deep(stripslashes_deep($response));
  393. }
  394. /**
  395. * A sort of callback function that Filters Authorize.Net® ARB responses.
  396. *
  397. * Provides alternative explanations in some cases that require special attention.
  398. *
  399. * @package s2Member\AuthNet
  400. * @since 1.5
  401. *
  402. * @param array $response An array of response variables.
  403. * @return array An array of response variables; possibly modified by this routine.
  404. */
  405. public static function _authnet_arb_response_filters($response = FALSE)
  406. {
  407. return $response; // Nothing here yet.
  408. }
  409. /**
  410. * Get ``$_POST`` or ``$_REQUEST`` vars from Authorize.Net®.
  411. *
  412. * Authorize.Net® returns `x_MD5_Hash` in uppercase format for some reason.
  413. *
  414. * @package s2Member\AuthNet
  415. * @since 1.5
  416. *
  417. * @return array|bool An array of verified ``$_POST`` or ``$_REQUEST`` variables, else false.
  418. *
  419. * @todo Continue optimizing this routine with ``empty()`` and ``isset()``.
  420. * @todo Candidate for the use of ``ifsetor()``?
  421. * @todo Update to use ``strcasecmp()``.
  422. */
  423. public static function authnet_postvars()
  424. {
  425. if(!empty($_REQUEST["s2member_pro_authnet_notify"]) && !empty($_REQUEST["x_MD5_Hash"]))
  426. {
  427. $postvars = c_ws_plugin__s2member_utils_strings::trim_deep(stripslashes_deep($_REQUEST));
  428.  
  429. foreach($postvars as $var => $value)
  430. if(preg_match("/^s2member_/", $var))
  431. unset($postvars[$var]);
  432.  
  433. $aim_digest_vars = $GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["pro_authnet_api_login_id"].$postvars["x_trans_id"].$postvars["x_amount"];
  434. $arb_digest_vars = $postvars["x_trans_id"].$postvars["x_amount"];
  435.  
  436. if(strtolower($postvars["x_MD5_Hash"]) === md5($GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["pro_authnet_api_salt_key"].$aim_digest_vars))
  437. return $postvars;
  438.  
  439. else if(strtolower($postvars["x_MD5_Hash"]) === md5($GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["pro_authnet_api_salt_key"].$arb_digest_vars))
  440. return $postvars;
  441.  
  442. else // Nope.
  443. return false;
  444. }
  445. else // Nope.
  446. return false;
  447. }
  448. /**
  449. * Calculates start date for a Recurring Payment Profile.
  450. *
  451. * @package s2Member\AuthNet
  452. * @since 1.5
  453. *
  454. * @param str $period1 Optional. A "Period Term" combination. Defaults to `0 D`.
  455. * @param str $period3 Optional. A "Period Term" combination. Defaults to `0 D`.
  456. * @return int The start time, a Unix timestamp.
  457. */
  458. public static function authnet_start_time($period1 = FALSE, $period3 = FALSE)
  459. {
  460. if(!($p1_time = 0) && ($period1 = trim(strtoupper($period1))))
  461. {
  462. list($num, $span) = preg_split("/ /", $period1, 2);
  463.  
  464. $days = 0; // Days start at 0.
  465.  
  466. if(is_numeric($num) && !is_numeric($span))
  467. {
  468. $days = ($span === "D") ? 1 : $days;
  469. $days = ($span === "W") ? 7 : $days;
  470. $days = ($span === "M") ? 30 : $days;
  471. $days = ($span === "Y") ? 365 : $days;
  472. }
  473.  
  474. $p1_days = (int)$num * (int)$days;
  475. $p1_time = $p1_days * 86400;
  476. }
  477.  
  478. if(!($p3_time = 0) && ($period3 = trim(strtoupper($period3))))
  479. {
  480. list($num, $span) = preg_split("/ /", $period3, 2);
  481.  
  482. $days = 0; // Days start at 0.
  483.  
  484. if(is_numeric($num) && !is_numeric($span))
  485. {
  486. $days = ($span === "D") ? 1 : $days;
  487. $days = ($span === "W") ? 7 : $days;
  488. $days = ($span === "M") ? 30 : $days;
  489. $days = ($span === "Y") ? 365 : $days;
  490. }
  491.  
  492. $p3_days = (int)$num * (int)$days;
  493. $p3_time = $p3_days * 86400;
  494. }
  495.  
  496. $start_time = strtotime("now") + $p1_time + $p3_time;
  497.  
  498. $start_time = ($start_time <= 0) ? strtotime("now") : $start_time;
  499.  
  500. $start_time = $start_time + 43200; // + 12 hours.
  501.  
  502. return $start_time;
  503. }
  504. /**
  505. * Calculates period in days for Authorize.Net® ARB integration.
  506. *
  507. * @package s2Member\AuthNet
  508. * @since 1.5
  509. *
  510. * @param int|str $period Optional. A numeric Period that coincides with ``$term``.
  511. * @param str $term Optional. A Term that coincides with ``$period``.
  512. * @return int A "Period Term", in days. Defaults to `0`.
  513. */
  514. public static function authnet_per_term_2_days($period = FALSE, $term = FALSE)
  515. {
  516. if(is_numeric($period) && !is_numeric($term) && ($term = strtoupper($term)))
  517. {
  518. $days = ($term === "D") ? 1 : $days;
  519. $days = ($term === "W") ? 7 : $days;
  520. $days = ($term === "M") ? 30 : $days;
  521. $days = ($term === "Y") ? 365 : $days;
  522.  
  523. return (int)$period * (int)$days;
  524. }
  525. else
  526. return 0;
  527. }
  528. /**
  529. * Re-formats credit card expiration dates for Authorize.Net®.
  530. *
  531. * @package s2Member\AuthNet
  532. * @since 1.5
  533. *
  534. * @param str $exp Expects a credit card expiration date in `mm/yyyy` format.
  535. * @return str A credit card expiration date in `yyyy-mm` format for Authorize.Net®.
  536. */
  537. public static function authnet_exp_date($exp = FALSE)
  538. {
  539. list($mm, $yyyy) = preg_split("/\//", $exp, 2);
  540.  
  541. return trim($yyyy."-".$mm, "- \t\n\r\0\x0B");
  542. }
  543. /**
  544. * Parses an Authorize.Net® Silent Post.
  545. *
  546. * Parses `s2_reference`, `s2_domain`, `s2_invoice`, `s2_start_time`, `s2_p1`, `s2_p3`, `s2_custom`
  547. * from an Authorize.Net® Silent Post *(aka: IPN)* response.
  548. *
  549. * @package s2Member\AuthNet
  550. * @since 1.5
  551. *
  552. * @param array $array Expects an array of details returned by an Authorize.Net® Silent Post.
  553. * @return array|bool The same ``$array``, but with additional details filled by this routine; else false.
  554. *
  555. * @todo Continue optimizing this routine with ``empty()`` and ``isset()``.
  556. * @todo Candidate for the use of ``ifsetor()``?
  557. */
  558. public static function authnet_parse_arb_desc($array = FALSE)
  559. {
  560. if(is_array($array) && !empty($array["x_description"]) && preg_match("/\(\((.+?)\)\)/i", $array["x_description"], $m))
  561. {
  562. list($array["s2_reference"], $array["s2_domain"], $array["s2_invoice"], $array["s2_currency"]) = preg_split("/~/", $m[1], 4);
  563. list($array["s2_start_time"], $array["s2_p1"], $array["s2_p3"]) = preg_split("/\:/", $array["s2_reference"], 3);
  564.  
  565. $array["x_description"] = preg_replace("/\(\((.+?)\)\)/i", "", $array["x_description"]);
  566.  
  567. $array["s2_custom"] = (!empty($array["x_subscription_id"])) ? c_ws_plugin__s2member_utils_users::get_user_custom_with($array["x_subscription_id"]) : "";
  568. $array["s2_custom"] = ($array["s2_custom"]) ? $array["s2_custom"] : $array["s2_domain"];
  569.  
  570. return c_ws_plugin__s2member_utils_strings::trim_deep($array);
  571. }
  572. else // False.
  573. return false;
  574. }
  575. /**
  576. * Determines whether or not Tax may apply.
  577. *
  578. * @package s2Member\AuthNet
  579. * @since 1.5
  580. *
  581. * @return bool True if Tax may apply, else false.
  582. */
  583. public static function authnet_tax_may_apply()
  584. {
  585. if((float)$GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["pro_default_tax"] > 0)
  586. return true;
  587.  
  588. else if($GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["pro_tax_rates"])
  589. return true;
  590.  
  591. return false;
  592. }
  593. /**
  594. * Handles the return of Tax for Pro Forms, via AJAX; through a JSON object.
  595. *
  596. * @package s2Member\AuthNet
  597. * @since 1.5
  598. *
  599. * @return null Or exits script execution after returning data for AJAX caller.
  600. *
  601. * @todo Check the use of ``strip_tags()`` in this routine?
  602. * @todo Continue optimizing this routine with ``empty()`` and ``isset()``.
  603. * @todo Candidate for the use of ``ifsetor()``?
  604. */
  605. public static function authnet_ajax_tax()
  606. {
  607. if(!empty($_POST["ws_plugin__s2member_pro_authnet_ajax_tax"]) && ($nonce = $_POST["ws_plugin__s2member_pro_authnet_ajax_tax"]) && (wp_verify_nonce($nonce, "ws-plugin--s2member-pro-authnet-ajax-tax") || c_ws_plugin__s2member_utils_encryption::decrypt($nonce) === "ws-plugin--s2member-pro-authnet-ajax-tax"))
  608. /* A wp_verify_nonce() won't always work here, because s2member-pro-min.js must be cacheable. The output from wp_create_nonce() would go stale.
  609. So instead, s2member-pro-min.js should use ``c_ws_plugin__s2member_utils_encryption::encrypt()`` as an alternate form of nonce. */
  610. {
  611. status_header(200); // Send a 200 OK status header.
  612. header("Content-Type: text/plain; charset=UTF-8"); // Content-Type text/plain with UTF-8.
  613. while (@ob_end_clean ()); // Clean any existing output buffers.
  614.  
  615. if(!empty($_POST["ws_plugin__s2member_pro_authnet_ajax_tax_vars"]) && is_array($_p_tax_vars = c_ws_plugin__s2member_utils_strings::trim_deep(stripslashes_deep($_POST["ws_plugin__s2member_pro_authnet_ajax_tax_vars"]))))
  616. {
  617. if(is_array($attr = (!empty($_p_tax_vars["attr"])) ? unserialize(c_ws_plugin__s2member_utils_encryption::decrypt($_p_tax_vars["attr"])) : false))
  618. {
  619. $attr = (!empty($attr["coupon"])) ? c_ws_plugin__s2member_pro_authnet_utilities::authnet_apply_coupon($attr, $attr["coupon"]) : $attr;
  620.  
  621. $trial = ($attr["rr"] !== "BN" && $attr["tp"]) ? true : false; // Is there a trial?
  622. $sub_total_today = ($trial) ? $attr["ta"] : $attr["ra"]; // What is the sub-total today?
  623.  
  624. $state = strip_tags($_p_tax_vars["state"]);
  625. $country = strip_tags($_p_tax_vars["country"]);
  626. $zip = strip_tags($_p_tax_vars["zip"]);
  627. $currency = $attr["cc"]; // Currency.
  628. $desc = $attr["desc"]; // Description.
  629.  
  630. /* Trial is `null` in this function call. We only need to return what it costs today.
  631. However, we do tag on a "trial" element in the array so the ajax routine will know about this. */
  632. $a = c_ws_plugin__s2member_pro_authnet_utilities::authnet_cost(null, $sub_total_today, $state, $country, $zip, $currency, $desc);
  633. echo json_encode(array("trial" => $trial, "sub_total" => $a["sub_total"], "tax" => $a["tax"], "tax_per" => $a["tax_per"], "total" => $a["total"], "cur" => $a["cur"], "cur_symbol" => $a["cur_symbol"], "desc" => $a["desc"]));
  634. }
  635. }
  636.  
  637. exit(); // Clean exit.
  638. }
  639. }
  640. /**
  641. * Handles all cost calculations for Authorize.Net®.
  642. *
  643. * Returns an associative array with a possible Percentage Rate, along with the calculated Tax Amount.
  644. * Tax calculations are based on State/Province, Country, and/or Zip Code.
  645. * Updated to support multiple data fields in it's return value.
  646. *
  647. * @package s2Member\AuthNet
  648. * @since 1.5
  649. *
  650. * @param int|str $trial_sub_total Optional. A numeric Amount/cost of a possible Initial/Trial being offered.
  651. * @param int|str $sub_total Optional. A numeric Amount/cost of the purchase and/or Regular Period.
  652. * @param str $state Optional. The State/Province where the Customer is billed.
  653. * @param str $country Optional. The Country where the Customer is billed.
  654. * @param int|str $zip Optional. The Postal/Zip Code where the Customer is billed.
  655. * @param str $currency Optional. Expects a 3 character Currency Code.
  656. * @param str $desc Optional. Description of the sale.
  657. * @return array Array of calculations.
  658. *
  659. * @todo Add support for `Zip + 4` syntax?
  660. */
  661. public static function authnet_cost($trial_sub_total = FALSE, $sub_total = FALSE, $state = FALSE, $country = FALSE, $zip = FALSE, $currency = FALSE, $desc = FALSE)
  662. {
  663. $state = strtoupper(c_ws_plugin__s2member_pro_utilities::full_state($state, ($country = strtoupper($country))));
  664. $rates = strtoupper($GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["pro_tax_rates"]);
  665. $default = $GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["pro_default_tax"];
  666. $ps = _x("%", "s2member-front percentage-symbol", "s2member");
  667.  
  668. foreach(array("trial_sub_total" => $trial_sub_total, "sub_total" => $sub_total) as $this_key => $this_sub_total)
  669. {
  670. unset($_default, $this_tax, $this_tax_per, $this_total, $configured_rates, $configured_rate, $location, $rate, $m);
  671.  
  672. if(is_numeric($this_sub_total) && $this_sub_total > 0) // Must have a valid Sub-Total.
  673. {
  674. if(preg_match("/%$/", $default)) // Percentage-based.
  675. {
  676. if(($_default = (float)$default) > 0)
  677. {
  678. $this_tax = round(($this_sub_total / 100) * $_default, 2);
  679. $this_tax_per = $_default.$ps;
  680. }
  681. else // Else the Tax is 0.00.
  682. {
  683. $this_tax = 0.00;
  684. $this_tax_per = $_default.$ps;
  685. }
  686. }
  687. else if(($_default = (float)$default) > 0)
  688. {
  689. $this_tax = round($_default, 2);
  690. $this_tax_per = ""; // Flat.
  691. }
  692. else // Else the Tax is 0.00.
  693. {
  694. $this_tax = 0.00; // No Tax.
  695. $this_tax_per = ""; // Flat rate.
  696. }
  697.  
  698. if(strlen($country) === 2) // Must have a valid country.
  699. {
  700. foreach(preg_split("/[\r\n\t]+/", $rates) as $rate)
  701. {
  702. if($rate = trim($rate)) // Do NOT process empty lines.
  703. {
  704. list($location, $rate) = preg_split("/\=/", $rate, 2);
  705. $location = trim($location);
  706. $rate = trim($rate);
  707.  
  708. if($location === $country)
  709. $configured_rates[1] = $rate;
  710.  
  711. else if($state && $location === $state."/".$country)
  712. $configured_rates[2] = $rate;
  713.  
  714. else if($state && preg_match("/^([A-Z]{2})\/(".preg_quote($country, "/").")$/", $location, $m) && strtoupper(c_ws_plugin__s2member_pro_utilities::full_state($m[1], $m[2]))."/".$m[2] === $state."/".$country)
  715. $configured_rates[2] = $rate;
  716.  
  717. else if($zip && preg_match("/^([0-9]+)-([0-9]+)\/(".preg_quote($country, "/").")$/", $location, $m) && $zip >= $m[1] && $zip <= $m[2] && $country === $m[3])
  718. $configured_rates[3] = $rate;
  719.  
  720. else if($zip && $location === $zip."/".$country)
  721. $configured_rates[4] = $rate;
  722. }
  723. }
  724.  
  725. if(is_array($configured_rates) && !empty($configured_rates))
  726. {
  727. krsort($configured_rates);
  728. $configured_rate = array_shift($configured_rates);
  729.  
  730. if(preg_match("/%$/", $configured_rate)) // Percentage.
  731. {
  732. if(($configured_rate = (float)$configured_rate) > 0)
  733. {
  734. $this_tax = round(($this_sub_total / 100) * $configured_rate, 2);
  735. $this_tax_per = $configured_rate.$ps;
  736. }
  737. else // Else the Tax is 0.00.
  738. {
  739. $this_tax = 0.00; // No Tax.
  740. $this_tax_per = $configured_rate.$ps;
  741. }
  742. }
  743. else if(($configured_rate = (float)$configured_rate) > 0)
  744. {
  745. $this_tax = round($configured_rate, 2);
  746. $this_tax_per = ""; // Flat rate.
  747. }
  748. else // Else the Tax is 0.00.
  749. {
  750. $this_tax = 0.00; // No Tax.
  751. $this_tax_per = ""; // Flat rate.
  752. }
  753. }
  754. }
  755.  
  756. $this_total = $this_sub_total + $this_tax;
  757. }
  758. else // Else the Tax is 0.00.
  759. {
  760. $this_tax = 0.00; // No Tax.
  761. $this_tax_per = ""; // Flat rate.
  762. $this_sub_total = 0.00; // 0.00.
  763. $this_total = 0.00; // 0.00.
  764. }
  765.  
  766. if($this_key === "trial_sub_total")
  767. {
  768. $trial_tax = $this_tax;
  769. $trial_tax_per = $this_tax_per;
  770. $trial_sub_total = $this_sub_total;
  771. $trial_total = $this_total;
  772. }
  773. else if($this_key === "sub_total")
  774. {
  775. $tax = $this_tax;
  776. $tax_per = $this_tax_per;
  777. $sub_total = $this_sub_total;
  778. $total = $this_total;
  779. }
  780. }
  781.  
  782. return array("trial_sub_total" => number_format($trial_sub_total, 2, ".", ""), "sub_total" => number_format($sub_total, 2, ".", ""), "trial_tax" => number_format($trial_tax, 2, ".", ""), "tax" => number_format($tax, 2, ".", ""), "trial_tax_per" => $trial_tax_per, "tax_per" => $tax_per, "trial_total" => number_format($trial_total, 2, ".", ""), "total" => number_format($total, 2, ".", ""), "cur" => $currency, "cur_symbol" => c_ws_plugin__s2member_utils_cur::symbol($currency), "desc" => $desc);
  783. }
  784. /**
  785. * Checks to see if a Coupon Code was supplied, and if so; what does it provide?
  786. *
  787. * @package s2Member\AuthNet
  788. * @since 1.5
  789. *
  790. * @param array $attr An array of Pro Form Attributes.
  791. * @param str $coupon_code Optional. A possible Coupon Code supplied by the Customer.
  792. * @param str $return Optional. Return type. One of `response|attr`. Defaults to `attr`.
  793. * @param array $process Optional. An array of additional processing routines to run here.
  794. * One or more of these values: `affiliates-1px-response|affiliates-silent-post|notifications`.
  795. * @return array|str Original array, with prices and description modified when/if a Coupon Code is accepted.
  796. * Or, if ``$return === "response"``, return a string response, indicating status.
  797. *
  798. * @todo See if it's possible to simplify this routine.
  799. * @todo Add support for tracking Coupon Code usage.
  800. * @todo Add support for a fixed number of uses.
  801. */
  802. public static function authnet_apply_coupon($attr = FALSE, $coupon_code = FALSE, $return = FALSE, $process = FALSE)
  803. {
  804. if(($coupon_code = trim(strtolower($coupon_code))) || ($coupon_code = trim(strtolower($attr["coupon"]))))
  805. if($attr["accept_coupons"] && $GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["pro_coupon_codes"])
  806. {
  807. $cs = c_ws_plugin__s2member_utils_cur::symbol($attr["cc"]);
  808. $tx = (c_ws_plugin__s2member_pro_authnet_utilities::authnet_tax_may_apply()) ? _x(" + tax", "s2member-front", "s2member") : "";
  809. $ps = _x("%", "s2member-front percentage-symbol", "s2member");
  810.  
  811. if(strlen($affiliate_suffix_chars = $GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["pro_affiliate_coupon_code_suffix_chars"]))
  812. if(preg_match("/^(.+?)".preg_quote($affiliate_suffix_chars, "/")."([0-9]+)$/i", $coupon_code, $m))
  813. ($full_coupon_code = $m[0]).($coupon_code = $m[1]).($affiliate_id = $m[2]);
  814. unset /* Just a little housekeeping here. */($affiliate_suffix_chars, $m);
  815.  
  816. foreach(c_ws_plugin__s2member_utils_strings::trim_deep(preg_split("/[\r\n\t]+/", $GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["pro_coupon_codes"])) as $_line)
  817. {
  818. if(($_line = trim($_line, " \r\n\t\0\x0B|")) && is_array($_coupon = preg_split("/\|/", $_line)))
  819. {
  820. $coupon["code"] = (!empty($_coupon[0])) ? trim(strtolower($_coupon[0])) : "";
  821.  
  822. $coupon["percentage"] = (!empty($_coupon[1]) && preg_match("/%/", $_coupon[1])) ? (float)$_coupon[1] : 0;
  823. $coupon["flat-rate"] = (!empty($_coupon[1]) && !preg_match("/%/", $_coupon[1])) ? (float)$_coupon[1] : 0;
  824.  
  825. $coupon["expired"] = (!empty($_coupon[2]) && /* Expired? */ strtotime($_coupon[2]) < time()) ? $_coupon[2] : false;
  826.  
  827. $coupon["directive"] = (!empty($_coupon[3]) && ($_coupon[3] = strtolower($_coupon[3]))) ? preg_replace("/_/", "-", $_coupon[3]) : "all";
  828. $coupon["directive"] = (preg_match("/^(ta-only|ra-only|all)$/", $coupon["directive"])) ? $coupon["directive"] : "all";
  829.  
  830. $coupon["singulars"] = (!empty($_coupon[4]) && ($_coupon[4] = strtolower($_coupon[4])) && $_coupon[4] !== "all") ? $_coupon[4] : "all";
  831. $coupon["singulars"] = ($coupon["singulars"] !== "all") ? preg_split("/[\r\n\t\s;,]+/", trim(preg_replace("/[^0-9,]/", "", $coupon["singulars"]), ",")) : array("all");
  832.  
  833. unset /* Just a little housekeeping here. Unset these temporary variables. */($_line, $_coupon);
  834.  
  835. if($coupon_code === $coupon["code"] && /* And it's NOT yet expired, or lasts forever? */ !$coupon["expired"])
  836. {
  837. if($coupon["singulars"] === array("all")|| in_array($attr["singular"], $coupon["singulars"]))
  838. {
  839. $coupon_accepted = /* Yes, this Coupon Code has been accepted. */ true;
  840.  
  841. if($coupon["flat-rate"]) // If it's a flat-rate Coupon.
  842. {
  843. if(($coupon["directive"] === "ra-only" || $coupon["directive"] === "all") && $attr["sp"])
  844. {
  845. $coupon_applies = /* Applying. */ true;
  846.  
  847. $ta = number_format($attr["ta"], 2, ".", "");
  848. $ta = ($ta >= 0.00) ? $ta : "0.00";
  849.  
  850. $ra = number_format($attr["ra"] - $coupon["flat-rate"], 2, ".", "");
  851. $ra = ($ra >= 0.01) ? $ra : "0.01";
  852.  
  853. $desc = sprintf(_x("COUPON %s off. (Now: %s)", "s2member-front", "s2member"), $cs.number_format($coupon["flat-rate"], 2, ".", ""), $cs.$ra.$tx);
  854. $response = sprintf(_x('<div>Coupon: <strong>%s off</strong>. (Now: <strong>%s</strong>)</div>', "s2member-front", "s2member"), $cs.number_format($coupon["flat-rate"], 2, ".", ""), $cs.$ra.$tx);
  855. }
  856. else if($coupon["directive"] === "ta-only" && $attr["tp"] && !$attr["sp"])
  857. {
  858. $coupon_applies = /* Applying. */ true;
  859.  
  860. $ta = number_format($attr["ta"] - $coupon["flat-rate"], 2, ".", "");
  861. $ta = ($ta >= 0.00) ? $ta : "0.00";
  862.  
  863. $ra = number_format($attr["ra"], 2, ".", "");
  864. $ra = ($ra >= 0.01) ? $ra : "0.01";
  865.  
  866. $desc = sprintf(_x("COUPON %s off. (Now: %s, then %s)", "s2member-front", "s2member"), $cs.number_format($coupon["flat-rate"], 2, ".", ""), $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ta, $attr["tp"]." ".$attr["tt"]).$tx, $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ra, $attr["rp"]." ".$attr["rt"], $attr["rr"]));
  867. $response = sprintf(_x('<div>Coupon: <strong>%s off</strong>. (Now: <strong>%s, then %s</strong>)</div>', "s2member-front", "s2member"), $cs.number_format($coupon["flat-rate"], 2, ".", ""), $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ta, $attr["tp"]." ".$attr["tt"]).$tx, $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ra, $attr["rp"]." ".$attr["rt"], $attr["rr"]));
  868. }
  869. else if($coupon["directive"] === "ra-only" && $attr["tp"] && !$attr["sp"])
  870. {
  871. $coupon_applies = /* Applying. */ true;
  872.  
  873. $ta = number_format($attr["ta"], 2, ".", "");
  874. $ta = ($ta >= 0.00) ? $ta : "0.00";
  875.  
  876. $ra = number_format($attr["ra"] - $coupon["flat-rate"], 2, ".", "");
  877. $ra = ($ra >= 0.01) ? $ra : "0.01";
  878.  
  879. $desc = sprintf(_x("COUPON %s off. (Now: %s, then %s)", "s2member-front", "s2member"), $cs.number_format($coupon["flat-rate"], 2, ".", ""), $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ta, $attr["tp"]." ".$attr["tt"]).$tx, $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ra, $attr["rp"]." ".$attr["rt"], $attr["rr"]));
  880. $response = sprintf(_x('<div>Coupon: <strong>%s off</strong>. (Now: <strong>%s, then %s</strong>)</div>', "s2member-front", "s2member"), $cs.number_format($coupon["flat-rate"], 2, ".", ""), $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ta, $attr["tp"]." ".$attr["tt"]).$tx, $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ra, $attr["rp"]." ".$attr["rt"], $attr["rr"]));
  881. }
  882. else if($coupon["directive"] === "all" && $attr["tp"] && !$attr["sp"])
  883. {
  884. $coupon_applies = /* Applying. */ true;
  885.  
  886. $ta = number_format($attr["ta"] - $coupon["flat-rate"], 2, ".", "");
  887. $ta = ($ta >= 0.00) ? $ta : "0.00";
  888.  
  889. $ra = number_format($attr["ra"] - $coupon["flat-rate"], 2, ".", "");
  890. $ra = ($ra >= 0.01) ? $ra : "0.01";
  891.  
  892. $desc = sprintf(_x("COUPON %s off. (Now: %s, then %s)", "s2member-front", "s2member"), $cs.number_format($coupon["flat-rate"], 2, ".", ""), $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ta, $attr["tp"]." ".$attr["tt"]).$tx, $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ra, $attr["rp"]." ".$attr["rt"], $attr["rr"]));
  893. $response = sprintf(_x('<div>Coupon: <strong>%s off</strong>. (Now: <strong>%s, then %s</strong>)</div>', "s2member-front", "s2member"), $cs.number_format($coupon["flat-rate"], 2, ".", ""), $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ta, $attr["tp"]." ".$attr["tt"]).$tx, $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ra, $attr["rp"]." ".$attr["rt"], $attr["rr"]));
  894. }
  895. else if($coupon["directive"] === "ra-only" && !$attr["tp"] && !$attr["sp"])
  896. {
  897. $coupon_applies = /* Applying. */ true;
  898.  
  899. $ta = number_format($attr["ta"], 2, ".", "");
  900. $ta = ($ta >= 0.00) ? $ta : "0.00";
  901.  
  902. $ra = number_format($attr["ra"] - $coupon["flat-rate"], 2, ".", "");
  903. $ra = ($ra >= 0.01) ? $ra : "0.01";
  904.  
  905. $desc = sprintf(_x("COUPON %s off. (Now: %s)", "s2member-front", "s2member"), $cs.number_format($coupon["flat-rate"], 2, ".", ""), $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ra, $attr["rp"]." ".$attr["rt"], $attr["rr"]).$tx);
  906. $response = sprintf(_x('<div>Coupon: <strong>%s off</strong>. (Now: <strong>%s</strong>)</div>', "s2member-front", "s2member"), $cs.number_format($coupon["flat-rate"], 2, ".", ""), $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ra, $attr["rp"]." ".$attr["rt"], $attr["rr"]).$tx);
  907. }
  908. else if($coupon["directive"] === "all" && !$attr["tp"] && !$attr["sp"])
  909. {
  910. $coupon_applies = /* Applying. */ true;
  911.  
  912. $ta = number_format($attr["ta"] - $coupon["flat-rate"], 2, ".", "");
  913. $ta = ($ta >= 0.00) ? $ta : "0.00";
  914.  
  915. $ra = number_format($attr["ra"] - $coupon["flat-rate"], 2, ".", "");
  916. $ra = ($ra >= 0.01) ? $ra : "0.01";
  917.  
  918. $desc = sprintf(_x("COUPON %s off. (Now: %s)", "s2member-front", "s2member"), $cs.number_format($coupon["flat-rate"], 2, ".", ""), $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ra, $attr["rp"]." ".$attr["rt"], $attr["rr"]).$tx);
  919. $response = sprintf(_x('<div>Coupon: <strong>%s off</strong>. (Now: <strong>%s</strong>)</div>', "s2member-front", "s2member"), $cs.number_format($coupon["flat-rate"], 2, ".", ""), $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ra, $attr["rp"]." ".$attr["rt"], $attr["rr"]).$tx);
  920. }
  921.  
  922. else // Otherwise, we need a default response to display.
  923. $response = _x('<div>Sorry, your Coupon is not applicable.</div>', "s2member-front", "s2member");
  924. }
  925.  
  926. else if($coupon["percentage"]) // Else if it's a percentage.
  927. {
  928. if(($coupon["directive"] === "ra-only" || $coupon["directive"] === "all") && $attr["sp"])
  929. {
  930. $coupon_applies = /* Applying. */ true;
  931.  
  932. $p = ($attr["ta"] / 100) * $coupon["percentage"];
  933. $ta = number_format($attr["ta"], 2, ".", "");
  934. $ta = ($ta >= 0.00) ? $ta : "0.00";
  935.  
  936. $p = ($attr["ra"] / 100) * $coupon["percentage"];
  937. $ra = number_format($attr["ra"] - $p, 2, ".", "");
  938. $ra = ($ra >= 0.01) ? $ra : "0.01";
  939.  
  940. $desc = sprintf(_x("COUPON %s off. (Now: %s)", "s2member-front", "s2member"), number_format($coupon["percentage"], 0).$ps, $cs.$ra.$tx);
  941. $response = sprintf(_x('<div>Coupon: <strong>%s off</strong>. (Now: <strong>%s</strong>)</div>', "s2member-front", "s2member"), number_format($coupon["percentage"], 0).$ps, $cs.$ra.$tx);
  942. }
  943. else if($coupon["directive"] === "ta-only" && $attr["tp"] && !$attr["sp"])
  944. {
  945. $coupon_applies = /* Applying. */ true;
  946.  
  947. $p = ($attr["ta"] / 100) * $coupon["percentage"];
  948. $ta = number_format($attr["ta"] - $p, 2, ".", "");
  949. $ta = ($ta >= 0.00) ? $ta : "0.00";
  950.  
  951. $p = ($attr["ra"] / 100) * $coupon["percentage"];
  952. $ra = number_format($attr["ra"], 2, ".", "");
  953. $ra = ($ra >= 0.01) ? $ra : "0.01";
  954.  
  955. $desc = sprintf(_x("COUPON %s off. (Now: %s, then %s)", "s2member-front", "s2member"), number_format($coupon["percentage"], 0).$ps, $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ta, $attr["tp"]." ".$attr["tt"]).$tx, $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ra, $attr["rp"]." ".$attr["rt"], $attr["rr"]));
  956. $response = sprintf(_x('<div>Coupon: <strong>%s off</strong>. (Now: <strong>%s, then %s</strong>)</div>', "s2member-front", "s2member"), number_format($coupon["percentage"], 0).$ps, $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ta, $attr["tp"]." ".$attr["tt"]).$tx, $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ra, $attr["rp"]." ".$attr["rt"], $attr["rr"]));
  957. }
  958. else if($coupon["directive"] === "ra-only" && $attr["tp"] && !$attr["sp"])
  959. {
  960. $coupon_applies = /* Applying. */ true;
  961.  
  962. $p = ($attr["ta"] / 100) * $coupon["percentage"];
  963. $ta = number_format($attr["ta"], 2, ".", "");
  964. $ta = ($ta >= 0.00) ? $ta : "0.00";
  965.  
  966. $p = ($attr["ra"] / 100) * $coupon["percentage"];
  967. $ra = number_format($attr["ra"] - $p, 2, ".", "");
  968. $ra = ($ra >= 0.01) ? $ra : "0.01";
  969.  
  970. $desc = sprintf(_x("COUPON %s off. (Now: %s, then %s)", "s2member-front", "s2member"), number_format($coupon["percentage"], 0).$ps, $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ta, $attr["tp"]." ".$attr["tt"]).$tx, $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ra, $attr["rp"]." ".$attr["rt"], $attr["rr"]));
  971. $response = sprintf(_x('<div>Coupon: <strong>%s off</strong>. (Now: <strong>%s, then %s</strong>)</div>', "s2member-front", "s2member"), number_format($coupon["percentage"], 0).$ps, $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ta, $attr["tp"]." ".$attr["tt"]).$tx, $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ra, $attr["rp"]." ".$attr["rt"], $attr["rr"]));
  972. }
  973. else if($coupon["directive"] === "all" && $attr["tp"] && !$attr["sp"])
  974. {
  975. $coupon_applies = /* Applying. */ true;
  976.  
  977. $p = ($attr["ta"] / 100) * $coupon["percentage"];
  978. $ta = number_format($attr["ta"] - $p, 2, ".", "");
  979. $ta = ($ta >= 0.00) ? $ta : "0.00";
  980.  
  981. $p = ($attr["ra"] / 100) * $coupon["percentage"];
  982. $ra = number_format($attr["ra"] - $p, 2, ".", "");
  983. $ra = ($ra >= 0.01) ? $ra : "0.01";
  984.  
  985. $desc = sprintf(_x("COUPON %s off. (Now: %s, then %s)", "s2member-front", "s2member"), number_format($coupon["percentage"], 0).$ps, $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ta, $attr["tp"]." ".$attr["tt"]).$tx, $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ra, $attr["rp"]." ".$attr["rt"], $attr["rr"]));
  986. $response = sprintf(_x('<div>Coupon: <strong>%s off</strong>. (Now: <strong>%s, then %s</strong>)</div>', "s2member-front", "s2member"), number_format($coupon["percentage"], 0).$ps, $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ta, $attr["tp"]." ".$attr["tt"]).$tx, $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ra, $attr["rp"]." ".$attr["rt"], $attr["rr"]));
  987. }
  988. else if($coupon["directive"] === "ra-only" && !$attr["tp"] && !$attr["sp"])
  989. {
  990. $coupon_applies = /* Applying. */ true;
  991.  
  992. $p = ($attr["ta"] / 100) * $coupon["percentage"];
  993. $ta = number_format($attr["ta"], 2, ".", "");
  994. $ta = ($ta >= 0.00) ? $ta : "0.00";
  995.  
  996. $p = ($attr["ra"] / 100) * $coupon["percentage"];
  997. $ra = number_format($attr["ra"] - $p, 2, ".", "");
  998. $ra = ($ra >= 0.01) ? $ra : "0.01";
  999.  
  1000. $desc = sprintf(_x("COUPON %s off. (Now: %s)", "s2member-front", "s2member"), number_format($coupon["percentage"], 0).$ps, $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ra, $attr["rp"]." ".$attr["rt"], $attr["rr"]).$tx);
  1001. $response = sprintf(_x('<div>Coupon: <strong>%s off</strong>. (Now: <strong>%s</strong>)</div>', "s2member-front", "s2member"), number_format($coupon["percentage"], 0).$ps, $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ra, $attr["rp"]." ".$attr["rt"], $attr["rr"]).$tx);
  1002. }
  1003. else if($coupon["directive"] === "all" && !$attr["tp"] && !$attr["sp"])
  1004. {
  1005. $coupon_applies = /* Applying. */ true;
  1006.  
  1007. $p = ($attr["ta"] / 100) * $coupon["percentage"];
  1008. $ta = number_format($attr["ta"] - $p, 2, ".", "");
  1009. $ta = ($ta >= 0.00) ? $ta : "0.00";
  1010.  
  1011. $p = ($attr["ra"] / 100) * $coupon["percentage"];
  1012. $ra = number_format($attr["ra"] - $p, 2, ".", "");
  1013. $ra = ($ra >= 0.01) ? $ra : "0.01";
  1014.  
  1015. $desc = sprintf(_x("COUPON %s off. (Now: %s)", "s2member-front", "s2member"), number_format($coupon["percentage"], 0).$ps, $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ra, $attr["rp"]." ".$attr["rt"], $attr["rr"]).$tx);
  1016. $response = sprintf(_x('<div>Coupon: <strong>%s off</strong>. (Now: <strong>%s</strong>)</div>', "s2member-front", "s2member"), number_format($coupon["percentage"], 0).$ps, $cs.c_ws_plugin__s2member_utils_time::amount_period_term($ra, $attr["rp"]." ".$attr["rt"], $attr["rr"]).$tx);
  1017. }
  1018.  
  1019. else // Otherwise, we need a default response to display.
  1020. $response = _x('<div>Sorry, your Coupon is not applicable.</div>', "s2member-front", "s2member");
  1021. }
  1022.  
  1023. else // Else there was no discount applied at all.
  1024. $response = sprintf(_x('<div>Coupon: <strong>%s0.00 off</strong>.</div>', "s2member-front", "s2member"), $cs);
  1025. }
  1026.  
  1027. else // Otherwise, we need a response that indicates not applicable for this purchase.
  1028. $response = _x('<div>Sorry, your Coupon cannot be applied to this particular purchase.</div>', "s2member-front", "s2member");
  1029. }
  1030.  
  1031. else if($coupon_code === $coupon["code"] && $coupon["expired"])
  1032. $response = sprintf(_x('<div>Sorry, your Coupon <strong>expired</strong>: <em>%s</em>.</div>', "s2member-front", "s2member"), $coupon["expired"]);
  1033. }
  1034. }
  1035.  
  1036. if(isset($coupon_applies, $desc) && $coupon_applies /* Need to modify the description dynamically? */)
  1037. // translators: `%1$s` is new price/description, after coupon applied. `%2$s` is original description.
  1038. $attr["desc"] = sprintf(_x('%1$s ~ ORIGINALLY: %2$s', "s2member-front", "s2member"), $desc, $attr["desc"]);
  1039.  
  1040. $attr["ta"] = (isset($coupon_applies, $ta) && $coupon_applies) ? /* Do we have a new Trial Amount? */ $ta : $attr["ta"];
  1041. $attr["ra"] = (isset($coupon_applies, $ra) && $coupon_applies) ? /* A new Regular Amount? */ $ra : $attr["ra"];
  1042.  
  1043. if(is_array($process) && /* Processing affiliates? */ (in_array("affiliates-silent-post", $process) || in_array("affiliates-1px-response", $process)))
  1044. if(isset($coupon_applies) && $coupon_applies && /* Now, is this an Affiliate Coupon Code? Contains an affiliate ID? */ !empty($affiliate_id))
  1045. if(empty($_COOKIE["idev"]) /* Special consideration here. iDevAffiliate® must NOT have already tracked this customer. */)
  1046. if(($_urls = $GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["pro_affiliate_coupon_code_tracking_urls"]))
  1047.  
  1048. foreach(preg_split("/[\r\n\t]+/", $_urls) as $_url /* Notify each of the URLs. */)
  1049.  
  1050. if(($_url = preg_replace("/%%full_coupon_code%%/i", c_ws_plugin__s2member_utils_strings::esc_ds(urlencode($full_coupon_code)), $_url)))
  1051. if(($_url = preg_replace("/%%coupon_code%%/i", c_ws_plugin__s2member_utils_strings::esc_ds(urlencode($coupon_code)), $_url)))
  1052. if(($_url = preg_replace("/%%(?:coupon_affiliate_id|affiliate_id)%%/i", c_ws_plugin__s2member_utils_strings::esc_ds(urlencode($affiliate_id)), $_url)))
  1053. if(($_url = preg_replace("/%%user_ip%%/i", c_ws_plugin__s2member_utils_strings::esc_ds(urlencode($_SERVER["REMOTE_ADDR"])), $_url)))
  1054. {
  1055. if(($_url = trim(preg_replace("/%%(.+?)%%/i", "", $_url))) /* Cleanup any remaining Replacement Codes. */)
  1056.  
  1057. if(!($_r = 0) && ($_url = preg_replace("/^silent-php\|/i", "", $_url, 1, $_r)) && $_r && in_array /* Processing? */("affiliates-silent-post", $process))
  1058. c_ws_plugin__s2member_utils_urls::remote /* Post silently via PHP. Relies on IP tracking. */($_url, false, array("blocking" => false));
  1059.  
  1060. else if(!($_r = 0) && ($_url = preg_replace("/^img-1px\|/i", "", $_url, 1, $_r)) && $_r && in_array("affiliates-1px-response", $process))
  1061. if( /* Now, we MUST also have a ``$response``, and MUST be returning ``$response``. */!empty($response) && $return === "response")
  1062. $response .= "\n".'<img src="'.esc_attr($_url).'" style="width:0; height:0; border:0;" alt="" />';
  1063. }
  1064. unset /* Just a little housekeeping here. Unset these variables. */($_urls, $_url, $_r);
  1065.  
  1066. if(empty($response)) // Is ``$response`` NOT set by now? If it's not, we need a default ``$response``.
  1067. $response = _x('<div>Sorry, your Coupon is N/A, invalid or expired.</div>', "s2member-front", "s2member");
  1068. }
  1069. else // Otherwise, we need a default response to display.
  1070. $response = _x('<div>Sorry, your Coupon is N/A, invalid or expired.</div>', "s2member-front", "s2member");
  1071.  
  1072. $attr["_coupon_applies"] = (isset($coupon_applies) && $coupon_applies) ? /* Coupon applies? */ "1" : "0";
  1073. $attr["_coupon_code"] = (isset($coupon_applies) && $coupon_applies) ? /* Coupon applies? */ $coupon_code : "";
  1074. $attr["_full_coupon_code"] = (isset($coupon_applies) && $coupon_applies && !empty($full_coupon_code)) ? $full_coupon_code : ((isset($coupon_applies) && $coupon_applies) ? $coupon_code : "");
  1075. $attr["_coupon_affiliate_id"] = (isset($coupon_applies) && $coupon_applies && !empty($affiliate_id) && empty($_COOKIE["idev"])) ? $affiliate_id : "";
  1076.  
  1077. return ( /* Returning ``$response``? */$return === "response") ? $response : $attr;
  1078. }
  1079. }
  1080. }
  1081. ?>

pro\s2member-pro\includes\classes\gateways\authnet\authnet-utilities.inc.php

Source Code Documentation