simple-payments.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. <?php
  2. /**
  3. * Disable direct access/execution to/of the widget code.
  4. */
  5. if ( ! defined( 'ABSPATH' ) ) {
  6. exit;
  7. }
  8. if ( ! class_exists( 'Jetpack_Simple_Payments_Widget' ) ) {
  9. /**
  10. * Simple Payments Button
  11. *
  12. * Display a Simple Payment Button as a Widget.
  13. */
  14. class Jetpack_Simple_Payments_Widget extends WP_Widget {
  15. // https://developer.paypal.com/docs/integration/direct/rest/currency-codes/
  16. private static $supported_currency_list = array(
  17. 'USD' => '$',
  18. 'GBP' => '&#163;',
  19. 'JPY' => '&#165;',
  20. 'BRL' => 'R$',
  21. 'EUR' => '&#8364;',
  22. 'NZD' => 'NZ$',
  23. 'AUD' => 'A$',
  24. 'CAD' => 'C$',
  25. 'INR' => '₹',
  26. 'ILS' => '₪',
  27. 'RUB' => '₽',
  28. 'MXN' => 'MX$',
  29. 'SEK' => 'Skr',
  30. 'HUF' => 'Ft',
  31. 'CHF' => 'CHF',
  32. 'CZK' => 'Kč',
  33. 'DKK' => 'Dkr',
  34. 'HKD' => 'HK$',
  35. 'NOK' => 'Kr',
  36. 'PHP' => '₱',
  37. 'PLN' => 'PLN',
  38. 'SGD' => 'S$',
  39. 'TWD' => 'NT$',
  40. 'THB' => '฿',
  41. );
  42. /**
  43. * Constructor.
  44. */
  45. function __construct() {
  46. parent::__construct(
  47. 'jetpack_simple_payments_widget',
  48. /** This filter is documented in modules/widgets/facebook-likebox.php */
  49. apply_filters( 'jetpack_widget_name', __( 'Simple Payments', 'jetpack' ) ),
  50. array(
  51. 'classname' => 'jetpack-simple-payments',
  52. 'description' => __( 'Add a Simple Payment Button as a Widget.', 'jetpack' ),
  53. 'customize_selective_refresh' => true,
  54. )
  55. );
  56. global $pagenow;
  57. if ( is_customize_preview() || 'widgets.php' === $pagenow ) {
  58. add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_styles' ) );
  59. }
  60. $jetpack_simple_payments = Jetpack_Simple_Payments::getInstance();
  61. if ( is_customize_preview() && $jetpack_simple_payments->is_enabled_jetpack_simple_payments() ) {
  62. add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) );
  63. add_filter( 'customize_refresh_nonces', array( $this, 'filter_nonces' ) );
  64. add_action( 'wp_ajax_customize-jetpack-simple-payments-buttons-get', array( $this, 'ajax_get_payment_buttons' ) );
  65. add_action( 'wp_ajax_customize-jetpack-simple-payments-button-save', array( $this, 'ajax_save_payment_button' ) );
  66. add_action( 'wp_ajax_customize-jetpack-simple-payments-button-delete', array( $this, 'ajax_delete_payment_button' ) );
  67. }
  68. if ( is_active_widget( false, false, $this->id_base ) || is_customize_preview() ) {
  69. add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_style' ) );
  70. }
  71. }
  72. /**
  73. * Return an associative array of default values.
  74. *
  75. * These values are used in new widgets.
  76. *
  77. * @return array Default values for the widget options.
  78. */
  79. private function defaults() {
  80. $current_user = wp_get_current_user();
  81. $default_product_id = $this->get_first_product_id();
  82. return array(
  83. 'title' => '',
  84. 'product_post_id' => $default_product_id,
  85. 'form_action' => '',
  86. 'form_product_id' => 0,
  87. 'form_product_title' => '',
  88. 'form_product_description' => '',
  89. 'form_product_image_id' => 0,
  90. 'form_product_image_src' => '',
  91. 'form_product_currency' => '',
  92. 'form_product_price' => '',
  93. 'form_product_multiple' => '',
  94. 'form_product_email' => $current_user->user_email,
  95. );
  96. }
  97. /**
  98. * Adds a nonce for customizing menus.
  99. *
  100. * @param array $nonces Array of nonces.
  101. * @return array $nonces Modified array of nonces.
  102. */
  103. function filter_nonces( $nonces ) {
  104. $nonces['customize-jetpack-simple-payments'] = wp_create_nonce( 'customize-jetpack-simple-payments' );
  105. return $nonces;
  106. }
  107. function enqueue_style() {
  108. wp_enqueue_style( 'jetpack-simple-payments-widget-style', plugins_url( 'simple-payments/style.css', __FILE__ ), array(), '20180518' );
  109. }
  110. function admin_enqueue_styles() {
  111. wp_enqueue_style( 'jetpack-simple-payments-widget-customizer', plugins_url( 'simple-payments/customizer.css', __FILE__ ) );
  112. }
  113. function admin_enqueue_scripts() {
  114. wp_enqueue_media();
  115. wp_enqueue_script( 'jetpack-simple-payments-widget-customizer', plugins_url( '/simple-payments/customizer.js', __FILE__ ), array( 'jquery' ), false, true );
  116. wp_localize_script( 'jetpack-simple-payments-widget-customizer', 'jpSimplePaymentsStrings', array(
  117. 'deleteConfirmation' => __( 'Are you sure you want to delete this item? It will be disabled and removed from all locations where it currently appears.', 'jetpack' )
  118. ) );
  119. }
  120. public function ajax_get_payment_buttons() {
  121. if ( ! check_ajax_referer( 'customize-jetpack-simple-payments', 'customize-jetpack-simple-payments-nonce', false ) ) {
  122. wp_send_json_error( 'bad_nonce', 400 );
  123. }
  124. if ( ! current_user_can( 'customize' ) ) {
  125. wp_send_json_error( 'customize_not_allowed', 403 );
  126. }
  127. $post_type_object = get_post_type_object( Jetpack_Simple_Payments::$post_type_product );
  128. if ( ! current_user_can( $post_type_object->cap->create_posts ) || ! current_user_can( $post_type_object->cap->publish_posts ) ) {
  129. wp_send_json_error( 'insufficient_post_permissions', 403 );
  130. }
  131. $product_posts = get_posts( array(
  132. 'numberposts' => 100,
  133. 'orderby' => 'date',
  134. 'post_type' => Jetpack_Simple_Payments::$post_type_product,
  135. 'post_status' => 'publish',
  136. ) );
  137. $formatted_products = array_map( array( $this, 'format_product_post_for_ajax_reponse' ), $product_posts );
  138. wp_send_json_success( $formatted_products );
  139. }
  140. public function format_product_post_for_ajax_reponse( $product_post ) {
  141. return array(
  142. 'ID' => $product_post->ID,
  143. 'post_title' => $product_post->post_title,
  144. );
  145. }
  146. public function ajax_save_payment_button() {
  147. if ( ! check_ajax_referer( 'customize-jetpack-simple-payments', 'customize-jetpack-simple-payments-nonce', false ) ) {
  148. wp_send_json_error( 'bad_nonce', 400 );
  149. }
  150. if ( ! current_user_can( 'customize' ) ) {
  151. wp_send_json_error( 'customize_not_allowed', 403 );
  152. }
  153. $post_type_object = get_post_type_object( Jetpack_Simple_Payments::$post_type_product );
  154. if ( ! current_user_can( $post_type_object->cap->create_posts ) || ! current_user_can( $post_type_object->cap->publish_posts ) ) {
  155. wp_send_json_error( 'insufficient_post_permissions', 403 );
  156. }
  157. if ( empty( $_POST['params'] ) || ! is_array( $_POST['params'] ) ) {
  158. wp_send_json_error( 'missing_params', 400 );
  159. }
  160. $params = wp_unslash( $_POST['params'] );
  161. $errors = $this->validate_ajax_params( $params );
  162. if ( ! empty( $errors->errors ) ) {
  163. wp_send_json_error( $errors );
  164. }
  165. $product_post_id = isset( $params['product_post_id'] ) ? intval( $params['product_post_id'] ) : 0;
  166. $product_post = array(
  167. 'ID' => $product_post_id,
  168. 'post_type' => Jetpack_Simple_Payments::$post_type_product,
  169. 'post_status' => 'publish',
  170. 'post_title' => $params['post_title'],
  171. 'post_content' => $params['post_content'],
  172. '_thumbnail_id' => ! empty( $params['image_id'] ) ? $params['image_id'] : -1,
  173. 'meta_input' => array(
  174. 'spay_currency' => $params['currency'],
  175. 'spay_price' => $params['price'],
  176. 'spay_multiple' => isset( $params['multiple'] ) ? intval( $params['multiple'] ) : 0,
  177. 'spay_email' => is_email( $params['email'] ),
  178. ),
  179. );
  180. if ( empty( $product_post_id ) ) {
  181. $product_post_id = wp_insert_post( $product_post );
  182. } else {
  183. $product_post_id = wp_update_post( $product_post );
  184. }
  185. if ( ! $product_post_id || is_wp_error( $product_post_id ) ) {
  186. wp_send_json_error( $product_post_id );
  187. }
  188. $tracks_properties = array(
  189. 'id' => $product_post_id,
  190. 'currency' => $params['currency'],
  191. 'price' => $params['price']
  192. );
  193. if ( 0 === $product_post['ID'] ) {
  194. $this->record_event( 'created', 'create', $tracks_properties );
  195. } else {
  196. $this->record_event( 'updated', 'update', $tracks_properties );
  197. }
  198. wp_send_json_success( array(
  199. 'product_post_id' => $product_post_id,
  200. 'product_post_title' => $params['post_title'],
  201. ) );
  202. }
  203. public function ajax_delete_payment_button() {
  204. if ( ! check_ajax_referer( 'customize-jetpack-simple-payments', 'customize-jetpack-simple-payments-nonce', false ) ) {
  205. wp_send_json_error( 'bad_nonce', 400 );
  206. }
  207. if ( ! current_user_can( 'customize' ) ) {
  208. wp_send_json_error( 'customize_not_allowed', 403 );
  209. }
  210. if ( empty( $_POST['params'] ) || ! is_array( $_POST['params'] ) ) {
  211. wp_send_json_error( 'missing_params', 400 );
  212. }
  213. $params = wp_unslash( $_POST['params'] );
  214. $illegal_params = array_diff( array_keys( $params ), array( 'product_post_id' ) );
  215. if ( ! empty( $illegal_params ) ) {
  216. wp_send_json_error( 'illegal_params', 400 );
  217. }
  218. $product_id = ( int ) $params['product_post_id'];
  219. $product_post = get_post( $product_id );
  220. $return = array( 'status' => $product_post->post_status );
  221. wp_delete_post( $product_id, true );
  222. $status = get_post_status( $product_id );
  223. if ( false === $status ) {
  224. $return['status'] = 'deleted';
  225. }
  226. $this->record_event( 'deleted', 'delete', array( 'id' => $product_id ) );
  227. wp_send_json_success( $return );
  228. }
  229. /**
  230. * Returns the number of decimal places on string representing a price.
  231. *
  232. * @param string $number Price to check.
  233. * @return number number of decimal places.
  234. */
  235. private function get_decimal_places( $number ) {
  236. $parts = explode( '.', $number );
  237. if ( count( $parts ) > 2 ) {
  238. return null;
  239. }
  240. return isset( $parts[1] ) ? strlen( $parts[1] ) : 0;
  241. }
  242. public function validate_ajax_params( $params ) {
  243. $errors = new WP_Error();
  244. $illegal_params = array_diff( array_keys( $params ), array( 'product_post_id', 'post_title', 'post_content', 'image_id', 'currency', 'price', 'multiple', 'email' ) );
  245. if ( ! empty( $illegal_params ) ) {
  246. $errors->add( 'illegal_params', __( 'Invalid parameters.', 'jetpack' ) );
  247. }
  248. if ( empty( $params['post_title'] ) ) {
  249. $errors->add( 'post_title', __( "People need to know what they're paying for! Please add a brief title.", 'jetpack' ) );
  250. }
  251. if ( empty( $params['price'] ) || ! is_numeric( $params['price'] ) || floatval( $params['price'] ) <= 0 ) {
  252. $errors->add( 'price', __( 'Everything comes with a price tag these days. Please add a your product price.', 'jetpack' ) );
  253. }
  254. // Japan's Yen is the only supported currency with a zero decimal precision.
  255. $precision = strtoupper( $params['currency'] ) === 'JPY' ? 0 : 2;
  256. $price_decimal_places = $this->get_decimal_places( $params['price'] );
  257. if ( is_null( $price_decimal_places ) || $price_decimal_places > $precision ) {
  258. $errors->add( 'price', __( 'Invalid price', 'jetpack' ) );
  259. }
  260. if ( empty( $params['email'] ) || ! is_email( $params['email'] ) ) {
  261. $errors->add( 'email', __( 'We want to make sure payments reach you, so please add an email address.', 'jetpack' ) );
  262. }
  263. return $errors;
  264. }
  265. function get_first_product_id() {
  266. $product_posts = get_posts( array(
  267. 'numberposts' => 1,
  268. 'orderby' => 'date',
  269. 'post_type' => Jetpack_Simple_Payments::$post_type_product,
  270. 'post_status' => 'publish',
  271. ) );
  272. return ! empty( $product_posts ) ? $product_posts[0]->ID : null;
  273. }
  274. /**
  275. * Front-end display of widget.
  276. *
  277. * @see WP_Widget::widget()
  278. *
  279. * @param array $args Widget arguments.
  280. * @param array $instance Saved values from database.
  281. */
  282. function widget( $args, $instance ) {
  283. $instance = wp_parse_args( $instance, $this->defaults() );
  284. echo $args['before_widget'];
  285. /** This filter is documented in core/src/wp-includes/default-widgets.php */
  286. $title = apply_filters( 'widget_title', $instance['title'] );
  287. if ( ! empty( $title ) ) {
  288. echo $args['before_title'] . $title . $args['after_title'];
  289. }
  290. echo '<div class="jetpack-simple-payments-content">';
  291. if ( ! empty( $instance['form_action'] ) && in_array( $instance['form_action'], array( 'add', 'edit' ) ) && is_customize_preview() ) {
  292. require( dirname( __FILE__ ) . '/simple-payments/widget.php' );
  293. } else {
  294. $jsp = Jetpack_Simple_Payments::getInstance();
  295. $simple_payments_button = $jsp->parse_shortcode( array(
  296. 'id' => $instance['product_post_id'],
  297. ) );
  298. if ( ! is_null( $simple_payments_button ) || is_customize_preview() ) {
  299. echo $simple_payments_button;
  300. }
  301. }
  302. echo '</div><!--simple-payments-->';
  303. echo $args['after_widget'];
  304. /** This action is already documented in modules/widgets/gravatar-profile.php */
  305. do_action( 'jetpack_stats_extra', 'widget_view', 'simple_payments' );
  306. }
  307. /**
  308. * Gets the latests field value from either the old instance or the new instance.
  309. *
  310. * @param array $mixed Array of values for the new form instance.
  311. * @param array $mixed Array of values for the old form instance.
  312. * @return mixed $mixed Field value.
  313. */
  314. private function get_latest_field_value( $new_instance, $old_instance, $field) {
  315. return ! empty( $new_instance[ $field ] )
  316. ? sanitize_text_field( $new_instance[ $field ] )
  317. : $old_instance[ $field ];
  318. }
  319. /**
  320. * Gets the product fields from the product post. If no post found
  321. * it returns the default values.
  322. *
  323. * @param int Product Post ID.
  324. * @return array $fields Product Fields from the Product Post.
  325. */
  326. private function get_product_from_post( $product_post_id ) {
  327. $product_post = get_post( $product_post_id );
  328. $form_product_id = $product_post_id;
  329. if( ! empty( $product_post ) ) {
  330. $form_product_image_id = get_post_thumbnail_id( $product_post_id );
  331. return array(
  332. 'form_product_id' => $form_product_id,
  333. 'form_product_title' => get_the_title( $product_post ),
  334. 'form_product_description' => $product_post->post_content,
  335. 'form_product_image_id' => $form_product_image_id,
  336. 'form_product_image_src' => wp_get_attachment_image_url( $form_product_image_id, 'thumbnail' ),
  337. 'form_product_currency' => get_post_meta( $product_post_id, 'spay_currency', true ),
  338. 'form_product_price' => get_post_meta( $product_post_id, 'spay_price', true ),
  339. 'form_product_multiple' => get_post_meta( $product_post_id, 'spay_multiple', true ) || '0',
  340. 'form_product_email' => get_post_meta( $product_post_id, 'spay_email', true ),
  341. );
  342. }
  343. return $this->defaults();
  344. }
  345. /**
  346. * Record a Track event and bump a MC stat.
  347. *
  348. * @param string $stat_name
  349. * @param string $event_action
  350. * @param array $event_properties
  351. */
  352. private function record_event( $stat_name, $event_action, $event_properties = array() ) {
  353. $current_user = wp_get_current_user();
  354. // `bumps_stats_extra` only exists on .com
  355. if ( function_exists( 'bump_stats_extras' ) ) {
  356. require_lib( 'tracks/client' );
  357. tracks_record_event( $current_user, 'simple_payments_button_' . $event_action, $event_properties );
  358. /** This action is documented in modules/widgets/social-media-icons.php */
  359. do_action( 'jetpack_bump_stats_extra', 'jetpack-simple_payments', $stat_name );
  360. return;
  361. }
  362. jetpack_tracks_record_event( $current_user, 'jetpack_wpa_simple_payments_button_' . $event_action, $event_properties );
  363. $jetpack = Jetpack::init();
  364. // $jetpack->stat automatically prepends the stat group with 'jetpack-'
  365. $jetpack->stat( 'simple_payments', $stat_name ) ;
  366. $jetpack->do_stats( 'server_side' );
  367. }
  368. /**
  369. * Sanitize widget form values as they are saved.
  370. *
  371. * @see WP_Widget::update()
  372. *
  373. * @param array $new_instance Values just sent to be saved.
  374. * @param array $old_instance Previously saved values from database.
  375. *
  376. * @return array Updated safe values to be saved.
  377. */
  378. function update( $new_instance, $old_instance ) {
  379. $defaults = $this->defaults();
  380. //do not overrite `product_post_id` for `$new_instance` with the defaults
  381. $new_instance = wp_parse_args( $new_instance, array_diff_key( $defaults, array( 'product_post_id' => 0 ) ) );
  382. $old_instance = wp_parse_args( $old_instance, $defaults );
  383. $required_widget_props = array(
  384. 'title' => $this->get_latest_field_value( $new_instance, $old_instance, 'title' ),
  385. 'product_post_id' => $this->get_latest_field_value( $new_instance, $old_instance, 'product_post_id' ),
  386. 'form_action' => $this->get_latest_field_value( $new_instance, $old_instance, 'form_action' ),
  387. );
  388. if ( strcmp( $new_instance['form_action'], $old_instance['form_action'] ) !== 0 ) {
  389. if ( $new_instance['form_action'] == 'edit' ) {
  390. return array_merge( $this->get_product_from_post( ( int ) $old_instance['product_post_id'] ), $required_widget_props );
  391. }
  392. if ( $new_instance['form_action'] == 'clear' ) {
  393. return array_merge( $this->defaults(), $required_widget_props );
  394. }
  395. }
  396. $form_product_image_id = (int) $new_instance['form_product_image_id'];
  397. $form_product_email = ! empty( $new_instance['form_product_email'] )
  398. ? sanitize_text_field( $new_instance['form_product_email'] )
  399. : $defaults['form_product_email'];
  400. return array_merge( $required_widget_props, array(
  401. 'form_product_id' => ( int ) $new_instance['form_product_id'],
  402. 'form_product_title' => sanitize_text_field( $new_instance['form_product_title'] ),
  403. 'form_product_description' => sanitize_text_field( $new_instance['form_product_description'] ),
  404. 'form_product_image_id' => $form_product_image_id,
  405. 'form_product_image_src' => wp_get_attachment_image_url( $form_product_image_id, 'thumbnail' ),
  406. 'form_product_currency' => sanitize_text_field( $new_instance['form_product_currency'] ),
  407. 'form_product_price' => sanitize_text_field( $new_instance['form_product_price'] ),
  408. 'form_product_multiple' => sanitize_text_field( $new_instance['form_product_multiple'] ),
  409. 'form_product_email' => $form_product_email,
  410. ) );
  411. }
  412. /**
  413. * Back-end widget form.
  414. *
  415. * @see WP_Widget::form()
  416. *
  417. * @param array $instance Previously saved values from database.
  418. */
  419. function form( $instance ) {
  420. $jetpack_simple_payments = Jetpack_Simple_Payments::getInstance();
  421. if ( ! $jetpack_simple_payments->is_enabled_jetpack_simple_payments() ) {
  422. require dirname( __FILE__ ) . '/simple-payments/admin-warning.php';
  423. return;
  424. }
  425. $instance = wp_parse_args( $instance, $this->defaults() );
  426. $product_posts = get_posts( array(
  427. 'numberposts' => 100,
  428. 'orderby' => 'date',
  429. 'post_type' => Jetpack_Simple_Payments::$post_type_product,
  430. 'post_status' => 'publish',
  431. ) );
  432. require dirname( __FILE__ ) . '/simple-payments/form.php';
  433. }
  434. }
  435. // Register Jetpack_Simple_Payments_Widget widget.
  436. function register_widget_jetpack_simple_payments() {
  437. if ( ! class_exists( 'Jetpack_Simple_Payments' ) ) {
  438. return;
  439. }
  440. $jetpack_simple_payments = Jetpack_Simple_Payments::getInstance();
  441. if ( ! $jetpack_simple_payments->is_enabled_jetpack_simple_payments() ) {
  442. return;
  443. }
  444. register_widget( 'Jetpack_Simple_Payments_Widget' );
  445. }
  446. add_action( 'widgets_init', 'register_widget_jetpack_simple_payments' );
  447. }