· 9 years ago · Jul 06, 2017, 09:40 AM
1<?php
2/*
3Plugin Name: Opinahjo Members
4Description: Opinahjo member and order functionality
5Author: Opinahjo
6Version: 0.8
7Text Domain: opinahjo-members
8*/
9/**
10 * @package Opinahjo_Members
11 * @version 0.8
12 */
13/* admin init
14if( !is_plugin_active( 'opinahjo-common/opinahjo-common.php' ) ) {
15 die('This plugin builds on Opinahjo Common. Not active, giving up.');
16} */
17
18function plugin_init() {
19 $plugin_dir = basename(dirname(__FILE__));
20 load_plugin_textdomain( 'opinahjo-members', false, $plugin_dir.'/languages/' );
21}
22add_action('plugins_loaded', 'plugin_init');
23
24require_once( 'script_pipedrive.php' );
25
26/* Removing some old PMPro stuff from profiles and members list */
27remove_action( 'show_user_profile', 'pmpro_membership_level_profile_fields' );
28remove_action( 'edit_user_profile', 'pmpro_membership_level_profile_fields' );
29
30// THESE DON'T SEEM TO WORK
31// remove_filter( 'manage_users_columns', 'pmpro_manage_users_columns', 100 );
32// remove_filter( 'manage_users_custom_column', 'pmpro_manage_users_custom_column', 100 );
33
34add_filter('manage_users_columns', 'opmem_manage_users_columns');
35function opmem_manage_users_columns($columns)
36{
37 $columns['opmem_membership_level'] = __('Package', 'opinahjo-members');
38 return $columns;
39}
40
41add_filter( 'manage_users_custom_column', 'opmem_manage_users_custom_column', 10, 3);
42function opmem_manage_users_custom_column($column_data, $column_name, $user_id) {
43
44 if($column_name == 'opmem_membership_level')
45 {
46 $user_package = opmem_get_user_basic_package($user_id, true);
47 if($user_package !== false && !empty($user_package))
48 {
49 $column_data = $user_package['package_name'];
50 }
51 else
52 {
53 $column_data = __('None', 'pmpro');
54 }
55 }
56 return $column_data;
57}
58
59/**
60 * Defining some values for billing and Procountor
61 */
62if ( !defined('OPMEM_INVOICE_PATH' ) )
63{
64 /* Invoice paths for Procountor's XML saving */
65 if(strpos($_SERVER['HTTP_HOST'], '.dev'))
66 {
67 define( 'OPMEM_INVOICE_PATH', '/Users/heikki/invoices/' );
68 $procountor_secret = 'L-T67kbW5ZBX';
69 }
70 elseif(strpos($_SERVER['HTTP_HOST'], 'dev1.'))
71 {
72 define( 'OPMEM_INVOICE_PATH', '/var/www/invoices/' );
73 $procountor_secret = 'L-T67kbW5ZBX';
74 }
75 else
76 {
77 define( 'OPMEM_INVOICE_PATH', '/var/www/invoices/' );
78 $procountor_secret = 'a4swXu5GxpDf';
79 }
80}
81
82/**
83 * Set up the site configuration fields. These are essential for the billing to work properly.
84 */
85if(function_exists("register_field_group"))
86{
87 register_field_group(array (
88 'id' => 'acf_site-configuration',
89 'title' => 'Site configuration',
90 'fields' => array (
91 array (
92 'key' => 'field_34633tg4534ge3',
93 'label' => 'Billing country',
94 'name' => 'billing_country',
95 'type' => 'select',
96 'choices' => array(
97 '' => '- Required -',
98 'FI' => 'Finland',
99 'NO' => 'Norway',
100 'SE' => 'Sweden',
101 ),
102 'instructions' => 'Enables/disables some of the country-specific features in invoicing.',
103 'default_value' => '',
104 'placeholder' => '- Required -',
105 'prepend' => '',
106 'append' => '',
107 'formatting' => 'html',
108 'maxlength' => '',
109 ),
110 array (
111 'key' => 'field_6e3y4y6446h34',
112 'label' => 'Default billing language',
113 'name' => 'billing_language',
114 'type' => 'select',
115 'choices' => array(
116 '' => '- Required -',
117 'FINNISH' => 'Finnish',
118 'NORWEGIAN' => 'Norwegian',
119 'SWEDISH' => 'Swedish',
120 ),
121 'instructions' => 'Default invoice language for this site.',
122 'default_value' => '',
123 'placeholder' => '- Required -',
124 'prepend' => '',
125 'append' => '',
126 'formatting' => 'html',
127 'maxlength' => '',
128 ),
129 array (
130 'key' => 'field_592fd7c617dce',
131 'label' => 'Currency',
132 'name' => 'currency',
133 'type' => 'text',
134 'instructions' => 'Currency code as defined by ISO 4217, eg. EUR, SEK, NOK... Defaults to EUR.',
135 'default_value' => '',
136 'placeholder' => '',
137 'prepend' => '',
138 'append' => '',
139 'formatting' => 'html',
140 'maxlength' => '',
141 ),
142 array (
143 'key' => 'field_593005bd2f013',
144 'label' => 'Default payment terms',
145 'name' => 'default_payment_terms',
146 'type' => 'number',
147 'instructions' => 'Days between invoice date and due date as number. Defaults to 14 days.',
148 'default_value' => '',
149 'placeholder' => '',
150 'prepend' => '',
151 'append' => '',
152 'min' => '',
153 'max' => '',
154 'step' => '',
155 ),
156 array (
157 'key' => 'field_5930062f8fee9',
158 'label' => 'Default VAT percentage',
159 'name' => 'default_vat',
160 'type' => 'number',
161 'instructions' => 'Value Added Tax to be added to the price. Defaults to 0.',
162 'default_value' => '',
163 'placeholder' => '',
164 'prepend' => '',
165 'append' => '',
166 'min' => '',
167 'max' => '',
168 'step' => '',
169 ),
170 array (
171 'key' => 'field_593552e0f3eb3',
172 'label' => 'Company IBAN',
173 'name' => 'company_iban',
174 'type' => 'text',
175 'instructions' => 'Your IBAN. Note: this needs to be the same as the IBAN in Procountor.',
176 'default_value' => '',
177 'placeholder' => '- Required -',
178 'prepend' => '',
179 'append' => '',
180 'formatting' => 'html',
181 'maxlength' => '',
182 ),
183 array (
184 'key' => 'field_355g462fhj643',
185 'label' => 'Procountor CompanyID',
186 'name' => 'procountor_companyid',
187 'type' => 'text',
188 'instructions' => 'CompanyID from Procountor. Required for connections to Procountor.',
189 'default_value' => '',
190 'placeholder' => '',
191 'prepend' => '',
192 'append' => '',
193 'formatting' => 'html',
194 'maxlength' => '',
195 ),
196 array (
197 'key' => 'field_8rbj3et359g35',
198 'label' => 'Order line format, main package',
199 'name' => 'order_line_format',
200 'type' => 'text',
201 'instructions' => 'Default: "{firstname} {lastname}, Opinahjon Akatemian {package}". Strings in brackages will be replaced.',
202 'default_value' => '',
203 'placeholder' => '',
204 'prepend' => '',
205 'append' => '',
206 'formatting' => 'html',
207 'maxlength' => '',
208 ),
209 array (
210 'key' => 'field_349gse4635y23',
211 'label' => 'Order line format, extra package',
212 'name' => 'order_line_format_extra',
213 'type' => 'text',
214 'instructions' => 'Default: "{package}"',
215 'default_value' => '',
216 'placeholder' => '',
217 'prepend' => '',
218 'append' => '',
219 'formatting' => 'html',
220 'maxlength' => '',
221 ),
222 array (
223 'key' => 'field_34593jf3952jg',
224 'label' => 'SMS sender name',
225 'name' => 'sms_sender_name',
226 'type' => 'text',
227 'instructions' => 'Sender name for SMS reminders. Max. 11 characters.',
228 'default_value' => '',
229 'placeholder' => '',
230 'prepend' => '',
231 'append' => '',
232 'formatting' => 'html',
233 'maxlength' => '',
234 ),
235 array (
236 'key' => 'field_4364f52fhhe34',
237 'label' => 'Email sender name',
238 'name' => 'email_sender_name',
239 'type' => 'text',
240 'instructions' => 'Sender name for email reminders. ',
241 'default_value' => '',
242 'placeholder' => '',
243 'prepend' => '',
244 'append' => '',
245 'formatting' => 'html',
246 'maxlength' => '',
247 ),
248/* array (
249 'key' => 'field_547345e0f35b7',
250 'label' => 'Connected sites',
251 'name' => 'connected_sites',
252 'type' => 'text',
253 'instructions' => 'Fill this if ',
254 'default_value' => '',
255 'placeholder' => '',
256 'prepend' => '',
257 'append' => '',
258 'formatting' => 'html',
259 'maxlength' => '',
260 ), */
261 ),
262 'location' => array (
263 array (
264 array (
265 'param' => 'options_page',
266 'operator' => '==',
267 'value' => 'acf-options',
268 'order_no' => 0,
269 'group_no' => 0,
270 ),
271 ),
272 ),
273 'options' => array (
274 'position' => 'normal',
275 'layout' => 'default',
276 'hide_on_screen' => array (
277 ),
278 ),
279 'menu_order' => 0,
280 ));
281}
282
283$procountor_countries = array(
284 'FI' => 'FINLAND',
285 'SE' => 'SWEDEN',
286 'EE' => 'ESTONIA',
287 'NO' => 'NORWAY',
288 'DK' => 'DENMARK',
289);
290
291/**
292 * Fetch some defaults from DB. ACF options fields.
293 *
294 * Currency: We've got EUR, NOK and SEK as of 2017-06
295*/
296$currency = trim(get_field('currency', 'options'));
297if(!empty($currency) && strlen($currency) == 3)
298 define( 'OPMEM_INVOICE_CURRENCY', $currency );
299else
300 define( 'OPMEM_INVOICE_CURRENCY', 'EUR' );
301
302$default_payment_terms = trim(get_field('default_payment_terms', 'options'));
303if(!empty($default_payment_terms))
304 define( 'OPMEM_INVOICE_DEFAULT_PAYMENT_TERMS', $default_payment_terms );
305else
306 define( 'OPMEM_INVOICE_DEFAULT_PAYMENT_TERMS', '14' );
307
308$default_vat = trim(get_field('default_vat', 'options'));
309/* VAT is added to the base price */
310if(!empty($default_vat))
311 define( 'OPMEM_INVOICE_VAT', $default_vat );
312else
313 define( 'OPMEM_INVOICE_VAT', '0' );
314
315$order_line_format = trim(get_field('order_line_format', 'options'));
316if(!empty($order_line_format))
317 define( 'OPMEM_INVOICE_ORDER_LINE_FORMAT', $order_line_format );
318else
319 define( 'OPMEM_INVOICE_ORDER_LINE_FORMAT', '{firstname} {lastname}, Opinahjon Akatemian {package}' );
320
321$order_line_format_extra = trim(get_field('order_line_format_extra', 'options'));
322if(!empty($order_line_format_extra))
323 define( 'OPMEM_INVOICE_ORDER_LINE_FORMAT_EXTRA', $order_line_format_extra );
324else
325 define( 'OPMEM_INVOICE_ORDER_LINE_FORMAT_EXTRA', '{package}' );
326
327$company_iban = trim(get_field('company_iban', 'options'));
328if(!empty($company_iban))
329 define( 'OPMEM_INVOICE_IBAN', $company_iban );
330else
331 define( 'OPMEM_INVOICE_IBAN', '' );
332
333$procountor_companyid = trim(get_field('procountor_companyid', 'options'));
334if(!empty($procountor_companyid))
335 define( 'OPMEM_INVOICE_COMPANYID', $procountor_companyid );
336else
337 define( 'OPMEM_INVOICE_COMPANYID', '' );
338
339$billing_country = trim(get_field('billing_country', 'options'));
340if(!empty($billing_country))
341{
342 define( 'OPMEM_BILLING_COUNTRY_CODE', $billing_country );
343 define( 'OPMEM_BILLING_COUNTRY', $procountor_countries[$billing_country] );
344}
345else
346{
347 define( 'OPMEM_BILLING_COUNTRY_CODE', 'FI' );
348 define( 'OPMEM_BILLING_COUNTRY', $procountor_countries['FI'] );
349}
350
351$billing_language = trim(get_field('billing_language', 'options'));
352if(!empty($billing_language))
353 define( 'OPMEM_BILLING_LANGUAGE', $billing_language );
354else
355 define( 'OPMEM_BILLING_LANGUAGE', 'ENGLISH' );
356
357
358if ( !defined('OPCOM_MAILERLITE_SECRET' ) )
359{
360 /* Define currency, VAT and payment terms */
361 if( strpos($_SERVER['HTTP_HOST'], 'accountortraining.no') !== false )
362 {
363 // define( 'OPMEM_INVOICE_DEFAULT_VAT', 0 );
364 // define( 'OPMEM_INVOICE_DEFAULT_PAYMENT_TERMS', 10 );
365 define( 'OPCOM_MAILERLITE_SECRET', 'eb4f86656679a9c41d501918acb4f64f' );
366 }
367 elseif( strpos($_SERVER['HTTP_HOST'], 'accountortraining.se') !== false
368 || strpos($_SERVER['HTTP_HOST'], 'devse.opinahjo.fi') !== false
369 || strpos($_SERVER['HTTP_HOST'], 'atse.dev') !== false )
370 {
371 define( 'OPCOM_MAILERLITE_SECRET', '9b3aa778481f916e004914801e8eb65f' );
372 define( 'OPCOM_MAILERLITE_NEW_ORDER_ARTICLES', '6692599' ); // Accountor Training articles & talks (GroupID - 6692599)
373 define( 'OPCOM_MAILERLITE_NO_ORDER', '6692581' ); // Accountor Training no subscribtion (GroupID - 6692581)
374 define( 'OPCOM_MAILERLITE_PROSPECTS', '6692575' ); // Accountor Training prospects (GroupID - 6692575)
375 define( 'OPCOM_MAILERLITE_NEW_ORDER_ACCOUNTOR', '6692587' ); // Accountor Training subscribers Accountor (GroupID - 6692587)
376 define( 'OPCOM_MAILERLITE_NEW_ORDER_OTHER', '6692593' ); // Accountor Training subscribers external (GroupID - 6692593)
377 define( 'OPCOM_MAILERLITE_CANCELLED_ORDER', '6692613' ); // Onboarding: Accountor Training cancellation (GroupID - 6692613)
378 define( 'OPCOM_MAILERLITE_CHANGED_ORDER', '6692647' ); // Onboarding: Accountor Training changes on subscription (GroupID - 6692647)
379 define( 'OPCOM_MAILERLITE_NEW_ORDER', '6692619' ); // Onboarding: Accountor Training new subscripiton (GroupID - 6692619)
380 define( 'OPCOM_MAILERLITE_TRIAL_SINGLE', '6692653' ); // Onboarding: Accountor Training Trial (GroupID - 6692653)
381 }
382 else
383 {
384 // define( 'OPMEM_INVOICE_DEFAULT_VAT', 24 );
385 // define( 'OPMEM_INVOICE_DEFAULT_PAYMENT_TERMS', 14 );
386 define( 'OPCOM_MAILERLITE_SECRET', 'f4963dbf9e80e685ab307332c946d055' );
387 define( 'OPCOM_MAILERLITE_TRIAL_SINGLE', '6080803' );
388
389 // Not sure how this should be done
390 define( 'OPCOM_MAILERLITE_THEME_WORK', '6628138' );
391
392 define( 'OPCOM_MAILERLITE_NEW_ORDER', '5627463' ); // Akatemian tilauksen aloittanut (GroupID - 5627463)
393 define( 'OPCOM_MAILERLITE_NEW_ORDER_ARTICLES', '4585865' ); //Opinahjo artikkelit talks / Opinahjo articles talks (GroupID - 4585865)
394 define( 'OPCOM_MAILERLITE_NEW_ORDER_ACCOUNTOR', '4509915' ); // Opinahjo koulutuspaketin tilaajat Accountor / Opinahjo subscribers Accountor (GroupID - 4509915)
395 define( 'OPCOM_MAILERLITE_NEW_ORDER_TIKON', '4510031' ); // Opinahjo koulutuspaketin tilaajat Tikon / Opinahjo subscribers Tikon (GroupID - 4510031)
396 define( 'OPCOM_MAILERLITE_NEW_ORDER_OTHER', '4510017' ); // Opinahjo koulutuspaketin tilaajat / Opinahjo subscribers (GroupID - 4510017)
397 define( 'OPCOM_MAILERLITE_NO_ORDER', '4494625' ); // Opinahjo ei voimassa olevaa tilausta / Opinahjo no subscribtion (GroupID - 4494625)
398 define( 'OPCOM_MAILERLITE_CANCELLED_ORDER', '5649029' ); // Akatemian tilauksen peruuttanut (GroupID - 5649029)
399 define( 'OPCOM_MAILERLITE_PROSPECTS', '4494611' ); // Opinahjo asiakasrekisteri / Opinahjo prospects (GroupID - 4494611)
400 define( 'OPCOM_MAILERLITE_CHANGED_ORDER', '5834947' ); // Akatemian tilauksen vaihtanut (GroupID - 5834947)
401 }
402}
403
404/* TODO: get page URLs from the system */
405$opmem_profile_pages = array(
406 'FI' => array(
407 'prefix' => '/tilaus/',
408 'order_form' => 'tilaa/',
409 'change_order' => 'vaihda/',
410 'cancel_order' => 'avbryt/',
411 'edit_billing_info' => 'andra-kontouppgifter/',
412 'change_password' => 'vaihda-salasana/',
413 ),
414 'SE' => array(
415 'prefix' => '/konto/',
416 'order_form' => 'bestall/',
417 'change_order' => 'bestall/',
418 'cancel_order' => 'avbryt/',
419 'edit_billing_info' => 'andra-kontouppgifter/',
420 'change_password' => 'andra-losenord/',
421 ),
422 'NO' => array(
423 'prefix' => '/konto/',
424 'order_form' => 'bestall/',
425 'change_order' => 'bestall/',
426 'cancel_order' => 'avbryt/',
427 'edit_billing_info' => 'andra-kontouppgifter/',
428 'change_password' => 'bytte-passord/',
429 ),
430);
431
432/*
433Endre Avbryt -> Oppsigelse av abonnement
434Bytte passord
435*/
436
437/**
438 * Set up Finvoice operators.
439 * Note: order forms and order system depend on this data.
440 */
441$finvoice_operators = array(
442 "op0" => "Valitse operaattori",
443 "op1" => "Aktia Pankki (HELSFIHH)",
444 "op2" => "Apix Messaging (3723327487)",
445 "op3" => "Basware (BAWCFI22)",
446 "op4" => "Enfo Zender (003714377140)",
447 "op5" => "Handelsbanken (HANDFIHH)",
448 "op6" => "OpusCapita (003710948874)",
449 "op7" => "Liaison Technologies (003708599126)",
450 "op8" => "CGI (003703575029)",
451 "op9" => "Visma (MAVENTA tai 003721291126)",
452 "op10" => "Nordea (NDEAFIHH)",
453 "op11" => "Notebeat (003717203971)",
454 "op12" => "NetBox Finland (003726044706)",
455 "op13" => "OP-Pohjola-Ryhmä (OKOYFIHH)",
456 "op14" => "Pagero (PAGERO)",
457 "op15" => "POP-Pankki (POPFFI22)",
458 "op16" => "Danske Bank (DABAFIHH)",
459 "op17" => "PostNord Strålfors (003701150617)",
460 "op18" => "S-Pankki (SBANFIHH)",
461 "op19" => "TeliaSonera Finland (003703575029)",
462 "op20" => "Säästöpankit (ITELFIHH)",
463 "op21" => "Tieto (003701011385)",
464 "op22" => "Tradeshift (00885060259470028)",
465 "op23" => "YAP Solutions (FIYAPSOL)"
466);
467
468global $wpdb;
469$campaigns_data = $wpdb->get_results('SELECT campaign_id, discount_code, discount_percentage, campaign_start, campaign_end FROM wpopi_opcom_campaign', OBJECT_K);
470foreach ($campaigns_data as $key => $code)
471{
472 $campaigns_select[$key] = $code->discount_code .' ('. $key .')';
473 /* HOW TO POPULATE GRAVITY FORMS DISCOUNT CODES */
474/* This is not finalized code! */
475 new GW_Create_Coupon( array(
476 // 'form_id' => 69,
477 'coupon_code' => $code->discount_code,
478 'plugin' => 'gf',
479 'type' => 'percentage',
480 'amount' => $code->discount_percentage,
481 'start' => date('m\/d\/Y', strtotime($code->campaign_start)),
482 'expire' => date('m\/d\/Y', strtotime($code->campaign_end))
483 ) );
484}
485// expiry_date
486// endDate
487
488// To be added: campaign id & info
489// fieldtypes: text, textarea, date, info
490// source: order, row, user, usermeta
491//
492// test, none, active, success, cancelled, accountor
493$billing_fields = array(
494
495 'user_info_start' => array(
496 'type' => 'fieldset_start',
497 'title' => 'User info',
498 ),
499 'first_name' => array(
500 'type' => 'text',
501 'source' => 'usermeta',
502 ),
503 'last_name' => array(
504 'type' => 'text',
505 'source' => 'usermeta',
506 ),
507 'user_email' => array(
508 'type' => 'info',
509 'source' => 'user',
510 ),
511 'company' => array(
512 'type' => 'text',
513 'source' => 'usermeta',
514 ),
515 'vatcode' => array(
516 'type' => 'text',
517 'source' => 'order',
518 'sources' => array(
519 'order' => 'vatcode',
520 'user' => 'oa_vatcode',
521 ),
522 'title' => 'Business ID',
523 ),
524 'oa_address' => array(
525 'type' => 'text',
526 'source' => 'usermeta',
527 ),
528 'oa_postalcode' => array(
529 'type' => 'text',
530 'source' => 'usermeta',
531 ),
532 'oa_city' => array(
533 'type' => 'text',
534 'source' => 'usermeta',
535 ),
536 'user_info_end' => array(
537 'type' => 'fieldset_end',
538 ),
539
540 'order_start' => array(
541 'type' => 'fieldset_start',
542 'title' => 'Order',
543 ),
544 'order_identifier' => array(
545 'title' => 'Unique order identifier',
546 'type' => 'info',
547 'source' => 'order',
548 ),
549 'campaign_id' => array(
550 'type' => 'select',
551 'source' => 'order',
552 'select_values' => $campaigns_select,
553 ),
554 'order_status' => array(
555 'type' => 'select',
556 'source' => 'order',
557 'select_values' => array(
558 'cancelled' => 'Cancelled',
559 'active' => 'Active',
560 'success' => 'Success',
561 'accountor' => 'Accountor',
562 'trial' => 'Trial',
563 ),
564 ),
565 'order_date' => array(
566 'type' => 'date',
567 'source' => 'order',
568 ),
569 'access_date' => array(
570 'type' => 'date',
571 'source' => 'order',
572 ),
573 'cancel_date' => array(
574 'type' => 'date',
575 'source' => 'order',
576 ),
577 'end_date' => array(
578 'type' => 'date',
579 'source' => 'order',
580 ),
581 'first_cancel_date' => array(
582 'type' => 'date',
583 'source' => 'order',
584 ),
585 'extra_info' => array(
586 'type' => 'textarea',
587 'source' => 'order',
588 'title' => 'Extra info (user provided)',
589 ),
590 'legacy_order_id' => array(
591 'type' => 'info',
592 'source' => 'order',
593 ),
594 'order_source' => array(
595 'type' => 'select',
596 'source' => 'order',
597 'select_values' => array(
598 'JMGroove' => 'JMGroove',
599 'Order Form' => 'Order Form',
600 'AdWords' => 'AdWords',
601 'Google Search' => 'Google Search',
602 'Event' => 'Event',
603 'Partner' => 'Partner',
604 'Trial' => 'Trial',
605 'Email' => 'Email',
606 'Campaign' => 'Campaign'
607 ),
608 ),
609 'order_end' => array(
610 'type' => 'fieldset_end',
611 ),
612
613/* 'oa_billing_ovt' => array(
614 'type' => 'info',
615 'source' => 'usermeta',
616 ), */
617
618 'billing_start' => array(
619 'type' => 'fieldset_start',
620 'title' => 'Billing info',
621 ),
622 'first_invoicing_date' => array(
623 'type' => 'date',
624 'source' => 'order',
625 ),
626 'last_invoice_date' => array(
627 'type' => 'info',
628 'source' => 'order',
629 'title' => 'Date of the latest invoice'
630 ),
631 'last_invoice_status' => array(
632 'type' => 'info',
633 'source' => 'order',
634 'title' => 'Status of the latest invoicing action'
635 ),
636 'customer_reference' => array(
637 'type' => 'text',
638 'source' => 'order',
639 ),
640 'payment_terms' => array(
641 'type' => 'text',
642 'source' => 'usermeta',
643 'title' => 'Payment terms if not 14 (numbers only)'
644 ),
645 'oa_billing_ovt' => array(
646 'type' => 'select',
647 'source' => 'usermeta',
648 'select_values' => array(
649 'billing_email' => 'Email',
650 'billing_web' => 'Finvoice',
651 'billing_paper' => 'Paper',
652 ),
653 'title' => 'Billing channel'
654 ),
655 'oa_billing_vlasku' => array(
656 'type' => 'text',
657 'source' => 'usermeta',
658 'title' => 'Finvoice address (OVT)',
659 ),
660 'oa_billing_service' => array(
661 'type' => 'select',
662 'source' => 'usermeta',
663 'select_values' => $finvoice_operators,
664 'title' => 'Finvoice operator',
665 ),
666 'oa_billing_email' => array(
667 'type' => 'text',
668 'source' => 'usermeta',
669 ),
670 'notes' => array(
671 'type' => 'textarea',
672 'source' => 'order',
673 'title' => 'Billing notes (internal use)',
674 ),
675 'billing_end' => array(
676 'type' => 'fieldset_end',
677 ),
678
679);
680
681$export_fields = array(
682
683 'order_id' => array(
684 'source' => 'order'
685 ),
686 'user_id' => array(
687 'source' => 'user'
688 ),
689 'user_login' => array(
690 'source' => 'user'
691 ),
692 'first_name' => 'default',
693 'last_name' => 'default',
694 'user_email' => 'default',
695 'package_id' => array(
696 'source' => 'order'
697 ),
698 'package_name' => 'COMPUTE',
699 'billing_amount' => 'orderrow',
700 'tax' => 24,
701 'discount_percentage' => 'orderrow',
702 'total' => 'COMPUTE',
703 'payment_type' => '',
704 'order_status' => 'default',
705 'gateway' => '', // obsolete
706 'gateway_environment' => '', // obsolete
707 'payment_transaction_id' => '', // obsolete
708 'subscription_transaction_id' => '', // obsolete
709 'campaign_id' => 'default',
710 'campaign_name' => 'COMPUTE',
711 'order_date' => 'default',
712 'cancel_date' => 'default',
713 'service_providers' => 'COMPUTE',
714 'tikon_orderid' => '',
715 'company' => 'default',
716 'oa_address' => 'default',
717 'oa_postalcode' => 'default',
718 'oa_city' => 'default',
719 'oa_billing_ovt' => 'default',
720 'oa_billing_vlasku' => 'default',
721 'oa_billing_email' => 'default',
722 'vatcode' => 'default',
723 'notes' => 'default'
724);
725
726$billing_row_fields = array(
727 'package_id' => array(
728 'type' => 'text',
729 ),
730 'description' => array(
731 'type' => 'text',
732 ),
733 'billing_amount' => array(
734 'type' => 'text',
735 ),
736 'tax_percentage' => array(
737 'type' => 'text',
738 ),
739 'discount_percentage' => array(
740 'type' => 'text',
741 ),
742);
743
744/**
745 * Define order form meta fields. Radio and select are defined as the same type in this case.
746 * Note: this is in the middle of translation
747 */
748$order_metafields = array(
749 'Puhelin' => array('meta' => 'oa_phone', 'type' => 'text'),
750 'Organisaatio' => array('meta' => 'company', 'type' => 'text'),
751 'Y-tunnus' => array('meta' => 'oa_vatcode', 'type' => 'text'),
752 'Verkkolaskuosoite' => array('meta' => 'oa_billing_vlasku', 'type' => 'text'),
753 'Laskutussähköposti' => array('meta' => 'oa_billing_email', 'type' => 'text'),
754 'Muut lisätiedot' => array('meta' => 'oa_otherinfo', 'type' => 'text'),
755 'Asiakas' => array('meta' => 'oa_billing_customer', 'type' => 'select'),
756 'Laskutustapa' => array('meta' => 'oa_billing_ovt', 'type' => 'select'),
757 'Operaattori' => array('meta' => 'oa_billing_service', 'type' => 'select'),
758 'Organisaation toimiala' => array('meta' => 'oa_company_sector', 'type' => 'select'),
759 'Osoite' => array('type' => 'address', 'meta' => array(1 => 'oa_address', 5 => 'oa_postalcode', 3 => 'oa_city')),
760
761 'Phone' => array('meta' => 'oa_phone', 'type' => 'text'),
762 'Organization' => array('meta' => 'company', 'type' => 'text'),
763 'VAT code' => array('meta' => 'oa_vatcode', 'type' => 'text'),
764 // 'Verkkolaskuosoite' => array('meta' => 'oa_billing_vlasku', 'type' => 'text'),
765 'Billing email' => array('meta' => 'oa_billing_email', 'type' => 'text'),
766 'Extra information' => array('meta' => 'oa_otherinfo', 'type' => 'text'),
767 'Customer type' => array('meta' => 'oa_billing_customer', 'type' => 'select'),
768 'Invoicing method' => array('meta' => 'oa_billing_ovt', 'type' => 'select'),
769 // 'Operaattori' => array('meta' => 'oa_billing_service', 'type' => 'select'),
770 // 'Organisaation toimiala' => array('meta' => 'oa_company_sector', 'type' => 'select'),
771 'Address' => array('type' => 'address', 'meta' => array(1 => 'oa_address', 5 => 'oa_postalcode', 3 => 'oa_city'))
772);
773
774$sql_fields = array(
775 'order_line' => 'line_id, wpopi_opcom_order_line.order_id, wpopi_opcom_order_line.package_id, wpopi_opcom_order_line.description, billing_amount, tax_percentage, discount_percentage, manual_discount',
776 'package' => 'package_id, name, price, type, upgrade_path, cancel_delay_months',
777 'order' => 'order_id, order_identifier, order_status, user_id, order_date, access_date, cancel_date, end_date,
778 first_invoicing_date, first_cancel_date, campaign_id, vatcode, organization_id, contract_start, billing_period, cancel_delay, extra_info, notes, last_invoice_date, last_invoice_status, order_source, customer_reference',
779 'campaign' => 'campaign_id, discount_code, description, order_terms, campaign_start, campaign_end, free_days, cancel_delay, discount_percentage',
780);
781
782/*
783$log_statuses = array(
784 'add_rows' => 'Add rows',
785 'add_row' => 'Add row',
786 'edit_rows' => 'Edit rows',
787 'add_order' => 'Add order',
788 'edit_order' => 'Edit order',
789 'write_invoice' => 'Write invoice',
790 'skip_invoice' => 'Skip invoice'
791);
792*/
793
794
795/*
796function opmem_get_package_name_by_id($atts)
797{
798 if(is_array($atts) && !empty($atts['id']))
799 {
800 $id = $atts['id'];
801 }
802 else
803 {
804 $id = $atts;
805 }
806 global $wpdb;
807 $packages = $wpdb->get_results('SELECT package_id, name, price, type FROM wpopi_opcom_package', OBJECT_K);
808 if(!empty($packages[$id]))
809 {
810 return $packages[$id]->name;
811 }
812}
813add_shortcode('opmem_package_name', 'opmem_get_package_name_by_id');
814*/
815
816/*
817* Order management
818*/
819
820add_action('admin_menu', 'opcom_admin_menu', 1000);
821
822function opcom_admin_menu()
823{
824 if(!is_admin())
825 return;
826
827 add_menu_page( 'Members', 'Members', 'manage_options', 'opcom_members', 'opcom_members_front', 'dashicons-heart');
828 add_submenu_page('opcom_members', "opinahjo", "Members", "manage_options", "opcom_members_list", "opcom_members_list");
829 add_submenu_page('opcom_members', "opinahjo", "Packages", "manage_options", "opcom_packages", "opcom_packages_list");
830 add_submenu_page('opcom_members', "opinahjo", "Invoicing", "manage_options", "opcom_billing_list", "opcom_billing_list");
831 add_submenu_page('opcom_members', "opinahjo", "Billing History", "manage_options", "opcom_billing_history", "opcom_billing_history");
832 add_submenu_page('opcom_members', "opinahjo", "Campaigns", "manage_options", "opcom_campaigns", "opcom_campaigns_list");
833 add_submenu_page('opcom_members', "opinahjo", "Add user", "manage_options", "opcom_new_user", "opcom_add_user_form");
834 add_submenu_page('opcom_members', "opinahjo", "User Import", "manage_options", "opcom_user_import", "opmem_users_mass_import");
835 add_submenu_page('opcom_members', "opinahjo", "Order Log", "manage_options", "opcom_order_log", "opcom_show_order_log");
836 add_submenu_page('opcom_members', 'opinahjo', 'Study plans', 'manage_options', 'opcom_studyplans', 'opcom_studyplan_list');
837
838 add_submenu_page('opcom_members', 'opinahjo', 'Test settings', 'manage_options', 'opcom_test', 'opcom_test_list');
839
840 remove_submenu_page('opcom_members', 'opcom_members');
841}
842
843function opcom_members_front()
844{
845 echo '<div class="wrap">';
846 echo '<h1>Opinahjo Memberships</h1>';
847 echo '<p>Hi there!</p>';
848 echo '</div>';
849}
850
851function opcom_test_list()
852{
853 require_once( dirname( __FILE__ ).'/class_order.php' );
854
855 echo '<div class="wrap"><h1>Test settings</h1>';
856 echo '<h2>Settings</h2>';
857 if(empty(OPMEM_INVOICE_IBAN))
858 {
859 echo '<p style="color: red;">IBAN not set</p>';
860 }
861 echo '<p>Site currency: '. OPMEM_INVOICE_CURRENCY .'</p>';
862 echo '<p>Billing country: '. OPMEM_BILLING_COUNTRY .'</p>';
863 echo '<p>Billing language: '. OPMEM_BILLING_LANGUAGE .'</p>';
864
865 echo '</div>';
866
867 echo '<h2>Procountor API connection</h2>';
868 $conf_file = '/var/www/site_conf/'. str_replace('.', '-', $_SERVER['HTTP_HOST']) .'.php';
869
870 include_once( $conf_file );
871 if(!isset($procountor_api_settings))
872 {
873 echo '<p style="color: red;">Can\'t load config file
874 <br />'. $conf_file .'</p>';
875 }
876 else
877 {
878 echo '<p>Procountor API server: '. $procountor_api_settings['server'] .'</p>';
879
880 $proc_prods = new Procountor_Products($procountor_api_settings);
881 $procountor_products = $proc_prods->getProducts();
882
883 echo '<p>Testing connection: ';
884 if($procountor_products['status'] == 200)
885 {
886 echo 'OK';
887 }
888 else
889 {
890 echo 'CAN\'T DETERMINE STATUS';
891 }
892 echo '</p>';
893 // print_r($procountor_products);
894 if($procountor_products['products'])
895 {
896 echo '<table>';
897 echo '<tr>
898 <td>id</td>
899 <td>name</td>
900 <td>code</td>
901 <td>price</td>
902 <td>currency</td>
903 </tr>';
904 foreach($procountor_products['products'] as $prod)
905 {
906 echo '<tr>';
907 echo '<td>'. $prod->id .'</td>';
908 echo '<td>'. $prod->name .'</td>';
909 echo '<td>'. $prod->code .'</td>';
910 echo '<td>'. $prod->price .'</td>';
911 echo '<td>'. $prod->currency .'</td>';
912 echo '</tr>';
913 }
914 echo '</table>';
915 echo '<p>This is the Procountor product list for the instance specified in the configuration.</p>';
916 }
917 else
918 {
919 echo '<p>Procountor product list received, but EMPTY.</p>';
920 }
921
922 }
923
924
925
926}
927
928/**
929 * Displays the packages in the system.
930 * Type extra stands for extra services such as Tikon.
931 *
932 * Please note: combination of order_status == 'trial' and package type 'normal' is valid.
933 */
934function opcom_packages_list()
935{
936
937 $package_types = array(
938 'trial' => 'Trial',
939 'trial-single' => 'Trial Single',
940 'normal' => 'Normal',
941 'extra' => 'Extra',
942 'restricted' => 'Restricted'
943 );
944
945 if(current_user_can('manage_options'))
946 {
947 global $wpdb, $sql_fields;
948 echo '<div class="wrap">';
949 echo '<style> .package_course_list { width: 42%; float: left; padding-right: 5%; } </style>';
950 if(isset($_GET['edit']))
951 {
952
953 $sql = "SELECT ID, post_title, '1' as site_id FROM $wpdb->posts
954 WHERE post_type = 'sfwd-courses' AND post_status = 'publish'
955 ORDER BY site_id, post_title ASC";
956 $pageposts = $wpdb->get_results($sql, OBJECT);
957
958 if(function_exists('switch_to_blog'))
959 {
960 $sql2 = "SELECT ID, post_title, '5' as site_id FROM wpopi_5_posts
961 WHERE post_type = 'sfwd-courses' AND post_status = 'publish'
962 ORDER BY site_id, post_title ASC";
963 $pageposts2 = $wpdb->get_results($sql2, OBJECT);
964 $pageposts = array_merge($pageposts, $pageposts2);
965 }
966
967
968 if($_POST['package-name']
969 && $package_types[$_POST['package-type']])
970 {
971// Save course stuff
972
973 write_log('-------------------- ');
974 write_log(' Update initialized ');
975 write_log('-------------------- ');
976
977 if(intval($_POST['package-upgrade_path']) == 0)
978 {
979 $upd_path = null;
980 }
981 else
982 {
983 $upd_path = intval($_POST['package-upgrade_path']);
984 }
985
986 $update_package = array(
987 'name' => $_POST['package-name'],
988 'price' => floatval($_POST['package-price']),
989 'type' => $_POST['package-type'],
990 'upgrade_path' => $upd_path,
991 'cancel_delay_months' => intval($_POST['package-cancel_delay_months'])
992 );
993 $wpdb->update('wpopi_opcom_package', $update_package, array('package_id' => $_GET['edit']));
994
995 foreach($pageposts as $ppost)
996 {
997 // Delete all, recreate those that are needed.
998 $res = $wpdb->delete('wpopi_opcom_package_course', array('package_id' => $_GET['edit'], 'course_id' => $ppost->ID, 'site_id' => $ppost->site_id));
999 if($res != 0)
1000 {
1001 write_log('Delete course '. $ppost->ID);
1002 }
1003
1004 if( in_array($ppost->ID, $_POST['course-site-'. $ppost->site_id]) )
1005 {
1006 $courses_to_save = array(
1007 'package_id' => $_GET['edit'],
1008 'course_id' => $ppost->ID,
1009 'site_id' => $ppost->site_id,
1010 );
1011 $wpdb->insert('wpopi_opcom_package_course', $courses_to_save);
1012 write_log('Insert course '. $ppost->ID);
1013 }
1014 }
1015 }
1016
1017 $package = $wpdb->get_row('SELECT '. $sql_fields['package'] .'
1018 FROM wpopi_opcom_package WHERE package_id = '. $_GET['edit']);
1019 echo '<h1 style="padding-bottom: 20px;">Edit package</h1>';
1020 echo '<p><a href="/wp-admin/admin.php?page=opcom_packages">Back to list</a></p>';
1021 echo '<form method="post" action="/wp-admin/admin.php?page=opcom_packages&edit='. $_GET['edit'] .'">';
1022 echo '<div class="postbox" style="width: 42%;"><div class="inside"><table class="form-table">';
1023 foreach(explode(', ', $sql_fields['package']) as $field)
1024 {
1025 echo '<tr>';
1026 if($field == 'package_id')
1027 {
1028 echo '<th>'. ucfirst(str_replace('_', ' ', $field)) .'</th>';
1029 echo '<td>'. $package->$field .'</td>';
1030 }
1031 elseif($field == 'type')
1032 {
1033// todo: add status codes from somewhere
1034 echo '<th>'. ucfirst(str_replace('_', ' ', $field)) .'</th>';
1035 echo '<td><select name="package-'. $field .'">';
1036 foreach($package_types as $key => $val)
1037 {
1038 $selected = '';
1039 if($key == $package->$field)
1040 {
1041 $selected = 'selected';
1042 }
1043 echo '<option '. $selected .' value="'. $key .'">'. $val .'</option>';
1044 }
1045 echo '</select></td>';
1046 }
1047 else
1048 {
1049 echo '<th>'. ucfirst(str_replace('_', ' ', $field)) .'</th>';
1050 echo '<td><input name="package-'. $field .'" value="'. $package->$field .'" />';
1051 echo '</td>';
1052 }
1053 echo '</tr>';
1054 }
1055 echo '</table></div></div>';
1056 echo '<h2>Courses</h2>';
1057
1058 // get package courses
1059 $sql_courses = "SELECT course_id, site_id FROM wpopi_opcom_package_course
1060 WHERE package_id = '". $_GET['edit'] ."'";
1061 $package_courses = $wpdb->get_results($sql_courses, OBJECT_K);
1062/*
1063 $sql_count = "SELECT COUNT(ID) as counted FROM $wpdb->posts
1064 WHERE post_type = 'sfwd-courses' AND post_status = 'publish'
1065 UNION
1066 SELECT COUNT(ID) as counted FROM wpopi_5_posts
1067 WHERE post_type = 'sfwd-courses' AND post_status = 'publish'";
1068 $counts = $wpdb->get_results($sql_count, ARRAY_A);
1069*/
1070 echo '<div class="package_course_list"><h3>Academy</h3>';
1071 $prev_site = 1;
1072 $break = true;
1073 foreach($pageposts as $post)
1074 {
1075 $prev_site = $post->site_id;
1076 if($prev_site != 1 && $break)
1077 {
1078 echo '</div><div class="package_course_list"><h3>Tikon</h3>';
1079 $break = false;
1080 }
1081 $selected = '';
1082 if(isset($package_courses[$post->ID]))
1083 {
1084 $selected = 'checked';
1085 }
1086 echo "\n<p style=\"margin-top: 0px; margin-bottom: 6px;\">";
1087 echo '<input '. $selected .' type="checkbox" name="course-site-'. $post->site_id .'[]" value="'. $post->ID .'" />';
1088 echo $post->post_title .'</p>';
1089 }
1090 echo '</div><div style="clear: both;"></div>';
1091
1092// TODO: get tikon courses
1093
1094 echo '<input type="hidden" name="action-package-nonce" value="'. wp_create_nonce('opcom-package') .'" />';
1095 echo '<br /><input type="submit" value="Save" class="button-primary" />';
1096 echo '</form>';
1097
1098 }
1099 else if($_GET['add'] == 2)
1100 {
1101 echo '<h1 style="padding-bottom: 20px;">Add new package</h1>';
1102 echo '<p><a href="/wp-admin/admin.php?page=opcom_packages">Back to list</a></p>';
1103 echo '<form method="post" action="/wp-admin/admin.php?page=opcom_packages&create'. $_GET['edit'] .'">';
1104 echo '<div class="postbox" style="width: 55%;"><div class="inside"><table class="form-table">';
1105
1106 foreach(explode(', ', $sql_fields['package']) as $field)
1107 {
1108 echo '<tr>';
1109 if($field == 'package_id')
1110 {
1111 // Don't show package id on creation process.
1112 }
1113 elseif($field == 'type')
1114 {
1115// todo: add status codes from somewhere
1116 echo '<th>'. ucfirst(str_replace('_', ' ', $field)) .'</th>';
1117 echo '<td><select name="package-'. $field .'">';
1118 foreach($package_types as $key => $val)
1119 {
1120 $selected = '';
1121 if($key == $package->$field)
1122 {
1123 $selected = 'selected';
1124 }
1125 echo '<option '. $selected .' value="'. $key .'">'. $val .'</option>';
1126 }
1127 echo '</select></td>';
1128 }
1129 else
1130 {
1131 echo '<th>'. ucfirst(str_replace('_', ' ', $field)) .'</th>';
1132 echo '<td><input name="package-'. $field .'" value="'. $package->$field .'" />';
1133 echo '</td>';
1134 }
1135 echo '</tr>';
1136 }
1137
1138 echo '</table></div></div>';
1139
1140 echo '</div><div style="clear: both;"></div>';
1141
1142 add_datepickers();
1143
1144 // TODO: get tikon courses
1145
1146 echo '<input type="hidden" name="action-package-nonce" value="'. wp_create_nonce('opcom-package') .'" />';
1147 echo '<br /><input type="submit" value="Create" class="button-primary" />';
1148 echo '</form>';
1149
1150 }
1151 else
1152 {
1153 if(isset($_GET['create']) && $_POST['package-name'])
1154 {
1155
1156 write_log('-----------------------------------');
1157 write_log(' Creating new package initialized ');
1158 write_log('---------------------------------- ');
1159
1160 $update_package = array(
1161 'name' => $_POST['package-name'],
1162 'price' => $_POST['package-price'],
1163 'type' => $_POST['package-type'],
1164 'upgrade_path' => $_POST['package-upgrade_path'],
1165 'cancel_delay_months' => $_POST['package-cancel_delay_months']
1166 );
1167 $wpdb->insert('wpopi_opcom_package', $update_package);
1168
1169 }
1170 $packages = $wpdb->get_results('SELECT '. $sql_fields['package'] .' FROM wpopi_opcom_package', OBJECT_K);
1171 opcom_admin_styles();
1172 echo '<h1 style="padding-bottom: 20px;">Packages <span class="dashicons dashicons-cart opcom"></span></h1>';
1173 ?>
1174 <table class="wp-list-table widefat striped" style="width: 75%; float: left !important;">
1175 <thead>
1176 <tr>
1177 <th>ID</td>
1178 <th>Name</th>
1179 <th>Price € (VAT 0%)</th>
1180 <th>Type</th>
1181 <th>Upgrade path</th>
1182 <th>Cancel delay</th>
1183 <th>Courses</th>
1184 </tr>
1185 </thead>
1186 <tbody>
1187 <?php
1188 foreach($packages as $package)
1189 {
1190
1191 $course_counter = 0;
1192 $sql_count = "SELECT COUNT(course_id) as counter FROM wpopi_opcom_package_course
1193 WHERE package_id = '". $package->package_id ."'";
1194 $count_courses = $wpdb->get_results($sql_count);
1195
1196 $course_counter = $count_courses[0]->counter;
1197
1198 if(function_exists('switch_to_blog'))
1199 {
1200 $sql_count = "SELECT COUNT(course_id) FROM wpopi_opcom_package_course
1201 WHERE package_id = '". $package->package_id ."'";
1202 $count_courses2 = $wpdb->get_results($sql_count);
1203 $course_counter = $course_counter + $count_courses2[0]->counter;
1204 }
1205
1206 echo '<tr>';
1207 echo '<td>'. $package->package_id .'</td>';
1208 echo '<td><a href="/wp-admin/admin.php?page=opcom_packages&edit='. $package->package_id .'">'. $package->name .'</a></td>';
1209 echo '<td>'. $package->price .' / month</td>';
1210 echo '<td>'. $package->type .'</td>';
1211 echo '<td>'. $package->upgrade_path .'</td>';
1212 if ($package->cancel_delay_months > 0)
1213 {
1214 echo '<td>'. $package->cancel_delay_months .' months</td>';
1215 }
1216 else
1217 {
1218 echo '<td></td>';
1219 }
1220 if($course_counter == 0)
1221 {
1222 $course_counter = '-';
1223 }
1224 echo '<td>'. $course_counter .'</td>';
1225 echo '</tr>';
1226 }
1227 echo '</tbody></table>';
1228
1229 ?>
1230 <div class="stuffbox handlediv" style="float: right; width: 23%;">
1231
1232 <div class="inside">
1233 <h2>Package types</h2>
1234 <ul>
1235 <li>normal - packages that will be shown on the order form</li>
1236 <li>extra - shown as extra option on the order form</li>
1237 <li>trial - only available via customized order forms</li>
1238 <li>trial-single - same as above, but adds any single course to the order</li>
1239 </ul>
1240 </div>
1241 </div>
1242 <?php
1243
1244 echo '<a href="/wp-admin/admin.php?page=opcom_packages&add=2" style="color: white; text-shadow: none; text-decoration: none;">';
1245 echo '<input class="button-primary" type="submit" value="Add" style="margin-right: 25%; margin-top: 20px;">';
1246 echo '</a>';
1247 }
1248 echo '</div>';
1249 }
1250}
1251
1252function opcom_billing_history()
1253{
1254 global $wpdb;
1255 $actions = array('write_invoice' => 'Sent', 'skip_invoice' => 'Skip');
1256 if($_GET['year'] && $_GET['month'])
1257 {
1258 $active_year = $_GET['year'];
1259 $active_month = $_GET['month'];
1260 }
1261 else
1262 {
1263 $active_year = date('Y');
1264 $active_month = date('n');
1265 }
1266 $month_last_day = date('t', strtotime($active_year. '-'. $active_month .'-01 00:00:01'));
1267
1268 $sql = "SELECT * FROM wpopi_opcom_order_log WHERE action IN ('write_invoice', 'skip_invoice')
1269 AND time BETWEEN '". strtotime($active_year. '-'. $active_month .'-01 00:00:01') ."'
1270 AND '". strtotime($active_year. '-'. $active_month .'-'. $month_last_day .'23:59:59') ."'";
1271 // ORDER BY user_id
1272 $log_entries = $wpdb->get_results($sql, OBJECT);
1273
1274 $totals = array();
1275 $content = '';
1276 $processed = array();
1277
1278 $table_head = '
1279 <thead class="billing_head">
1280 <tr>
1281 <th>Date</th>
1282 <th>Action</th>
1283 <th>Email</th>
1284 <th>Company</th>
1285 <th>Vat code</th>
1286 <th>Delivery dates</th>
1287 <th>Due date</th>
1288 <th>Package</th>
1289 <th>Price</th>
1290 </tr>
1291 </thead>
1292 ';
1293
1294 opcom_admin_styles();
1295 $content .= '<table class="userlist widefat striped">';
1296 $content .= $table_head;
1297 $i = 0;
1298
1299 foreach($log_entries as $entry)
1300 {
1301
1302 $message = unserialize($entry->message);
1303 $xml = new SimpleXMLElement($message['xml_payload']);
1304
1305 // Skipping double billing actions for 2017 / 04
1306 if(!isset($processed[trim($xml->BuyerCommunicationDetails->BuyerEmailaddressIdentifier)]))
1307 {
1308 $i++;
1309 $content .= '<tr>';
1310 $content .= '<td>'. date('Y-m-d', $entry->time) .'</td>';
1311 $content .= '<td>'. $actions[$entry->action] .'</td>';
1312 $totals['action'][$actions[$entry->action]]++;
1313 $totals['total_orders']++;
1314
1315 $content .= '<td>'. $xml->BuyerCommunicationDetails->BuyerEmailaddressIdentifier .'</td>';
1316 $content .= '<td>'. $xml->InvoiceRecipientPartyDetails->InvoiceRecipientOrganisationName .'</td>';
1317 $content .= '<td>'. $xml->BuyerPartyDetails->BuyerPartyIdentifier .'</td>';
1318
1319 $content .= '<td>'. date('Y-m-d', strtotime($xml->DeliveryDetails->DeliveryPeriodDetails->StartDate))
1320 .' - '. date('Y-m-d', strtotime($xml->DeliveryDetails->DeliveryPeriodDetails->EndDate)) .'</td>';
1321 $content .= '<td>'. date('Y-m-d', strtotime($xml->InvoiceDetails->PaymentTermsDetails->InvoiceDueDate)) .'</td>';
1322
1323 // echo '<td>'. print_r($xml, true) .'</td>';
1324
1325 $sum = 0;
1326 $articles = '';
1327 $has_tikon = false;
1328 foreach($xml->InvoiceRow as $invoicerow)
1329 {
1330 if(!empty($articles))
1331 {
1332 $articles .= '<br />'. $invoicerow->ArticleName;
1333 }
1334 else
1335 {
1336 $articles = $invoicerow->ArticleName;
1337 }
1338
1339 if($invoicerow->ArticleIdentifier == 10)
1340 {
1341 $has_tikon = true;
1342 }
1343 $totals['order_rows']++;
1344 $totals['packages'][trim($invoicerow->ArticleName)]++;
1345 $unitprice = trim($invoicerow->UnitPriceAmount);
1346 $discount = trim($invoicerow->RowDiscountPercent);
1347 if($discount == 0 || empty($discount))
1348 {
1349 $sum = $sum + $unitprice;
1350 }
1351 else
1352 {
1353 $sum = $sum + $unitprice - ($unitprice * $discount / 100);
1354 }
1355 }
1356
1357 if($has_tikon === true)
1358 {
1359 $totals['total_billable_tikon_euro'] = $totals['total_billable_tikon_euro'] + $sum;
1360 $totals['total_billable_tikon_count']++;
1361 }
1362 elseif($entry->action == 'skip_invoice')
1363 {
1364 $totals['total_skipped_euro'] = $totals['total_skipped_euro'] + $sum;
1365 $totals['total_skipped_count']++;
1366 }
1367 else
1368 {
1369 $totals['total_billable_euro'] = $totals['total_billable_euro'] + $sum;
1370 $totals['total_billable_count']++;
1371 }
1372
1373 $content .= '<td>'. $articles .'</td>';
1374 $content .= '<td>'. $sum .'</td>';
1375
1376 $content .= '</tr>';
1377 $processed[trim($xml->BuyerCommunicationDetails->BuyerEmailaddressIdentifier)] = 1;
1378 }
1379 }
1380 $content .= $table_head;
1381 $content .= '</table>';
1382
1383 // print_r($log_entries);
1384
1385 echo '<div class="wrap">';
1386 echo '<h2>Billing history for '. $active_year .' / '. $active_month .'</h2>';
1387
1388 echo '<p><strong>Billing actions</strong>';
1389 foreach ($totals['action'] as $action => $number)
1390 {
1391 echo '<br />'. $action .': '. $number;
1392 }
1393 echo '<br />Total invoices: '. $totals['total_orders'] .'</p>';
1394
1395 echo '<p><strong>Packages</strong>';
1396 foreach ($totals['packages'] as $package => $number)
1397 {
1398 echo '<br />'. $package .': '. $number;
1399 }
1400 echo '<br />Order rows for all invoices: '. $totals['order_rows'] .'</p>';
1401
1402 echo '<table class="opcom_billinghistory_totals"><tr><td><strong>Total €</strong></td><td></td><td>Orders</td></tr>';
1403 echo '<tr><td>Opinahjo: </td><td>'.
1404 number_format($totals['total_billable_euro'], 2, ',', ' ') .' €</td><td> '.
1405 $totals['total_billable_count'] .'</td></tr>';
1406 echo '<tr><td>Tikon: </td><td>'.
1407 number_format($totals['total_billable_tikon_euro'], 2, ',', ' ') .' €</td><td> '.
1408 $totals['total_billable_tikon_count'] .'</td></tr>';
1409 echo '<tr><td>Other skipped: </td><td>'.
1410 number_format($totals['total_skipped_euro'], 2, ',', ' ') .' €</td><td> '.
1411 $totals['total_skipped_count'] .'</td></tr></table><br />';
1412
1413 echo '<div class="top tablenav-pages opinahjo"><span class="pagination-links">';
1414 // <span class="displaying-num" style="float: left;">'. $count_listing .' results</span>'
1415
1416 $prev_month = $active_month - 1;
1417 $next_month = $active_month + 1;
1418 echo '<a class="prev-page" href="/wp-admin/admin.php?page=opcom_billing_history&year=2017&month='. $prev_month .'">Previous month</a>';
1419 if(date('n') != $active_month)
1420 {
1421 echo ' - <a class="next-page" href="/wp-admin/admin.php?page=opcom_billing_history&year=2017&month='. $next_month .'">Next month</a>';
1422 }
1423 echo '</span></div>';
1424
1425 echo '
1426 <script type="text/javascript" src="/wp-content/plugins/opinahjo-common/js/DataTables/datatables.min.js"></script>
1427 <script type="text/javascript" src="/wp-content/plugins/opinahjo-common/js/DataTables/date-euro-mod.js"></script>
1428 <link rel="stylesheet" type="text/css" href="/wp-content/plugins/opinahjo-common/js/DataTables/datatables.min.css" />
1429 <script type="text/javascript">
1430 jQuery( document ).ready(function() {
1431 jQuery(".userlist").DataTable({
1432 paging: false,
1433 select: false,
1434 });
1435 });
1436 </script>';
1437
1438 echo $content;
1439
1440 echo '</div>';
1441
1442}
1443
1444
1445function opcom_campaigns_list()
1446{
1447
1448 $package_types = array(
1449 'trial' => 'Trial',
1450 'trial-single' => 'Trial Single',
1451 'normal' => 'Normal',
1452 'extra' => 'Extra',
1453 'restricted' => 'Restricted'
1454 );
1455
1456 if(current_user_can('manage_options'))
1457 {
1458 global $wpdb, $sql_fields;
1459 echo '<div class="wrap">';
1460 echo '<style> .package_course_list { width: 42%; float: left; padding-right: 5%; } </style>';
1461 if(isset($_GET['edit']))
1462 {
1463
1464 $sql = "SELECT ID, post_title, '1' as site_id FROM $wpdb->posts
1465 WHERE post_type = 'sfwd-courses' AND post_status = 'publish'
1466 ORDER BY site_id, post_title ASC";
1467 $pageposts = $wpdb->get_results($sql, OBJECT);
1468
1469 if(function_exists('switch_to_blog'))
1470 {
1471 $sql2 = "SELECT ID, post_title, '5' as site_id FROM wpopi_5_posts
1472 WHERE post_type = 'sfwd-courses' AND post_status = 'publish'
1473 ORDER BY site_id, post_title ASC";
1474 $pageposts2 = $wpdb->get_results($sql2, OBJECT);
1475 $pageposts = array_merge($pageposts, $pageposts2);
1476 }
1477
1478 if($_POST['campaign-discount_code'])
1479 {
1480 // Save course stuff
1481
1482 write_log('-------------------- ');
1483 write_log(' Update initialized ');
1484 write_log('-------------------- ');
1485
1486 if(intval($_POST['campaign-upgrade_path']) == 0)
1487 {
1488 $upd_path = null;
1489 }
1490 else
1491 {
1492 $upd_path = intval($_POST['campaign-upgrade_path']);
1493 }
1494
1495 $update_campaign = array(
1496 'discount_code' => $_POST['campaign-discount_code'],
1497 'description' => $_POST['campaign-description'],
1498 'order_terms' => $_POST['campaign-order_terms'],
1499 'campaign_start' => $_POST['campaign-campaign_start'],
1500 'campaign_end' => $_POST['campaign-campaign_end'],
1501 'free_days' => $_POST['campaign-free_days'],
1502 'cancel_delay' => $_POST['campaign-cancel_delay'],
1503 'discount_percentage' => $_POST['campaign-discount_percentage']
1504
1505 );
1506 $wpdb->update('wpopi_opcom_campaign', $update_campaign, array('campaign_id' => $_GET['edit']));
1507
1508 }
1509
1510 $campaign = $wpdb->get_row('SELECT '. $sql_fields['campaign'] .'
1511 FROM wpopi_opcom_campaign WHERE campaign_id = '. $_GET['edit']);
1512 echo '<h1 style="padding-bottom: 20px;">Edit campaign</h1>';
1513 echo '<p><a href="/wp-admin/admin.php?page=opcom_campaigns">Back to list</a></p>';
1514 echo '<form method="post" action="/wp-admin/admin.php?page=opcom_campaigns&edit='. $_GET['edit'] .'">';
1515 echo '<div class="postbox" style="width: 55%;"><div class="inside"><table class="form-table">';
1516 foreach(explode(', ', $sql_fields['campaign']) as $field)
1517 {
1518 echo '<tr>';
1519 if($field == 'campaign_id')
1520 {
1521 echo '<th>'. ucfirst(str_replace('_', ' ', $field)) .'</th>';
1522 echo '<td>'. $campaign->$field .'</td>';
1523 }
1524 else if($field == 'description')
1525 {
1526 echo '<th>'. ucfirst(str_replace('_', ' ', $field)) .'</th>';
1527 echo '<td><textarea style="width: 400px; height: 100px;" name="campaign-'. $field .'">'. $campaign->$field .'</textarea>';
1528 echo '</td>';
1529 }
1530 else if($field == 'order_terms')
1531 {
1532 echo '<th>'. ucfirst(str_replace('_', ' ', $field)) .'</th>';
1533 echo '<td><textarea style="width: 400px; height: 100px;" name="campaign-'. $field .'">'. $campaign->$field .'</textarea>';
1534 echo '</td>';
1535 }
1536 else if($field == 'campaign_start')
1537 {
1538 echo '<th>'. ucfirst(str_replace('_', ' ', $field)) .'</th>';
1539 echo '<td><input class="c_start" name="campaign-'. $field .'" value="'. $campaign->$field .'" />';
1540 echo '</td>';
1541 }
1542 else if($field == 'campaign_end')
1543 {
1544 echo '<th>'. ucfirst(str_replace('_', ' ', $field)) .'</th>';
1545 echo '<td><input class="c_end" name="campaign-'. $field .'" value="'. $campaign->$field .'" />';
1546 echo '</td>';
1547 }
1548 else
1549 {
1550 echo '<th>'. ucfirst(str_replace('_', ' ', $field)) .'</th>';
1551 echo '<td><input name="campaign-'. $field .'" value="'. $campaign->$field .'" />';
1552 echo '</td>';
1553 }
1554 echo '</tr>';
1555 }
1556 echo '</table></div></div>';
1557
1558 echo '</div><div style="clear: both;"></div>';
1559
1560 add_datepickers();
1561
1562// TODO: get tikon courses
1563
1564 echo '<input type="hidden" name="action-campaign-nonce" value="'. wp_create_nonce('opcom-campaign') .'" />';
1565 echo '<br /><input type="submit" value="Save" class="button-primary" />';
1566 echo '</form>';
1567
1568 }
1569 else if(isset($_GET['add']))
1570 {
1571
1572 $campaign = $wpdb->get_row('SELECT '. $sql_fields['campaign'] .'
1573 FROM wpopi_opcom_campaign WHERE campaign_id = '. $_GET['edit']);
1574 echo '<h1 style="padding-bottom: 20px;">Add new campaign</h1>';
1575 echo '<p><a href="/wp-admin/admin.php?page=opcom_campaigns">Back to list</a></p>';
1576 echo '<form method="post" action="/wp-admin/admin.php?page=opcom_campaigns&create'. $_GET['edit'] .'">';
1577 echo '<div class="postbox" style="width: 55%;"><div class="inside"><table class="form-table">';
1578 foreach(explode(', ', $sql_fields['campaign']) as $field)
1579 {
1580 echo '<tr>';
1581 if($field == 'campaign_id')
1582 {
1583 // No need to show campaign id for creation since its auto-incrementing.
1584 }
1585 else if($field == 'description')
1586 {
1587 echo '<th>'. ucfirst(str_replace('_', ' ', $field)) .'</th>';
1588 echo '<td><textarea style="width: 400px; height: 100px;" name="campaign-'. $field .'">'. $campaign->$field .'</textarea>';
1589 echo '</td>';
1590 }
1591 else if($field == 'order_terms')
1592 {
1593 echo '<th>'. ucfirst(str_replace('_', ' ', $field)) .'</th>';
1594 echo '<td><textarea style="width: 400px; height: 100px;" name="campaign-'. $field .'">'. $campaign->$field .'</textarea>';
1595 echo '</td>';
1596 }
1597 else if($field == 'campaign_start')
1598 {
1599 echo '<th>'. ucfirst(str_replace('_', ' ', $field)) .'</th>';
1600 echo '<td><input class="c_start" name="campaign-'. $field .'" value="'. $campaign->$field .'" />';
1601 echo '</td>';
1602 }
1603 else if($field == 'campaign_end')
1604 {
1605 echo '<th>'. ucfirst(str_replace('_', ' ', $field)) .'</th>';
1606 echo '<td><input class="c_end" name="campaign-'. $field .'" value="'. $campaign->$field .'" />';
1607 echo '</td>';
1608 }
1609 else
1610 {
1611 echo '<th>'. ucfirst(str_replace('_', ' ', $field)) .'</th>';
1612 echo '<td><input name="campaign-'. $field .'" value="'. $campaign->$field .'" />';
1613 echo '</td>';
1614 }
1615 echo '</tr>';
1616 }
1617
1618 echo '</table></div></div>';
1619
1620 echo '</div><div style="clear: both;"></div>';
1621
1622 add_datepickers();
1623
1624 // TODO: get tikon courses
1625 if(isset($_POST['campaign-campaign_start']) || isset($_POST['campaign-campaign_end']))
1626 {
1627 if(!check_campaign_dates($_POST['campaign-campaign_start']) || !check_campaign_dates($_POST['campaign-campaign_end']))
1628 {
1629 echo '<p class="notify">virhe</p>';
1630 }
1631 }
1632 if(isset($_POST['campaign-campaign_start']))
1633 {
1634 if(empty($_POST['campaign-discount_code']))
1635 {
1636 echo '<p ="notify">no campaign code set</p>';
1637 }
1638 }
1639 echo '<input type="hidden" name="action-campaign-nonce" value="'. wp_create_nonce('opcom-campaign') .'" />';
1640 echo '<br /><input type="submit" value="Create" class="button-primary" />';
1641 echo '</form>';
1642 }
1643 else
1644 {
1645
1646 if(isset($_GET['create']) && $_POST['campaign-discount_code'])
1647 {
1648
1649 write_log('-----------------------------------');
1650 write_log(' Creating new campaign initialized ');
1651 write_log('---------------------------------- ');
1652
1653 if(intval($_POST['campaign-upgrade_path']) == 0)
1654 {
1655 $upd_path = null;
1656 }
1657 else
1658 {
1659 $upd_path = intval($_POST['campaign-upgrade_path']);
1660 }
1661
1662 $update_campaign = array(
1663 'discount_code' => $_POST['campaign-discount_code'],
1664 'description' => $_POST['campaign-description'],
1665 'order_terms' => $_POST['campaign-order_terms'],
1666 'campaign_start' => $_POST['campaign-campaign_start'],
1667 'campaign_end' => $_POST['campaign-campaign_end'],
1668 'free_days' => $_POST['campaign-free_days'],
1669 'cancel_delay' => $_POST['campaign-cancel_delay'],
1670 'discount_percentage' => $_POST['campaign-discount_percentage']
1671 );
1672 $wpdb->insert('wpopi_opcom_campaign', $update_campaign);
1673
1674
1675 }
1676 $campaigns = $wpdb->get_results('SELECT '. $sql_fields['campaign'] .' FROM wpopi_opcom_campaign', OBJECT_K);
1677 opcom_admin_styles();
1678 echo '<h1 style="padding-bottom: 20px;">Campaigns <span class="dashicons dashicons-tickets-alt opcom"></span></h1>';
1679
1680 ?>
1681 <table class="wp-list-table widefat striped" style="width: 75%; float: left !important;">
1682 <thead>
1683 <tr>
1684 <th>ID</td>
1685 <th>Discount code</strong></th>
1686 <th>Description</strong></th>
1687 <th>Campaign start</th>
1688 <th>Campaign end</th>
1689 <th>Free days</th>
1690 <th>Cancel delay</th>
1691 <th>Discount %</th>
1692 </tr>
1693 </thead>
1694 <tbody>
1695 <?php
1696
1697 foreach($campaigns as $campaign )
1698 {
1699 echo '<tr>';
1700 echo '<td>'. $campaign->campaign_id .'</td>';
1701 echo '<td><a href="/wp-admin/admin.php?page=opcom_campaigns&edit='. $campaign->campaign_id .'">'. $campaign->discount_code .'</a></td>';
1702 echo '<td>'. $campaign->description .'</td>';
1703 echo '<td>'. $campaign->campaign_start .'</td>';
1704 echo '<td>'. $campaign->campaign_end .'</td>';
1705 echo '<td>'. $campaign->free_days.'</td>';
1706 echo '<td>'. $campaign->cancel_delay.'</td>';
1707 echo '<td>'. $campaign->discount_percentage.'</td>';
1708 echo '</tr>';
1709 }
1710 echo '</tbody></table>';
1711
1712 echo '<a href="/wp-admin/admin.php?page=opcom_campaigns&add=1" style="color: white; text-shadow: none; text-decoration: none;">';
1713 echo '<input class="button-primary" type="submit" value="Add" style="margin-right: 25%; margin-top: 20px;">';
1714 echo '</a>';
1715 //echo '</div';
1716
1717 }
1718 echo '</div>';
1719
1720 }
1721}
1722
1723function check_campaign_dates($date)
1724{
1725 $tempDate = explode('-', $date);
1726 // checkdate(month, day, year)
1727 return checkdate($tempDate[1], $tempDate[2], $tempDate[0]);
1728}
1729
1730function add_datepickers()
1731{
1732 ?>
1733 <script>
1734 jQuery( document ).ready(function() {
1735 jQuery('.c_start').datepicker({
1736 format: "yyyy-mm-dd",
1737 language: "fi",
1738 autoclose: true
1739 });
1740
1741 jQuery('.c_end').datepicker({
1742 format: "yyyy-mm-dd",
1743 language: "fi",
1744 autoclose: true
1745 });
1746
1747 });
1748 </script>
1749 <?php
1750}
1751
1752function opcom_admin_styles()
1753{
1754 echo '<style>
1755 table.userlist { }
1756 table.userlist td { padding-right: 15px; }
1757 .displaying-num { padding-left: 10px; padding-right: 10px; }
1758 table.userlist .date { width: 80px; }
1759 input[type="text"], textarea { width: 280px; }
1760 fieldset { border: 1px solid #999; padding: 0px 20px 5px; margin: 20px 20px 0 0; width: 290px; float: left; }
1761 .edit_description { float: left; width: 60%; }
1762 .right { float: left; width: 30%; padding-top: 12px; }
1763 table.order_row { margin-top: 40px; }
1764 table.order_row td { padding-right: 20px; }
1765 table.order_row td input { width: 70px; }
1766 table.order_row td input.row-description, table.order_row td input.row-extra-description { width: 400px; }
1767 select.row-new-extra-package_id { min-width: 150px; }
1768 table tr td { vertical-align: text-top; }
1769 tr.multiple td { background-color: #eaeaea; }
1770 p.error { font-size: 20px; color: #ff0000; }
1771 select.action-menu, label.action-menu { font-size: 11px; }
1772 thead.billing_head th { border-top: 1px solid #ddd; font-size: 13px; }
1773 thead.billing_head:first-child th { border-top: 0; }
1774 form.billing_list { width: 25%; float; left; padding-top: 10px; }
1775 tr.add_tikon_extra td { opacity: 0.4 }
1776 .tablenav-pages.opinahjo { padding: 6px 8px; }
1777 .opcom_billinghistory_totals td { line-height: 15px; padding-right: 10px; }
1778 /* tablessorter */
1779 table.userlist thead tr th, table.userlist tfoot tr th { border-bottom: 1px solid #999; padding: 6px 4px 6px 9px; font-weight: 400; }
1780 .manipulate { cursor: pointer; }
1781 .stuffbox li { padding: 3px 10px; margin-bottom: 0; }
1782 .stuffbox li.selected { background: #e5e5e5; }
1783 h1 span.dashicons.opcom { font-size: 30px; margin-left: 10px; }
1784 .userlist_container.memberlist table.userlist td { font-size: 13px; }
1785 .userlist_container.memberlist { max-width: 100%; }
1786 .userlist_container.memberlist #userlist_wrapper td { padding-right: 0px !important; }
1787 .userlist_container.memberlist #userlist_wrapper td:first-child { }
1788 .dt-buttons { padding-left: 40px !important; }
1789 .stuffbox .box { width: 33%; float: left; }
1790 #userlist.invoicing_list td { font-size: 12px; }
1791 #ld_course_info { display: none; }
1792 </style>
1793 <div class="wrap">';
1794 /*
1795 td.invoicing_sent { border-left: 4px solid #039403; } #646fbb;
1796 td.invoicing_status { font-size: 11px; }
1797 td.invoicing_sent-history { border-left: 4px solid #20c720; } #e06255;
1798 td.invoicing_tikon { border-left: 4px solid #f8981d; }
1799 td.invoicing_new { border-left: 4px solid #83bcce }
1800 */
1801}
1802
1803/**
1804 * Shows order list or editing screen
1805 */
1806function opcom_billing_list()
1807{
1808
1809 $billing_year = date('Y');
1810 $billing_month = date('m');
1811 if(current_user_can('manage_options'))
1812 {
1813 opcom_admin_styles();
1814 if(isset($_GET['edit']))
1815 {
1816 opcom_show_billing_editing_screen($_GET['edit'], $billing_year, $billing_month);
1817 }
1818 else
1819 {
1820 opcom_show_billing_user_list($billing_year, $billing_month);
1821 }
1822 echo '</div>';
1823 }
1824}
1825
1826/**
1827 * Fairly straightforward export. Heavily depends on Wordpress.
1828 */
1829add_action( 'admin_init', 'opcom_billing_user_export' );
1830function opcom_billing_user_export()
1831{
1832
1833 if ( !empty( $_REQUEST['opcom_billing_export_list'] ) && !empty( $_REQUEST['opcom-nonce'] ) )
1834 {
1835 if(current_user_can('manage_options'))
1836 {
1837 $billing_year = date('Y');
1838 $billing_month = date('m');
1839 global $wpdb, $billing_fields, $export_fields, $finvoice_operators, $sql_fields;
1840
1841 $packages = $wpdb->get_results('SELECT package_id, name, price, type FROM wpopi_opcom_package', OBJECT_K);
1842 $campaigns = $wpdb->get_results('SELECT campaign_id, discount_code, discount_percentage FROM wpopi_opcom_campaign', OBJECT_K);
1843
1844 /* if(!empty($_GET['status']))
1845 {
1846 $sql_status = "WHERE order_status = '". $_GET['status'] ."'";
1847 }
1848 else
1849 {
1850 $sql_status = "WHERE order_status = 'success'";
1851 } */
1852
1853 $results = $wpdb->get_results("
1854 SELECT ". $sql_fields['order'] ."
1855 FROM wpopi_opcom_order
1856 ". $sql_status); // ORDER BY order_status DESC, vatcode"
1857
1858 $order_statuses = $wpdb->get_results("SELECT DISTINCT order_status FROM wpopi_opcom_order");
1859
1860 $export_rows = array();
1861 $export_rows[] = array(
1862 'order_id' => 'order_id',
1863 'user_id' => 'user_id',
1864 'user_login' => 'user_login',
1865 'first_name' => 'first_name',
1866 'last_name' => 'last_name',
1867 'user_email' => 'user_email',
1868 'phone' => 'phone',
1869 'package_id' => 'package_id',
1870 'package_name' => 'package_name',
1871 'billing_amount' => 'billing_amount',
1872 'tax' => 'tax',
1873 'discount_percentage' => 'discount_percentage',
1874 'total' => 'total',
1875 'payment_type' => 'payment_type',
1876 'order_status' => 'order_status',
1877 'gateway' => 'gateway', // obsolete
1878 'gateway_environment' => 'gateway_environment', // obsolete
1879 'payment_transaction_id' => 'payment_transaction_id', // obsolete
1880 'subscription_transaction_id' => 'subscription_transaction_id', // obsolete
1881 'campaign_id' => 'campaign_id',
1882 'campaign_name' => 'campaign_name',
1883 'order_date' => 'order_date',
1884 'cancel_date' => 'cancel_date',
1885 'service_providers' => 'service_providers',
1886 'tikon_orderid' => 'tikon_orderid', // what is this I don't even
1887 'company' => 'company',
1888 'address' => 'address',
1889 'postalcode' => 'postalcode',
1890 'city' => 'city',
1891 'billing_channel' => 'billing_channel',
1892 'billing_vlasku' => 'billing_vlasku',
1893 'billing_email' => 'billing_email',
1894 'vatcode' => 'vatcode',
1895 'notes' => 'notes'
1896 );
1897 foreach($results as $order)
1898 {
1899 $user = get_userdata($order->user_id);
1900 $usermeta = get_user_meta($order->user_id);
1901
1902 $order_lines = $wpdb->get_results("SELECT order_id, package_id, description, billing_amount, tax_percentage, discount_percentage, manual_discount
1903 FROM wpopi_opcom_order_line
1904 WHERE order_id = '". $order->order_id ."'");
1905 // LEFT JOIN wpopi_opcom_package ON wpopi_opcom_package.package_id = wpopi_opcom_order_line.package_id
1906
1907 $cancel_date = '';
1908 $invoice_cancel_date = '';
1909 if($order->cancel_date)
1910 {
1911 $cancel_date = date('Y-m-d', strtotime($order->cancel_date));
1912 $invoice_cancel_date = date('Ymd', strtotime($order->cancel_date));
1913 }
1914
1915 $vatcode = '';
1916 $taxcode = '';
1917 $orgnumber = '';
1918 if($order->vatcode)
1919 {
1920 $vat_fixed = str_replace(' ', '', $order->vatcode);
1921 if($vat_fixed == '-')
1922 {
1923 $vat_fixed = '';
1924 }
1925 $vatcode = $vat_fixed;
1926 $taxcode = 'FI'. str_replace('-', '', $vat_fixed);
1927 $orgnumber = str_replace('-', '', ltrim($vat_fixed, 0));
1928 }
1929
1930 $billing_identifier = '';
1931 $channelcode = 0;
1932 $laskukanava = '';
1933 $billing_email = $user->user_email;
1934 $billing_service_ok = false;
1935
1936 if($usermeta['oa_billing_ovt'][0] == 'billing_paper')
1937 {
1938 $channelcode = 2;
1939 $laskukanava = 'paperi';
1940 }
1941 elseif($usermeta['oa_billing_ovt'][0] == 'billing_web')
1942 {
1943 $channelcode = 3;
1944 $billing_identifier = str_replace(' ', '', $usermeta['oa_billing_vlasku'][0]). '@' .$usermeta['oa_billing_service'][0];
1945 $laskukanava = 'verkkolasku';
1946 if(isset($usermeta['oa_billing_service'][0]) && $usermeta['oa_billing_service'][0] != '' && $usermeta['oa_billing_service'][0] != 'op0' && array_key_exists($usermeta['oa_billing_service'][0], $finvoice_operators))
1947 {
1948 $billing_service_ok = true;
1949 $result = preg_replace('/[a-zA-Z0-9_\-åäö ]*\((\w+)( tai 003721291126)?\)$/', '$1', $finvoice_operators[$usermeta['oa_billing_service'][0]]);
1950 $billing_identifier = str_replace(' ', '', $usermeta['oa_billing_vlasku'][0]). '@' .$result;
1951 }
1952 }
1953 elseif($usermeta['oa_billing_ovt'][0] == 'billing_email')
1954 {
1955 $channelcode = 1;
1956 if(!empty($usermeta['oa_billing_email'][0]))
1957 {
1958 $billing_email = $usermeta['oa_billing_email'][0];
1959 }
1960 else
1961 {
1962 $billing_email = $user->user_email;
1963 }
1964 $laskukanava = 'email';
1965 }
1966 elseif(!empty($usermeta['oa_billing_ovt'][0]))
1967 {
1968 $channelcode = 3;
1969 $billing_identifier = $usermeta['oa_billing_ovt'][0]. '@' .$usermeta['oa_billing_service'][0];
1970 $laskukanava = 'verkkolasku';
1971 }
1972 else
1973 {
1974 $laskukanava = 'ei tiedossa, oletus email';
1975 $channelcode = 1;
1976 $billing_email = $user->user_email;
1977 }
1978
1979 $order_stamp = strtotime($order->order_date);
1980 $extra_days = 0;
1981 $startdate = $billing_year.'-'.$billing_month.'-01';
1982 $enddate = $billing_year.'-'.$billing_month.'-'. date('t', strtotime($billing_year.'-'.$billing_month.'-01'));
1983 if(date('Y', $order_stamp) == $billing_year && date('n', $order_stamp) == intval($billing_month) - 1)
1984 {
1985 $first_day = date('d', $order_stamp);
1986 $last_day = date('t', $order_stamp);
1987 $extra_days = intval($last_day) - intval($first_day);
1988 $start_month = intval($billing_month) - 1;
1989 $startdate = $billing_year.'-'.$start_month.'-'.$first_day;
1990 }
1991
1992 $billing_id = md5($billing_email. ' ' .$vatcode. ' ' .$order->order_date. ' ' .date('Ymd'));
1993
1994 $total = 0;
1995 $orderrows = array();
1996 $line_xml_total = array();
1997 $display_invoice_rows = '';
1998 $display_sums = '';
1999 foreach($order_lines as $line)
2000 {
2001 $discount = '';
2002 $discount_invoice = 0;
2003 if($line->discount_percentage)
2004 {
2005 $discount = '-'. $line->discount_percentage .' %';
2006 $discount_invoice = $line->discount_percentage;
2007 }
2008 $line_billing_amout = $line->billing_amount;
2009 if($extra_days != 0)
2010 {
2011 $line_billing_amout = $line->billing_amount + ($line->billing_amount / $last_day * $extra_days);
2012 }
2013
2014 $display_invoice_rows .= ' '. round($line_billing_amout, 2) .' € '. $discount .'</td>';
2015
2016
2017 $display_sums .= $packages[$line->package_id]->name. ' ' .round($line_billing_amout, 2) .' € '. $discount;
2018 if($line->discount_percentage)
2019 {
2020 $total = $total + $line->billing_amount - ($line->billing_amount * $line->discount_percentage / 100);
2021 }
2022 else
2023 {
2024 $total = $total + $line->billing_amount;
2025 }
2026
2027 if($line->description == 'Tikonin koulutukset')
2028 {
2029 $line_descr = '';
2030 }
2031 else
2032 {
2033 $line_descr = $line->description .', '.opcom_show_dates($order->order_date, $billing_year, $billing_month);
2034 }
2035
2036 }
2037 $tikon = '';
2038 if(isset($order_lines[1]))
2039 {
2040 $tikon = 'Tikon';
2041 }
2042
2043 $export_rows[] = array(
2044 'order_id' => $order->order_id,
2045 'user_id' => $order->user_id,
2046 'user_login' => $user->user_login,
2047 'first_name' => $usermeta['first_name'][0],
2048 'last_name' => $usermeta['last_name'][0],
2049 'user_email' => $user->user_email,
2050 'phone' => $usermeta['oa_phone'][0],
2051 'package_id' => $order_lines[0]->package_id,
2052 'package_name' => $packages[$order_lines[0]->package_id]->name,
2053 'billing_amount' => $order_lines[0]->billing_amount,
2054 'tax' => 24,
2055 'discount_percentage' => $order_lines[0]->discount_percentage,
2056 'total' => $order_lines[0]->billing_amount - ($order_lines[0]->billing_amount * $order_lines[0]->discount_percentage / 100),
2057 'payment_type' => '',
2058 'order_status' => $order->order_status,
2059 'gateway' => '', // obsolete
2060 'gateway_environment' => '', // obsolete
2061 'payment_transaction_id' => '', // obsolete
2062 'subscription_transaction_id' => '', // obsolete
2063 'campaign_id' => $order->campaign_id,
2064 'campaign_name' => $campaigns[$order->campaign_id]->discount_code,
2065 'order_date' => $order->order_date,
2066 'access_date' => $order->order_date,
2067 'cancel_date' => $cancel_date,
2068 'service_providers' => $tikon,
2069 'tikon_orderid' => '', // what is this I don't even
2070 'company' => $usermeta['company'][0],
2071 'address' => $usermeta['oa_address'][0],
2072 'postalcode' => $usermeta['oa_postalcode'][0],
2073 'city' => $usermeta['oa_city'][0],
2074 'billing_channel' => $laskukanava,
2075 'billing_vlasku' => $billing_identifier,
2076 'billing_email' => $billing_email,
2077 'vatcode' => $order->vatcode,
2078 'notes' => $order->notes
2079 );
2080
2081 }
2082 opcom_excel_export($export_rows, 'orders.xls', 'Opinahjo');
2083 die();
2084 }
2085 }
2086}
2087
2088/*
2089function write_log_by_order_id($order_id, $data)
2090{
2091 if($order_id == 5317)
2092 {
2093 write_log($data);
2094 }
2095} */
2096
2097require_once('script_billing_list.php');
2098
2099/**
2100 * Order log for Members.
2101 */
2102function opcom_show_order_log()
2103{
2104 global $wpdb;
2105 echo '<div class="wrap">
2106 <h1>Order log <span class="dashicons dashicons-admin-page opcom"></span></h1>
2107 <div class="userlist_container">';
2108
2109 if(current_user_can('manage_options'))
2110 {
2111 $and = '';
2112 if(isset($_GET['user_id']) && is_numeric($_GET['user_id']))
2113 {
2114 $and = ' AND user_id = ' .urlencode($_GET['user_id']);
2115 }
2116 else
2117 {
2118 echo '<p>Displaying 200 latest entries.</p>';
2119 }
2120
2121 echo '<table id="userlist" class="userlist widefat striped invoicing_list">';
2122 $sql = "SELECT * FROM wpopi_opcom_order_log WHERE channel = 'opcom-order' ". $and ."
2123 ORDER BY time DESC LIMIT 200";
2124 // ORDER BY user_id
2125 $log_entries = $wpdb->get_results($sql, OBJECT);
2126 echo $wpdb->last_error;
2127 // print_r($log_entries);
2128 echo '<thead><tr>
2129 <th>time</th>
2130 <th>admin id</th>
2131 <th>order id</th>
2132 <th>user</th>
2133 <th>action</th>
2134 <th>log entry (partial)</th>
2135 </tr></thead><tbody>';
2136 foreach($log_entries as $entry)
2137 {
2138 $user = get_userdata($entry->user_id);
2139 $message = unserialize($entry->message);
2140 echo '<tr>';
2141 echo '<td>'. date('Y-m-d H:i:s', $entry->time) .'</td>';
2142 echo '<td>'. $entry->admin_id .'</td>';
2143 echo '<td>'. $entry->order_id .'</td>';
2144 echo '<td>'. $user->user_email .'</td>';
2145 echo '<td>'. ucfirst(str_replace('_', ' ', $entry->action)) .'</td>';
2146 echo '<td>';
2147 if(isset($message['order']))
2148 {
2149 echo 'order_status: '. $message['order']->order_status;
2150 echo '<br />order_date: '. $message['order']->order_date;
2151 if($message['order']->cancel_date)
2152 {
2153 echo '<br />cancel_date: '. $message['order']->cancel_date;
2154 }
2155 }
2156 else
2157 {
2158 if(isset($message[0]))
2159 {
2160 foreach($message as $row)
2161 {
2162 echo 'package_id: '. $row->package_id .'<br />';
2163 }
2164 }
2165 else
2166 {
2167 echo 'package_id: '. $message['package_id'] .'<br />';
2168 }
2169 }
2170 echo '<div style="display: none;">';
2171 var_dump($message);
2172 echo '</div>';
2173 echo '</td>';
2174 echo '</tr>';
2175 }
2176 echo '</tbody></table>';
2177
2178 }
2179 echo '</div></div>';
2180}
2181
2182function opcom_members_list()
2183{
2184 global $wpdb, $sql_fields;
2185
2186// TBA: all active accounts
2187
2188 $order_status = '';
2189 $status_set = false;
2190 $is_front = true;
2191
2192 if($_GET['status'] == 'active'
2193 || $_GET['status'] == 'success'
2194 || $_GET['status'] == 'accountor'
2195 || $_GET['status'] == 'cancelled'
2196 || $_GET['status'] == 'trial')
2197 {
2198 $order_status .= " AND order_status IN ('". $_GET['status'] ."')";
2199 $limit = "";
2200 $status_set = true;
2201 $is_front = false;
2202 }
2203
2204 if(is_array($_GET['level']) || $_GET['query'] == 'all_active')
2205 {
2206 $is_front = false;
2207 }
2208
2209 if($status_set === false)
2210 {
2211 $order_status .= " AND order_status IN ('active', 'success', 'accountor', 'cancelled', 'trial')";
2212 }
2213
2214 if($is_front === true)
2215 {
2216 $limit = "LIMIT 100";
2217 }
2218
2219/* $array = array('test', 'bla');
2220$base = base64_encode(json_encode($array));
2221echo $base .'<br /><br />';
2222print_r(json_decode(base64_decode($base))); */
2223
2224 $packages = $wpdb->get_results('SELECT '. $sql_fields['package'] .' FROM wpopi_opcom_package ORDER BY upgrade_path', OBJECT_K);
2225 $order_rows = $wpdb->get_results("SELECT ". $sql_fields['order_line'] .", order_status, order_date, cancel_date, end_date, user_id, user_email, display_name
2226 FROM wpopi_opcom_order_line, wpopi_opcom_order, wpopi_users
2227 WHERE wpopi_opcom_order.order_id = wpopi_opcom_order_line.order_id
2228 AND wpopi_users.ID = wpopi_opcom_order.user_id
2229 ". $order_status ."
2230 AND user_email NOT LIKE '%@opinahjo.fi'
2231 ORDER BY order_id DESC ". $limit, OBJECT_K);
2232 // (SELECT line_id FROM wpopi_opcom_order_line line WHERE package_id = 10 AND line.order_id = ord.order_id) AS tikon
2233 echo $wpdb->last_error;
2234
2235 // print_r($order_rows);
2236
2237 $order_rows_org = array();
2238
2239 foreach($order_rows as $dbrow)
2240 {
2241 if( $dbrow->package_id == 10 )
2242 {
2243 $order_rows_org[$dbrow->order_id]['tikon'] = 'yes';
2244 }
2245 // Show "all active" when end date not in the past
2246 // OR Show if level set (statuses from DB query)
2247 // OR Show if the status AND level not set
2248 // OR It's the front
2249 elseif(
2250 ( $_GET['query'] == 'all_active' && ( empty($dbrow->end_date) || date('Y-m-d') <= substr($dbrow->end_date, 0, 10) ) )
2251 || in_array($dbrow->package_id, $_GET['level'])
2252 || isset($_GET['status']) && !isset($_GET['level'])
2253 || $is_front )
2254 {
2255 $order_rows_org[$dbrow->order_id]['order'] = $dbrow;
2256 }
2257 }
2258
2259 // print_r($order_rows_org);
2260
2261 opcom_admin_styles();
2262
2263 $table_head = '<thead>
2264 <tr>
2265 <!-- th>Order #</th -->
2266 <th>Order date</th>
2267 <th>Status</th>
2268 <th>Package</th>
2269 <th>Extra</th>
2270 <th>Firstname</th>
2271 <th>Lastname</th>
2272 <th>Email</th>
2273 <th>Cancel date</th>
2274 <th>End date</th>
2275 <th></th>
2276 </tr></thead>';
2277
2278 echo '<div class="wrap"><h1>Members <span class="dashicons dashicons-groups opcom"></span></h1>';
2279 if($is_front === true)
2280 {
2281 echo '<p>Last 50 memberships</p>';
2282 }
2283 else
2284 {
2285 echo '<p>Status: '. $_GET['status'] .'</p>';
2286 }
2287
2288 echo '
2289 <script type="text/javascript" language="javascript" src="/wp-content/plugins/opinahjo-common/js/DataTables/datatables.js"></script>
2290 <script type="text/javascript" src="/wp-content/plugins/opinahjo-common/js/DataTables/date-euro-mod.js"></script>';
2291
2292 echo '
2293 <link rel="stylesheet" type="text/css" href="/wp-content/plugins/opinahjo-common/js/DataTables/datatables.min.css" />
2294 <script type="text/javascript">
2295
2296 jQuery( document ).ready(function() {
2297 jQuery("#userlist").DataTable({
2298 select: true,
2299 "order": [[ 0, "desc" ]],
2300 "lengthMenu": [ [25, 50, 100, -1], [25, 50, 100, "All"] ],
2301 "columnDefs": [
2302 { "orderable": false, "targets": [9] },
2303 ],
2304 dom: "lBfrtip",
2305 buttons: [
2306 "copyHtml5",
2307 {
2308 extend: "copyHtml5",
2309 text: "Copy selected",
2310 exportOptions: {
2311 modifier: {
2312 selected: true
2313 }
2314 }
2315 },
2316 {
2317 extend: "excelHtml5",
2318 text: "Export all",
2319 },
2320 {
2321 extend: "excelHtml5",
2322 text: "Export selected",
2323 exportOptions: {
2324 modifier: {
2325 selected: true
2326 }
2327 }
2328 }
2329 ]
2330 });
2331 });
2332
2333 </script>
2334 <div class="stuffbox handlediv" style="float: left; width: 620px; margin-bottom: 20px;">
2335 <div class="inside"><div class="box">';
2336
2337 echo '<h2>Active accounts</h2><ul>';
2338 echo '<li><a href="/wp-admin/admin.php?page=opcom_members_list">Most recent</a></li>';
2339 echo '<li><a href="/wp-admin/admin.php?page=opcom_members_list&query=all_active">All active</a></li>';
2340
2341 echo '</ul></div><div class="box"><h2>Filter by order status</h2><ul>';
2342
2343 opcom_render_memberlist_link('trial', 'Trial', 'status', $_GET['status']);
2344 opcom_render_memberlist_link('success', 'Success', 'status', $_GET['status']);
2345 opcom_render_memberlist_link('cancelled', 'Cancelled', 'status', $_GET['status']);
2346 opcom_render_memberlist_link('active', 'Active', 'status', $_GET['status']);
2347 opcom_render_memberlist_link('accountor', 'Accountor', 'status', $_GET['status']);
2348 echo '</ul></div>';
2349 echo '<div class="box"><h2>Filter by package</h2><ul>';
2350 opcom_render_memberlist_link('9', 'S-paketti', 'level[]', $_GET['level']);
2351 opcom_render_memberlist_link('1', 'M-paketti', 'level[]', $_GET['level']);
2352 opcom_render_memberlist_link('2', 'L-paketti', 'level[]', $_GET['level']);
2353 opcom_render_memberlist_link('6', 'XL-paketti', 'level[]', $_GET['level']);
2354
2355 $trial_url_suffix = '';
2356 foreach($packages as $pack)
2357 {
2358 if($pack->type == 'trial' || $pack->type == 'trial-single')
2359 {
2360 $trial_url_suffix .= '&level[]='. $pack->package_id;
2361 }
2362 }
2363 echo '<li><a href="/wp-admin/admin.php?page=opcom_members_list'. $trial_url_suffix .'">Trial</a></li>';
2364
2365 echo '</ul></div></div>
2366 </div>
2367
2368 <div class="userlist_container memberlist">
2369 <table id="userlist" class="userlist widefat striped">'. $table_head .'<tbody>';
2370
2371 $i = 1;
2372 foreach($order_rows_org as $row)
2373 {
2374 if(!empty($row['order']))
2375 {
2376 echo '<tr>';
2377 echo '<!-- td>'. $row['order']->order_id .'</td -->';
2378 echo '<td>'. substr($row['order']->order_date, 0, 10) .'</td>';
2379 echo '<td>'. $row['order']->order_status .'</td>';
2380 echo '<td>'. $packages[$row['order']->package_id]->name .'</td>';
2381 if($row['tikon'] == 'yes')
2382 {
2383 echo '<td>Tikon</td>';
2384 }
2385 else
2386 {
2387 echo '<td></td>';
2388 }
2389 $username = explode(' ', $row['order']->display_name);
2390 echo '<td>'. $username[0] .'</td>';
2391 echo '<td>'. $username[1] .'</td>';
2392 echo '<td>'. $row['order']->user_email .'</td>';
2393
2394 echo '<td>'. substr($row['order']->cancel_date, 0, 10) .'</td>';
2395 echo '<td>'. substr($row['order']->end_date, 0, 10) .'</td>';
2396 // echo '<td>'. print_r($row, true) .'<br />'. print_r($user, true) .'</td>';
2397 echo '<td><a title="User: '. $row['order']->user_id .'" href="/wp-admin/user-edit.php?user_id='. $row['order']->user_id .'"><span class="dashicons dashicons-admin-users"></span></a> ';
2398 echo '<a title="Order: '. $row['order']->order_id .'" href="/wp-admin/admin.php?page=opcom_billing_list&edit='. $row['order']->order_id .'"><span class="dashicons dashicons-cart"></span></a></td>';
2399
2400 echo '</tr>';
2401 if($i >= 50 && $is_front === true)
2402 {
2403 break;
2404 }
2405 $i++;
2406 }
2407 }
2408
2409 echo '</tbody></table></div></div>';
2410
2411}
2412
2413function opcom_render_memberlist_link($value, $text, $type, $current_value)
2414{
2415 $url_prefix = '/wp-admin/admin.php?page=opcom_members_list';
2416 $class = '';
2417 if($current_value == $value || in_array($value, $current_value))
2418 {
2419 $class = ' class="selected" ';
2420 }
2421 $extra_attr = '';
2422 if(empty($_GET[$type]))
2423 {
2424 if($type == 'level[]' && $_GET['status'])
2425 {
2426 $extra_attr .= '&status='.$_GET['status'];
2427 }
2428 elseif($type == 'status' && is_array($_GET['level']))
2429 {
2430 foreach($_GET['level'] as $lev)
2431 {
2432 $extra_attr .= '&level[]='.$lev;
2433 }
2434
2435 }
2436 }
2437 echo '<li '. $class .'><a href="'. $url_prefix .$extra_attr .'&'. $type .'='. $value .'">'. $text .'</a></li>';
2438}
2439
2440
2441function opcom_show_billing_editing_screen($order_id, $billing_year, $billing_month, $profile_page = false)
2442{
2443
2444 global $billing_fields, $wpdb, $finvoice_operators, $sql_fields;
2445
2446 // Need these for up/downgrade calculations
2447 $packages = $wpdb->get_results('SELECT '. $sql_fields['package'] .' FROM wpopi_opcom_package ORDER BY upgrade_path', OBJECT_K);
2448 $user_id = $wpdb->get_var("SELECT user_id FROM wpopi_opcom_order WHERE order_id = '".$order_id."'");
2449
2450 global $campaigns_data;
2451 ?>
2452 <script>
2453 var campaigns_data = <?php echo json_encode($campaigns_data); ?>;
2454 </script>
2455 <?php
2456
2457 if($profile_page)
2458 {
2459
2460 ?>
2461 <script>
2462 var packages = <?php echo json_encode($packages); ?>;
2463 var cur_datetime = '<?php echo date('Y-m-d H:i:s'); ?>';
2464 jQuery(document).ready(function() {
2465
2466 jQuery('select.row-new-extra-package_id').change(function() {
2467 jQuery('tr.add_tikon_extra td').css('opacity', '1');
2468 });
2469
2470 jQuery('select.order-campaign_id').change(function() {
2471 changedates();
2472// console.log(jQuery('select.order-campaign_id').val());
2473// console.log(campaigns_data[jQuery('select.order-campaign_id').val()]['discount_percentage'] +'%');
2474 if(jQuery('select.order-campaign_id').val() != 0)
2475 {
2476 if(campaigns_data[jQuery('select.order-campaign_id').val()]['discount_percentage'] == null)
2477 {
2478 jQuery('input.row-new-discount_percentage').val('');
2479 }
2480 else
2481 {
2482 jQuery('input.row-new-discount_percentage').val(campaigns_data[jQuery('select.order-campaign_id').val()]['discount_percentage']);
2483 }
2484 }
2485 });
2486 jQuery('select.order-order_status').change(function() {
2487 changedates();
2488 });
2489 jQuery('select.row-new-package_id').change(function() {
2490// console.log(jQuery('select.row-new-package_id').val());
2491// console.log(jQuery('select.row-new-package_id option:selected').text());
2492 jQuery('input.row-new-billing_amount').val(packages[jQuery('select.row-new-package_id').val()]['price']);
2493
2494 var str = jQuery('input.row-description').val();
2495 str = str.replace(/(\w+-\w+)$/,'');
2496 str = str + packages[jQuery('select.row-new-package_id').val()]['name'];
2497 jQuery('input.row-description').val(str);
2498// console.log(str);
2499 });
2500 });
2501
2502 function changedates()
2503 {
2504 if(jQuery('input.order-order_date').val() == '')
2505 {
2506 jQuery('input.order-order_date').val(cur_datetime);
2507 }
2508 if(jQuery('input.order-access_date').val() == '')
2509 {
2510 jQuery('input.order-access_date').val(cur_datetime);
2511 }
2512 if(jQuery('select.row-new-package_id').val() == 0)
2513 {
2514 jQuery('select.row-new-package_id option[value=9]').attr('selected','selected');
2515 }
2516 }
2517
2518 </script>
2519
2520 <?php
2521 foreach($billing_fields as $f => $v)
2522 {
2523 unset($billing_fields[$f]);
2524 if($f == 'user_info_end')
2525 {
2526 break;
2527 }
2528 }
2529 foreach($billing_fields as $f => $v)
2530 {
2531 if(substr($f, 0, 3) == 'oa_')
2532 {
2533 unset($billing_fields[$f]);
2534 }
2535 }
2536 unset($billing_fields['payment_terms']);
2537 }
2538 else
2539 {
2540 ?>
2541 <script>
2542 jQuery(document).ready(function() {
2543 jQuery('select.order-campaign_id').change(function() {
2544 if(jQuery('select.order-campaign_id').val() != 0)
2545 {
2546 if(campaigns_data[jQuery('select.order-campaign_id').val()]['discount_percentage'] == null)
2547 {
2548 jQuery('input.row-change-discount_percentage').val('');
2549 }
2550 else
2551 {
2552 jQuery('input.row-change-discount_percentage').val(campaigns_data[jQuery('select.order-campaign_id').val()]['discount_percentage']);
2553 }
2554 }
2555 });
2556 });
2557 </script>
2558 <?php
2559 }
2560
2561 if($_POST['user_edit_form_order'] == 'order' && $profile_page === false)
2562 {
2563 $crm_data_order = opcom_members_save_member_order($order_id, $user_id, $profile_page);
2564 $crm_data_rows = opcom_members_save_member_rows($order_id, $user_id, $packages);
2565 }
2566
2567 if($order_id)
2568 {
2569 $order = $wpdb->get_row("
2570 SELECT ". $sql_fields['order'] ."
2571 FROM wpopi_opcom_order
2572 WHERE order_id = '$order_id'");
2573
2574 if($order->order_status != 'history')
2575 {
2576 $order_history = $wpdb->get_results("
2577 SELECT order_id, order_status
2578 FROM wpopi_opcom_order
2579 WHERE user_id = ".$order->user_id." AND order_status IN ('history', 'cancelled')");
2580 }
2581 elseif($order->order_status == 'history')
2582 {
2583 $order_active = $wpdb->get_var("
2584 SELECT order_id
2585 FROM wpopi_opcom_order
2586 WHERE user_id = ".$order->user_id." ORDER BY order_id DESC");
2587 }
2588
2589 $meta = get_user_meta($order->user_id);
2590 $user = get_userdata($order->user_id);
2591 }
2592 else
2593 {
2594 // Note: setting order ID to something wacky in case it doesn't exist
2595 $order_id = '[new order]';
2596 $user_id = $_GET['user_id'];
2597 $meta = get_user_meta($user_id);
2598 $user = get_userdata($user_id);
2599 }
2600
2601 if($_GET['prev'])
2602 {
2603 echo '<a href="/wp-admin/admin.php?page=opcom_billing_list&status='. $_GET['prev'] .'">« Back to list</a>';
2604 }
2605 if($profile_page)
2606 {
2607 echo '<h2>User\'s order</h2>';
2608 }
2609 else
2610 {
2611 echo '<h1>Edit order</h1>';
2612 }
2613
2614 echo '<div class="edit_description"><p>Order ID: ';
2615 if($profile_page)
2616 {
2617 echo '<a href="/wp-admin/admin.php?page=opcom_billing_list&edit='. $order_id .'">'. $order_id .'</a>';
2618 }
2619 else
2620 {
2621 echo $order_id;
2622 }
2623
2624 if(!$profile_page)
2625 {
2626 echo '<br />User ID: <a href="/wp-admin/user-edit.php?user_id='. $order->user_id .'">'. $order->user_id .'</a></p>';
2627 }
2628
2629 if($order_history && !$profile_page)
2630 {
2631 echo '<p>This order has historical data.';
2632 foreach($order_history as $history_item)
2633 {
2634 echo '<br /><a href="/wp-admin/admin.php?page=opcom_billing_list&edit='. $history_item->order_id .'">'. $history_item->order_id .'</a> ('. $history_item->order_status .')';
2635 }
2636 echo '</p>';
2637 }
2638 echo '<p><a target="_blank" href="/wp-admin/admin.php?page=opcom_order_log&user_id=' .$user_id. '">View order log</a></p>';
2639
2640 echo '</div>';
2641
2642 if(!$profile_page)
2643 {
2644 echo '<div class="right">';
2645 echo '<form target="_blank" name="aspnetForm" method="post" action="https://tietopalvelu.ytj.fi/yrityshaku.aspx?kielikoodi=1">
2646 <input name="hakusana" type="hidden" value="'. $meta['company'][0] .'" id="_ctl0_cphSisalto_hakusana" />
2647 <input type="submit" value="Search by Company Name on YTJ" />
2648 </form>';
2649
2650 echo '<form target="_blank" method="get" action="http://www.tieke.fi/display/verkkolasku/Verkkolaskuosoitteisto">
2651 <input name="run_1_hakusana" type="hidden" value="'. $meta['company'][0] .'" id="_ctl0_cphSisalto_hakusana" />
2652 <input name="run_1" value="run" type="hidden" />
2653 <input type="submit" value="Search by Company Name on Tieke" />
2654 </form>';
2655
2656 echo '</div><div style="clear: both;"></div>';
2657
2658 echo '<form method="post">';
2659 /* <input type="hidden" name="page" value="opcom_billing_list" />
2660 <input type="hidden" name="edit" value="'. $order_id .'" />'; */
2661 }
2662 else
2663 {
2664 echo '<div style="clear: both;"></div>';
2665 }
2666 echo '<input type="hidden" name="order_id" value="'. $order_id .'" />';
2667 $readonly = '';
2668 $disabled = '';
2669 if($order->order_status == 'history')
2670 {
2671 $readonly = 'readonly';
2672 $disabled = 'disabled';
2673 echo '<p>This page shows order history. Editing disabled.';
2674 if($order_active)
2675 {
2676 echo '<br />Current order: <a href="/wp-admin/admin.php?page=opcom_billing_list&edit='. $order_active .'">'. $order_active .'</a>';
2677 }
2678 echo '</p>';
2679 }
2680
2681 foreach($billing_fields as $key => $values)
2682 {
2683 if(substr($values['type'], 0, 8) != 'fieldset')
2684 {
2685 if(!empty($values['title']))
2686 {
2687 echo "\n<p><strong>". $values['title'] .'</strong>';
2688 }
2689 else
2690 {
2691 echo "\n<p><strong>". ucfirst(str_replace(array('oa_', '_'), array('', ' '), $key)) .'</strong>';
2692 }
2693 }
2694 $value = '';
2695 if(isset($values['sources']) && is_array($values['sources']))
2696 {
2697 $value = $order->$key;
2698 if(empty($value))
2699 {
2700 $value = $meta[$values['sources']['user']][0];
2701 }
2702 }
2703 elseif($values['source'] == 'order')
2704 {
2705 $value = $order->$key;
2706 }
2707 elseif($values['source'] == 'usermeta')
2708 {
2709 $value = $meta[$key][0];
2710 }
2711 elseif($values['source'] == 'user')
2712 {
2713 $value = $user->$key;
2714 }
2715
2716 if($values['type'] == 'select')
2717 {
2718 echo '<br /><select class="'. $values['source'] .'-'. $key .'" name="'. $values['source'] .'-'. $key .'" '. $disabled .'>';
2719 echo '<option value="0"> -- Keep the current value -- </option>';
2720 $found = false;
2721 foreach($values['select_values'] as $opt_value => $opt_title)
2722 {
2723 $selected = '';
2724 if($opt_value == $value)
2725 {
2726 $selected = ' selected ';
2727 $found = true;
2728 }
2729 echo '<option '. $selected .' value="'. $opt_value .'">'. $opt_title .'</option>';
2730 }
2731 echo '</select>';
2732 if($key == 'oa_billing_service' && substr($value, 0, 2) == 'op')
2733 {
2734 $value = $finvoice_operators[$value];
2735 }
2736 echo '<br />Value of the field: '. $value;
2737 if($key == 'oa_billing_service' && !in_array($value, $finvoice_operators))
2738 {
2739 echo '<br /><strong>Value does not match the list of operators</strong>';
2740 }
2741 elseif($key == 'oa_billing_ovt' && $found === false)
2742 {
2743 echo '<br /><strong>Verify the billing channel and delivery info</strong>';
2744 }
2745
2746 }
2747 elseif($values['type'] == 'text' || $values['type'] == 'date')
2748 {
2749 echo '<br /><input class="'. $values['source'] .'-'. $key .'" type="text" name="'. $values['source'] .'-'. $key .'" value="'. $value .'" '. $readonly .' />';
2750 }
2751 elseif($values['type'] == 'textarea')
2752 {
2753 echo '<br /><textarea name="'. $values['source'] .'-'. $key .'" '. $readonly .'>'. $value .'</textarea>';
2754 }
2755 elseif($values['type'] == 'info')
2756 {
2757 if($key == 'order_identifier')
2758 {
2759 echo '<br />'. substr($value, 0, 12);
2760 }
2761 else
2762 {
2763 echo '<br />'. $value;
2764 }
2765 }
2766 elseif($values['type'] == 'fieldset_start')
2767 {
2768 echo "\n\n<fieldset>\n<legend>". $values['title'] .'</legend>';
2769 }
2770 elseif($values['type'] == 'fieldset_end')
2771 {
2772 echo '</fieldset>';
2773 }
2774
2775 if(substr($values['type'], 0, 8) != 'fieldset')
2776 {
2777 echo '</p>';
2778 }
2779 }
2780 echo '<div style="clear: both;"></div>
2781 <input type="hidden" name="user_edit_form_order" value="order" />';
2782
2783 $results2 = $wpdb->get_results("SELECT line_id, order_id, package_id, description, billing_amount, tax_percentage, discount_percentage, manual_discount
2784 FROM wpopi_opcom_order_line
2785 WHERE order_id = '". $order_id ."'");
2786
2787 if($order_id == '[new order]' || empty($results2))
2788 {
2789
2790 echo '<table class="order_row">';
2791 echo "\n<tr>";
2792 echo '<td>Package</td>';
2793 echo '<td>Price</td>';
2794 echo '<td>Discount %</td>';
2795
2796 echo '<td>Description</td>';
2797 echo '</tr>';
2798
2799 echo '<tr>';
2800
2801 echo '<td><select class="row-new-package_id" name="row-new-package_id">';
2802 echo '<option value="0">-- none --</option>';
2803 foreach($packages as $key => $pack)
2804 {
2805 // Allow up/downgrade only to actual packages
2806 if($pack->type == 'normal' || $pack->type == 'trial' || $pack->type == 'trial-single')
2807 {
2808 $selected = '';
2809 if ($line->package_id == $key)
2810 {
2811 $selected = 'selected';
2812 }
2813 echo '<option '. $selected .' value="'. $key .'">'. $pack->name .' ('. $pack->package_id .') - '. $pack->price .' €</option>';
2814 }
2815
2816 }
2817 echo '</select></td>';
2818 echo '<td><input class="row-new-billing_amount" name="row-new-billing_amount" value="49" /></td>';
2819 echo '<td><input class="row-new-discount_percentage" name="row-new-discount_percentage" value="" /></td>';
2820
2821 echo '<td><input class="row-description" name="row-new-description" value="'. opmem_create_order_line($user->user_firstname .' '. $user->user_lastname, 'S-paketti') .'" />';
2822 echo '</tr>';
2823
2824 show_new_extra_line(true);
2825
2826 echo '</table>';
2827 echo '<input type="hidden" name="user_edit_form_rows" value="rows" />';
2828
2829 }
2830 else
2831 {
2832 // LEFT JOIN wpopi_opcom_package ON wpopi_opcom_package.package_id = wpopi_opcom_order_line.package_id
2833
2834 $orderrows = array();
2835
2836 echo '<p>Please note: changing a package will form a new order.</p>';
2837/* if(!$profile_page)
2838 {
2839 echo '<form method="post">';
2840 } */
2841 echo '<table class="order_row">';
2842 echo "\n<tr>";
2843 echo '<td>Package</td>';
2844 echo '<td>Billing amount €</td>';
2845 echo '<td>Discount %</td>';
2846
2847 echo '<td>Discounted €</td>';
2848 echo '<td>VAT %</td>';
2849 echo '<td>Description</td>';
2850 echo '</tr>';
2851 $show_tikon_form = true;
2852 foreach($results2 as $line)
2853 {
2854 $discount = '';
2855 $discount_invoice = 0;
2856 if($line->discount_percentage)
2857 {
2858 $discount = '-'. $line->discount_percentage .' %';
2859 $discount_invoice = $line->discount_percentage;
2860 }
2861 $line_billing_amout = $line->billing_amount;
2862
2863 if($line->discount_percentage)
2864 {
2865 $line_billing_amout = $line->billing_amount - ($line->billing_amount * $line->discount_percentage / 100);
2866 }
2867 else
2868 {
2869 $line_billing_amout = $line->billing_amount;
2870 }
2871
2872 if($line->description == 'Tikonin koulutukset')
2873 {
2874 $line_descr = '';
2875 }
2876 else
2877 {
2878 $line_descr = $line->description;
2879 }
2880
2881 if( $packages[$line->package_id]->type == 'extra'
2882 || $packages[$line->package_id]->type == 'restricted' )
2883 {
2884 $show_tikon_form = false;
2885 }
2886
2887 $datestring = opcom_show_dates($order->order_date, $billing_year, $billing_month);
2888
2889 echo "\n\n<tr>";
2890 echo '<td><input type="hidden" name="rows[]" value="'. $line->line_id .'" />';
2891
2892 $line_update_discount = '';
2893 if($packages[$line->package_id]->type == 'normal' || $packages[$line->package_id]->type == 'trial' || $packages[$line->package_id]->type == 'trial-single')
2894 {
2895 $line_update_discount = 'class="row-change-discount_percentage"';
2896 echo '<select name="row-'. $line->line_id .'-package_id" '. $disabled .' >';
2897// echo '<option value="0">-- cancel (normal processing) --</option>';
2898// echo '<option value="close">-- none (close immediately) --</option>';
2899 foreach($packages as $key => $pack)
2900 {
2901 // Allow up/downgrade only to actual packages
2902 if($pack->type == 'normal' || $pack->type == 'trial' || $pack->type == 'trial-single')
2903 {
2904 $selected = '';
2905 if ($line->package_id == $key)
2906 {
2907 $selected = 'selected';
2908 }
2909 echo '<option '. $selected .' value="'. $key .'">'. $pack->name .' ('. $pack->package_id .')</option>';
2910 }
2911
2912 }
2913 echo '</select>';
2914 echo '<input type="hidden" name="row-'. $line->line_id .'-old-package_id" value="'. $line->package_id .'" />';
2915 }
2916 else
2917 {
2918 echo '<input type="hidden" name="row-'. $line->line_id .'-package_id" value="'. $line->package_id .'" />';
2919 echo '<input type="hidden" name="row-'. $line->line_id .'-old-package_id" value="'. $line->package_id .'" />';
2920 echo $packages[$line->package_id]->name .' ('. $line->package_id .')';
2921 }
2922 echo '</td>';
2923 echo '<td><input name="row-'. $line->line_id .'-billing_amount" value="'. $line->billing_amount .'" '. $readonly .' /></td>';
2924 echo '<td><input '.$line_update_discount.' name="row-'. $line->line_id .'-discount_percentage" value="'. $line->discount_percentage .'" '. $readonly .' /></td>';
2925
2926 echo '<td>'. round($line_billing_amout, 2) .'</td>';
2927 echo '<td>'. $line->tax_percentage .'</td>';
2928 echo '<td><input class="row-description" name="row-'. $line->line_id .'-description" value="'. $line->description .'" '. $readonly .' />';
2929
2930 if( $packages[$line->package_id]->type == 'extra'
2931 || $packages[$line->package_id]->type == 'resricted' )
2932 {
2933 echo '<input type="submit" value="test" />';
2934 }
2935
2936 // echo ' '. $datestring .
2937 echo '</td>';
2938 echo '</tr>';
2939 }
2940 if($show_tikon_form)
2941 {
2942 show_new_extra_line();
2943 }
2944 echo '</table>
2945 <input type="hidden" name="user_edit_form_rows" value="rows" />';
2946/* if(!$profile_page)
2947 {
2948 echo '<input type="submit" value="Save Rows" class="button button-primary button-large" '. $disabled .' /></form>';
2949 } */
2950 }
2951 if(!$profile_page)
2952 {
2953 echo '<input type="submit" class="button button-primary button-large" value="Save Order" id="form_submit" '. $disabled .' /></form>';
2954 }
2955
2956}
2957
2958function show_new_extra_line($new = false)
2959{
2960 global $wpdb, $sql_fields;
2961 $packages = $wpdb->get_results("SELECT ". $sql_fields['package']
2962 ." FROM wpopi_opcom_package
2963 WHERE type IN ('extra', 'restricted')", OBJECT_K);
2964 $form_options = '';
2965
2966 foreach($packages as $pack)
2967 {
2968 $form_options .= '<option value="'. $pack->package_id .'">'. $pack->name .'</option>';
2969
2970 }
2971 echo '
2972 <tr class="add_tikon_extra">
2973 <td>
2974 <select class="row-new-extra-package_id" name="row-new-extra-package_id">
2975 <option selected value="0">-- none --</option>
2976 '. $form_options .'
2977 </select>
2978 </td>
2979 <td><input class="row-new-extra-billing_amount" name="row-new-extra-billing_amount" value="" /></td>
2980 <td><input class="row-new-extra-discount_percentage" name="row-new-extra-discount_percentage" value="" /></td>
2981 ';
2982 if($new === false)
2983 {
2984 echo '<td></td><td></td>';
2985 }
2986 echo '<td><input class="row-extra-description" name="row-new-extra-description" value="" />
2987 </tr>';
2988
2989}
2990
2991function opcom_members_save_member_rows($order_id, $user_id, $packages)
2992{
2993 global $wpdb;
2994
2995 $crm_data = array();
2996
2997 if(isset($_POST['row-new-package_id'])
2998 && $_POST['row-new-package_id'] != 0
2999 && $_POST['user_edit_form_rows'] == 'rows')
3000 {
3001 // todo: add validation
3002 $row_to_insert = array(
3003 'package_id' => $_POST['row-new-package_id'],
3004 'discount_percentage' => $_POST['row-new-discount_percentage'],
3005 'billing_amount' => $_POST['row-new-billing_amount'],
3006 'description' => $_POST['row-new-description'],
3007 'tax_percentage' => OPMEM_INVOICE_VAT,
3008 'order_id' => $order_id,
3009 );
3010
3011 $wpdb->insert('wpopi_opcom_order_line', $row_to_insert);
3012 opcom_log_order('add_row', $row_to_insert, $user_id, $order_id);
3013/* TODO: add logging */
3014
3015 $crm_data['change_type'] = 'insert';
3016 $crm_data['package_id'] = $_POST['row-new-package_id'];
3017 }
3018
3019 /* Adding extra packages */
3020 if(isset($_POST['row-new-extra-package_id'])
3021 && $_POST['row-new-extra-package_id'] != 0
3022 && $_POST['user_edit_form_rows'] == 'rows')
3023 {
3024 $row_to_insert = array(
3025 'package_id' => $_POST['row-new-extra-package_id'],
3026 'discount_percentage' => $_POST['row-new-extra-discount_percentage'],
3027 'billing_amount' => $_POST['row-new-extra-billing_amount'],
3028 'description' => $_POST['row-new-extra-description'],
3029 'tax_percentage' => OPMEM_INVOICE_VAT,
3030 'order_id' => $order_id,
3031 );
3032 $wpdb->insert('wpopi_opcom_order_line', $row_to_insert);
3033 opcom_log_order('add_row', $row_to_insert, $user_id, $order_id);
3034
3035 $crm_data['extra'] = 'tikon';
3036 }
3037
3038/* elseif($_POST['order_id'] == '[new order]'
3039 && $_POST['user_edit_form_rows'] == 'rows')
3040 {
3041 // todo: add validation
3042 $row_to_insert = array(
3043 'package_id' => $_POST['row-new-package_id'],
3044 'discount_percentage' => $_POST['row-new-discount_percentage'],
3045 'billing_amount' => $_POST['row-new-billing_amount'],
3046 'description' => $_POST['row-new-description'],
3047 'tax_percentage' => '24',
3048 'order_id' => $order_id,
3049 );
3050 $wpdb->insert('wpopi_opcom_order_line', $row_to_insert);
3051
3052 } */
3053 elseif($_POST['user_edit_form_rows'] == 'rows')
3054 {
3055 global $sql_fields;
3056
3057 // TODO: save log only if stuff changes?
3058 $post_rows = $_POST['rows'];
3059 // this sould always be an array
3060 $searchrows = implode (', ', $post_rows);
3061 $oldrows = $wpdb->get_results("SELECT ". $sql_fields['order_line'] ."
3062 FROM wpopi_opcom_order_line
3063 WHERE line_id IN (". $searchrows .")");
3064 opcom_log_order('edit_rows', $oldrows, $user_id, $order_id);
3065
3066 $create_new_order = false;
3067 $active_row = 0;
3068 // trying to see if one of the rows demands an order update
3069
3070 $cancel_delay_months = 1;
3071 foreach($post_rows as $old_row_id)
3072 {
3073 // if not the same, there's a package change
3074 // lets also make sure if it's a package that can be upgraded
3075 if($_POST['row-'. $old_row_id .'-package_id'] != $_POST['row-'. $old_row_id .'-old-package_id']
3076 && ( ($packages[$_POST['row-'. $old_row_id .'-old-package_id']]->type == 'normal'
3077 && $packages[$_POST['row-'. $old_row_id .'-old-package_id']]->upgrade_path != null)
3078 || $packages[$_POST['row-'. $old_row_id .'-old-package_id']]->type == 'trial'
3079 || $packages[$_POST['row-'. $old_row_id .'-old-package_id']]->type == 'trial-single') )
3080 {
3081 $create_new_order = true;
3082 $active_row = $old_row_id;
3083 }
3084
3085 // lets collect the cancel delay data
3086 if ($cancel_delay_months < $packages[$_POST['row-'. $old_row_id .'-package_id']]->cancel_delay_months)
3087 {
3088 $cancel_delay_months = $packages[$_POST['row-'. $old_row_id .'-package_id']]->cancel_delay_months;
3089 }
3090 }
3091
3092 // creating a new order
3093 if($create_new_order)
3094 {
3095
3096 $db_fields = str_replace('order_id, ', '', $sql_fields['order']);
3097 // copy current order
3098 $old_access_date = $wpdb->get_var('SELECT access_date FROM wpopi_opcom_order WHERE order_id = '. $order_id);
3099 $res = $wpdb->query('INSERT INTO wpopi_opcom_order ('. $db_fields .')
3100 SELECT '. $db_fields .' FROM wpopi_opcom_order WHERE order_id = '. $order_id);
3101 $new_order = $wpdb->insert_id;
3102 $wpdb->update('wpopi_opcom_order', array('order_status' => 'history'), array('order_id' => $order_id));
3103 $old_order = $order_id;
3104
3105 write_log('Copying the old order. '. $wpdb->last_error);
3106// NOTE: handle old access dates
3107
3108// order_date
3109// access_date
3110// cancel_date
3111// end_date
3112// first_invoicing_date
3113// first_cancel_date
3114
3115 $end_year = date('Y');
3116 $end_month = intval(date('m')) + $cancel_delay_months;
3117 if($end_month > 12 )
3118 {
3119 $end_year = $end_year + 1;
3120 $end_month = $end_month - 12;
3121 }
3122 $end_date = $end_year. '-' .$end_month. '-' .date('t', strtotime($end_year. '-' .$end_month. '-01')). ' 23:59:59';
3123// echo $old_end_date;
3124// echo '<br />'.$end_date;
3125 if(strtotime($old_access_date) > strtotime($end_date))
3126 {
3127 $end_date = $old_access_date;
3128 }
3129
3130// echo '<br />'.$active_row;
3131// echo '<br />'.$packages[$_POST['row-'. $active_row. '-package_id']]->upgrade_path;
3132// echo '<br />'.$packages[$_POST['row-'. $active_row. '-old-package_id']]->upgrade_path;
3133
3134 if(!empty($packages[$old_package_id]->upgrade_path) && empty($order[0]->end_date))
3135 {
3136
3137 if ($packages[$_POST['row-'. $active_row. '-package_id']]->upgrade_path < $packages[$_POST['row-'. $active_row. '-old-package_id']]->upgrade_path)
3138 {
3139 write_log('Package to smaller');
3140 $wpdb->update('wpopi_opcom_order',
3141 array('end_date' => $end_date, 'cancel_date' => date('Y-m-d H:i:s')),
3142 array('order_id' => $order_id));
3143
3144 // this doesn't have first cancel
3145
3146 $wpdb->update('wpopi_opcom_order',
3147 array('access_date' => $end_date, 'order_date' => date('Y-m-d H:i:s')),
3148 array('order_id' => $new_order));
3149
3150 $crm_data['change_type'] = 'downgrade';
3151
3152 }
3153 elseif ($packages[$_POST['row-'. $active_row. '-package_id']]->upgrade_path > $packages[$_POST['row-'. $active_row. '-old-package_id']]->upgrade_path)
3154 {
3155 write_log('Package to larger');
3156 $wpdb->update('wpopi_opcom_order',
3157 array('end_date' => date('Y-m-d H:i:s'), 'cancel_date' => date('Y-m-d H:i:s')),
3158 array('order_id' => $order_id));
3159
3160 $wpdb->update('wpopi_opcom_order',
3161 array('order_date' => date('Y-m-d H:i:s'), 'access_date' => date('Y-m-d H:i:s')),
3162 array('order_id' => $new_order));
3163
3164 $crm_data['change_type'] = 'upgrade';
3165 }
3166 }
3167 else
3168 {
3169 write_log('Normal package change');
3170 $wpdb->update('wpopi_opcom_order',
3171 array('end_date' => date('Y-m-d H:i:s'), 'cancel_date' => date('Y-m-d H:i:s')),
3172 array('order_id' => $order_id));
3173
3174 $wpdb->update('wpopi_opcom_order',
3175 array('order_date' => date('Y-m-d H:i:s'), 'access_date' => date('Y-m-d H:i:s'), 'cancel_date' => null, 'end_date' => null),
3176 array('order_id' => $new_order));
3177 }
3178
3179 }
3180
3181 foreach($post_rows as $old_row_id2)
3182 {
3183 $row_to_insert = array();
3184 $discount = null;
3185 if(!empty($_POST['row-'. $old_row_id2 .'-discount_percentage']))
3186 {
3187 $discount = $_POST['row-'. $old_row_id2 .'-discount_percentage'];
3188 }
3189
3190 if($create_new_order && $old_row_id2 == $active_row)
3191 {
3192
3193 $new_descr = str_replace($packages[$_POST['row-'. $old_row_id2 .'-old-package_id']]->name,
3194 $packages[$_POST['row-'. $old_row_id2 .'-package_id']]->name,
3195 $_POST['row-'. $old_row_id2 .'-description']);
3196 $row_to_insert = array(
3197 'package_id' => $_POST['row-'. $old_row_id2 .'-package_id'], // new id
3198 'discount_percentage' => $discount,
3199 'billing_amount' => $packages[$_POST['row-'. $old_row_id2 .'-package_id']]->price, // new price
3200 'description' => $new_descr,
3201 'tax_percentage' => OPMEM_INVOICE_VAT,
3202 'order_id' => $new_order,
3203 );
3204 $wpdb->insert('wpopi_opcom_order_line', $row_to_insert);
3205
3206 $crm_data['package_id'] = $_POST['row-'. $old_row_id2 .'-package_id'];
3207
3208 }
3209 elseif($create_new_order)
3210 {
3211
3212 $row_to_insert = array(
3213 'package_id' => $_POST['row-'. $old_row_id2 .'-package_id'],
3214 'discount_percentage' => $discount,
3215 'billing_amount' => $_POST['row-'. $old_row_id2 .'-billing_amount'],
3216 'description' => $_POST['row-'. $old_row_id2 .'-description'],
3217 'tax_percentage' => OPMEM_INVOICE_VAT,
3218 'order_id' => $new_order,
3219 );
3220 $wpdb->insert('wpopi_opcom_order_line', $row_to_insert);
3221
3222 $crm_data['package_id'] = $_POST['row-'. $old_row_id2 .'-package_id'];
3223 }
3224 else
3225 {
3226
3227 // no package_id
3228 $row_to_insert = array(
3229 'discount_percentage' => $discount,
3230 'billing_amount' => $_POST['row-'. $old_row_id2 .'-billing_amount'],
3231 'description' => $_POST['row-'. $old_row_id2 .'-description'],
3232 'tax_percentage' => OPMEM_INVOICE_VAT,
3233 );
3234 $wpdb->update('wpopi_opcom_order_line', $row_to_insert, array('line_id' => $old_row_id2));
3235
3236 $crm_data['package_id'] = $_POST['row-'. $old_row_id2 .'-package_id'];
3237 }
3238 }
3239 }
3240 return $crm_data;
3241}
3242
3243function opcom_members_save_member_order($order_id, $user_id, $profile_page)
3244{
3245 $crm_data = array();
3246
3247 if($_POST['user_edit_form_order'] == 'order')
3248 {
3249 global $sql_fields, $wpdb, $billing_fields;
3250
3251 $count_usermeta = 0;
3252 $fields_to_order = array();
3253
3254 opcom_log_order_save($order_id);
3255
3256 foreach($billing_fields as $key => $values)
3257 {
3258 /* if($values['source'] == 'order')
3259 {
3260 $value = $order->$key;
3261 }
3262 elseif($values['source'] == 'usermeta')
3263 {
3264 $value = $meta[$key][0];
3265 } */
3266 if($key == 'first_name')
3267 {
3268 $crm_data['first_name'] = $_POST[$values['source'] .'-'. $key];
3269 }
3270 if($key == 'last_name')
3271 {
3272 $crm_data['last_name'] = $_POST[$values['source'] .'-'. $key];
3273 }
3274
3275 if(isset($_POST[$values['source'] .'-'. $key]))
3276 {
3277// echo '<br />'. $key . ': '. $_POST[$values['source'] .'-'. $key];
3278
3279 if($values['type'] == 'text' || $values['type'] == 'textarea'
3280 || $values['type'] == 'select' || $values['type'] == 'date')
3281 {
3282 /* $data = array(
3283 'name' => $name,
3284 'email' => $email,
3285 'phone' => $phone,
3286 'f12220010cf3f7c738b5d032724eb59a3f93caea' => $package_name, // Akatemian paketti
3287 '082f0dc85a5a5a37228d8a903a8a83a19ad97618' => $order_status, // Tilauksen status
3288 '1df727afdfe191658fa620d869f17a0a81a85ede' => $order_date, // Tilauspäivä
3289 ); */
3290
3291 // Not touching the select values that are not what we want to see there
3292
3293 /* if ($values['type'] == 'select'
3294 && $values['source'] == 'order'
3295 && $_POST[$values['source'] .'-'. $key] == 0)
3296 {
3297 $fields_to_order[$key] = null;
3298 }
3299 elseif ($values['type'] == 'select'
3300 && $values['source'] == 'usermeta'
3301 && $_POST[$values['source'] .'-'. $key] == 0)
3302 {
3303 if(update_user_meta($user_id, $key, ''))
3304 {
3305 $count_usermeta++;
3306 }
3307 } */
3308 if ($values['type'] == 'select'
3309 && !array_key_exists($_POST[$values['source'] .'-'. $key], $values['select_values']))
3310 {
3311// skip select
3312 }
3313 else
3314 {
3315
3316 if($values['source'] == 'usermeta')
3317 {
3318 if(update_user_meta($user_id, $key, $_POST[$values['source'] .'-'. $key]))
3319 {
3320 $count_usermeta++;
3321 }
3322 }
3323 elseif($values['source'] == 'order')
3324 {
3325 if($values['type'] == 'date' && $_POST[$values['source'] .'-'. $key] == '')
3326 {
3327 $fields_to_order[$key] = null;
3328 }
3329 else
3330 {
3331 $fields_to_order[$key] = $_POST[$values['source'] .'-'. $key];
3332 }
3333 }
3334 }
3335 }
3336 }
3337 }
3338
3339 $wpdb->update('wpopi_opcom_order', $fields_to_order, array('order_id' => $order_id));
3340 if(!$profile_page)
3341 {
3342 echo '<p>';
3343 if(!$wpdb->last_error)
3344 {
3345 echo 'Order saved.';
3346 }
3347 else
3348 {
3349 echo 'Order not saved, ' .$wpdb->last_error .'';
3350 }
3351 if($count_usermeta > 0)
3352 {
3353 echo '<br />'. $count_usermeta .' user data fields updated.';
3354 }
3355 echo '</p>';
3356 }
3357 $crm_data['email'] = $_POST['email'];
3358 $crm_data['first_name'] = $_POST['first_name'];
3359 $crm_data['last_name'] = $_POST['last_name'];
3360 $crm_data['order_date'] = $_POST['order-order_date'];
3361 $crm_data['order_status'] = $_POST['order-order_status'];
3362 }
3363 return $crm_data;
3364}
3365
3366function opcom_members_save_new_member_order($order_id, $user_id)
3367{
3368 // TODO: add some validation
3369 global $wpdb;
3370 $user = get_userdata($user_id);
3371 if($_POST['order-campaign_id'] == 0)
3372 {
3373 $campaign_id = null;
3374 }
3375 else
3376 {
3377 $campaign_id = $_POST['order-campaign_id'];
3378 }
3379 $order = array(
3380 'user_id' => $user_id,
3381 'order_status' => $_POST['order-order_status'],
3382 'order_date' => $_POST['order-order_date'] ? $_POST['order-order_date'] : null,
3383 'access_date' => $_POST['order-access_date'] ? $_POST['order-access_date'] : null,
3384 'cancel_date' => $_POST['order-cancel_date'] ? $_POST['order-cancel_date'] : null,
3385 'end_date' => $_POST['order-end_date'] ? $_POST['order-end_date'] : null,
3386 'first_cancel_date' => $_POST['order-first_cancel_date'] ? $_POST['order-first_cancel_date'] : null,
3387 'vatcode' => $_POST['oa_vatcode'],
3388 'billing_period' => 1,
3389 'cancel_delay' => 30,
3390 'campaign_id' => $campaign_id,
3391 'notes' => $_POST['order-notes'],
3392 'order_source' => $_POST['order-order_source'],
3393 'order_identifier' => hash('ripemd160', $user->user_email .' - '. $_POST['order_date'])
3394 );
3395
3396 $wpdb->insert('wpopi_opcom_order', $order);
3397 $insert_id = $wpdb->insert_id;
3398 return $insert_id;
3399
3400}
3401
3402add_action( 'personal_options_update', 'opcom_member_history_save_profile_fields' );
3403add_action( 'edit_user_profile_update', 'opcom_member_history_save_profile_fields' );
3404function opcom_member_history_save_profile_fields( $user_id )
3405{
3406
3407 $order_id = $_POST['order_id'];
3408 // $user_id = $_GET['user_id'];
3409
3410 if($order_id == '[new order]')
3411 {
3412 $order_id = opcom_members_save_new_member_order($order_id, $user_id);
3413 }
3414 elseif($_POST['user_edit_form_order'] == 'order')
3415 {
3416 $crm_data_order = opcom_members_save_member_order($order_id, $user_id, true);
3417 }
3418
3419 if($_POST['user_edit_form_rows'] == 'rows')
3420 {
3421 global $sql_fields, $wpdb;
3422 $packages = $wpdb->get_results('SELECT '. $sql_fields['package'] .' FROM wpopi_opcom_package ORDER BY upgrade_path', OBJECT_K);
3423 $crm_data_rows = opcom_members_save_member_rows($order_id, $user_id, $packages);
3424 }
3425
3426 $crm_data = array_merge($crm_data_order, $crm_data_rows);
3427
3428 write_log('CRM - order');
3429 write_log($crm_data);
3430
3431}
3432
3433add_action('edit_user_profile', 'opcom_member_history_profile_fields');
3434add_action('show_user_profile', 'opcom_member_history_profile_fields');
3435function opcom_member_history_profile_fields($user)
3436{
3437
3438 global $wpdb;
3439
3440 $billing_year = date('Y');
3441 $billing_month = date('n');
3442
3443 $order_id = $wpdb->get_var("SELECT order_id FROM wpopi_opcom_order WHERE user_id = '". $user->ID ."' ORDER BY order_id DESC");
3444
3445 opcom_admin_styles();
3446 opcom_show_billing_editing_screen($order_id, $billing_year, $billing_month, true);
3447
3448}
3449
3450/*
3451* Save an order from the front end order form.
3452* Depends on Gravity Forms. Depends on the Gravity Forms to create a user account.
3453*
3454* See GF docs for instructions on the structures below.
3455*
3456* TODO: Modify so that it wont depend on form field ids.
3457*/
3458function opcom_save_order(&$entry, &$form)
3459{
3460/* print_r($form);
3461echo '<br /><br />';
3462print_r($entry); */
3463
3464 global $wpdb, $sql_fields, $order_metafields;
3465 write_log('Saving order');
3466
3467 $trial_user = false;
3468 $current_order = $wpdb->get_results("SELECT ". $sql_fields['order'] ."
3469 FROM wpopi_opcom_order
3470 WHERE user_id = '". get_current_user_id() ."'
3471 ORDER BY order_id DESC", ARRAY_A);
3472
3473 if ($current_order[0]['order_status'] == 'trial')
3474 {
3475 $trial_user = true;
3476 }
3477
3478 $packages = $wpdb->get_results('SELECT '. $sql_fields['package'] .' FROM wpopi_opcom_package ORDER BY upgrade_path', OBJECT_K);
3479 $userdata = array();
3480
3481 $order_date = date('Y-m-d H:i:s');
3482 $level_with_price = rgar( $entry, '31' );
3483 write_log('Level|price: '. $level_with_price);
3484 $cancel_delay = 30;
3485 $tikon_user = false;
3486 if(strpos($level_with_price, '|'))
3487 {
3488 $level_array = explode('|', $level_with_price);
3489 $level = $level_array[0];
3490 }
3491 else
3492 {
3493 /* We're probably screwed if it hits this part, but let's try to do what we can */
3494 $level = $level_with_price;
3495 }
3496
3497 $order = array(
3498 'order_status' => 'success',
3499 'order_date' => $order_date,
3500 'access_date' => $order_date,
3501 'vatcode' => rgar( $entry, '7' ),
3502 'billing_period' => 1,
3503 'extra_info' => rgar( $entry, '14' ),
3504 'new_level' => $level
3505 );
3506
3507 /* This field represents Tikon */
3508 if(rgar( $entry, '22.1' ))
3509 {
3510 $cancel_delay = 90;
3511 $tikon_user = true;
3512 }
3513 $discount_percentage = 0;
3514 if(rgar( $entry, '33' ))
3515 {
3516 /* This is apparently in the following format if you straight save it with Gforms:
3517 Procountor2016 (PROCOUNTOR2016: -15,80 €) */
3518 // $coupon = explode(' (', $user_discount_code);
3519 $campaign_info = $wpdb->get_row(
3520 'SELECT campaign_id, discount_code, discount_percentage
3521 FROM wpopi_opcom_campaign
3522 WHERE discount_code LIKE upper(\''.rgar( $entry, '33' ).'\')', ARRAY_A);
3523
3524 $order['campaign_id'] = $campaign_info['campaign_id'];
3525 $discount_percentage = $campaign_info['discount_percentage'];
3526 }
3527 if(rgar( $entry, '22.1' ))
3528 {
3529 $y = date('Y' ,strtotime($order_date));
3530 $m = date('m' ,strtotime($order_date));
3531 $d = date('d' ,strtotime($order_date));
3532 $m_end = $m + 3;
3533 if($m_end > 12)
3534 {
3535 $y + 1;
3536 $m_end - 12;
3537 }
3538 $order['first_cancel_date'] = date('Y-m-d H:i:s', strtotime($y.'-'.$m_end.'-'. $d .' 01:00:00'));
3539 }
3540 $order['cancel_delay'] = $cancel_delay;
3541
3542 foreach($order_metafields as $meta_title => $meta)
3543 {
3544 foreach($form['fields'] as $formfield)
3545 {
3546 if($meta_title == $formfield['label'] && $formfield->type == 'address')
3547 {
3548 $userdata['meta_oa_address'] = rgar( $entry, $formfield['id'].'.1' );
3549 $userdata['meta_oa_postalcode'] = rgar( $entry, $formfield['id'].'.5' );
3550 $userdata['meta_oa_city'] = rgar( $entry, $formfield['id'].'.3' );
3551 }
3552 elseif($meta_title == $formfield['label'])
3553 {
3554 $userdata['meta_'. $meta['meta']] = rgar( $entry, $formfield['id'] );
3555 }
3556 }
3557 }
3558
3559 $userdata['first_name'] = rgar( $entry, '3.3' );
3560 $userdata['last_name'] = rgar( $entry, '3.6' );
3561 $userdata['display_name'] = rgar( $entry, '3.3' ). ' ' .rgar( $entry, '3.6' );
3562
3563 write_log('Userdata');
3564 write_log($userdata);
3565
3566 // User logged in -> this is an order change
3567 if(is_user_logged_in() && !is_admin())
3568 {
3569 $user = get_user_by('id', get_current_user_id());
3570 $user_id = $user->ID;
3571 $order['user_id'] = $user_id;
3572 if($tikon_user === true)
3573 {
3574 $order['tikon'] = 1;
3575 }
3576 unset($order['package_id']);
3577 // $order['order_identifier'] = hash('ripemd160', $user->user_email .' - '. $order_date);
3578 opcom_update_order_frontend($order, $user);
3579 opmem_save_user_order_meta($user_id, $userdata);
3580
3581 $email = $user->user_email;
3582 if( $trial_user == true )
3583 {
3584 opmem_post_mailerlite_new_order($email, $user->$user_firstname, $user->$user_lastname, $tikon_user);
3585 }
3586 else
3587 {
3588 opmem_post_mailerlite_change($email, $user->user_firstname, $user->user_lastname, $tikon_user);
3589 }
3590 }
3591 else
3592 {
3593 // here
3594 $email = rgar( $entry, '2' );
3595
3596 $order_type = rgar( $entry, '35' );
3597 if(!empty($order_type))
3598 {
3599 $order['order_status'] = $order_type;
3600 }
3601 else
3602 {
3603 $order['order_status'] = 'success';
3604 }
3605
3606 // $password = opmem_random_str(10);
3607 $password = rgar( $entry, '1' );
3608 $userdata['user_pass'] = $password;
3609 $userdata['user_email'] = $email;
3610 $user_firstname = rgar( $entry, '3.3' );
3611 $user_lastname = rgar( $entry, '3.6' );
3612
3613 unset($order['new_level']);
3614 $order['order_identifier'] = hash('ripemd160', $email .' - '. $order_date);
3615 opmem_create_user_order($userdata, $level, 'success', $discount_percentage, $order, $tikon_user);
3616 opmem_post_mailerlite_new_order($email, $user_firstname, $user_lastname, $tikon_user);
3617 }
3618}
3619
3620/*
3621* Save an order from the admin order form.
3622* Depends on Gravity Forms. Depends on the Gravity Forms to create a user account.
3623*
3624* See GF docs for instructions on the structures below.
3625*
3626* TODO: Modify so that it wont depend on form field ids.
3627*/
3628function opcom_save_order_admin(&$entry, &$form)
3629{
3630/* print_r($form);
3631echo '<br /><br />'; */
3632
3633 global $wpdb, $sql_fields, $order_metafields;
3634 write_log('----------------------');
3635 write_log('- Saving admin order -');
3636 write_log('----------------------');
3637 write_log($entry);
3638
3639 $packages = $wpdb->get_results('SELECT '. $sql_fields['package'] .' FROM wpopi_opcom_package ORDER BY upgrade_path', OBJECT_K);
3640 $userdata = array();
3641
3642 $order_date = date('Y-m-d H:i:s');
3643 $level_with_price = rgar( $entry, '31' );
3644 write_log('Level|price: '. $level_with_price);
3645 $cancel_delay = 30;
3646 $tikon_user = false;
3647 if(strpos($level_with_price, '|'))
3648 {
3649 $level_array = explode('|', $level_with_price);
3650 $level = $level_array[0];
3651 }
3652 else
3653 {
3654 /* We're probably screwed if it hits this part, but let's try to do what we can */
3655 $level = $level_with_price;
3656 }
3657
3658 if( !empty(rgar( $entry, '40' )) )
3659 {
3660 $order_status = rgar( $entry, '40' );
3661 }
3662
3663 if( !empty(rgar( $entry, '42' )) )
3664 {
3665 $access_date = date( 'Y-m-d 00:00:01', strtotime(rgar( $entry, '42' )) );
3666 }
3667 else
3668 {
3669 $access_date = $order_date;
3670 }
3671
3672 $order = array(
3673 'order_status' => $order_status,
3674 'order_date' => $order_date,
3675 'access_date' => $access_date,
3676 'vatcode' => rgar( $entry, '7' ),
3677 'billing_period' => 1,
3678 'extra_info' => rgar( $entry, '14' ),
3679 'new_level' => $level
3680 );
3681
3682 if( !empty(rgar( $entry, '43' )) )
3683 {
3684 $order['end_date'] = date( 'Y-m-d 23:59:59', strtotime(rgar( $entry, '43' )) );
3685 }
3686 elseif( $order_status == 'trial' )
3687 {
3688 $order['end_date'] = date( 'Y-m-d 23:59:59', time() + 1209600 );
3689 }
3690
3691 /* This field represents Tikon */
3692 if( rgar( $entry, '38' ) == 'tikon' )
3693 {
3694 $cancel_delay = 90;
3695 $tikon_user = true;
3696 $y = date('Y' ,strtotime($order_date));
3697 $m = date('m' ,strtotime($order_date));
3698 $d = date('d' ,strtotime($order_date));
3699 $m_end = $m + 3;
3700 if($m_end > 12)
3701 {
3702 $y + 1;
3703 $m_end - 12;
3704 }
3705 $order['first_cancel_date'] = date('Y-m-d H:i:s', strtotime($y.'-'.$m_end.'-'. $d .' 01:00:00'));
3706 }
3707
3708 $discount_percentage = 0;
3709 if( rgar( $entry, '33' ) )
3710 {
3711 /* This is apparently in the following format if you straight save it with Gforms:
3712 Procountor2016 (PROCOUNTOR2016: -15,80 €) */
3713 // $coupon = explode(' (', $user_discount_code);
3714 $campaign_info = $wpdb->get_row(
3715 'SELECT campaign_id, discount_code, discount_percentage
3716 FROM wpopi_opcom_campaign
3717 WHERE discount_code LIKE upper(\''.rgar( $entry, '33' ).'\')', ARRAY_A);
3718
3719 $order['campaign_id'] = $campaign_info['campaign_id'];
3720 $discount_percentage = $campaign_info['discount_percentage'];
3721 }
3722
3723 $order['cancel_delay'] = $cancel_delay;
3724
3725 foreach($order_metafields as $meta_title => $meta)
3726 {
3727 foreach($form['fields'] as $formfield)
3728 {
3729 if($meta_title == $formfield['label'] && $formfield->type == 'address')
3730 {
3731 $userdata['meta_oa_address'] = rgar( $entry, $formfield['id'].'.1' );
3732 $userdata['meta_oa_postalcode'] = rgar( $entry, $formfield['id'].'.5' );
3733 $userdata['meta_oa_city'] = rgar( $entry, $formfield['id'].'.3' );
3734 }
3735 elseif($meta_title == $formfield['label'])
3736 {
3737 $userdata['meta_'. $meta['meta']] = rgar( $entry, $formfield['id'] );
3738 }
3739 }
3740 }
3741
3742 $userdata['first_name'] = rgar( $entry, '3.3' );
3743 $userdata['last_name'] = rgar( $entry, '3.6' );
3744 $userdata['display_name'] = rgar( $entry, '3.3' ). ' ' .rgar( $entry, '3.6' );
3745
3746 write_log('Userdata');
3747 write_log($userdata);
3748
3749 if(is_admin())
3750 {
3751 // here
3752 $email = rgar( $entry, '2' );
3753
3754 $order_type = rgar( $entry, '40' );
3755 if(!empty($order_type))
3756 {
3757 $order['order_status'] = $order_type;
3758 }
3759 else
3760 {
3761 $order['order_status'] = 'success';
3762 }
3763
3764 $koulutus_id = rgar( $entry, '41' );
3765 if( !empty($koulutus_id)
3766 && $level == 14 )
3767 {
3768 $koulutus_valinta = $wpdb->get_var( "SELECT post_title FROM wpopi_posts
3769 WHERE post_type = 'sfwd-courses' AND ID = ". $koulutus_id );
3770 $order['order_status'] = 'trial';
3771 $order['extra_info'] = $koulutus_valinta;
3772 $order['single_trial_course_title'] = $koulutus_valinta;
3773 $order['single_trial_course_id'] = $koulutus_id;
3774 $email_description_html = '<p><strong>Valittu koulutus:Â </strong><a href="'. get_permalink($koulutus_id) .'">'. $koulutus_valinta .'</a></p>';
3775 $email_description_text = 'Valittu koulutus:Â '. $koulutus_valinta .'
3776 '. get_permalink($koulutus_id);
3777 }
3778 else
3779 {
3780 $email_description_html = '<p><strong>Valitsemasi paketti:Â </strong> '. $packages[$level]->name .'</p>';
3781 $email_description_text = 'Valitsemasi paketti:Â '. $packages[$level]->name .'
3782 '. get_permalink($koulutus_id);
3783 }
3784
3785 if( !empty(rgar( $entry, '44' )) )
3786 {
3787 $password = rgar( $entry, '44' );
3788 }
3789 else
3790 {
3791 $password = opmem_random_str(10);
3792 }
3793
3794 // $password = rgar( $entry, '1' );
3795 $userdata['user_pass'] = $password;
3796 $userdata['user_email'] = $email;
3797 $user_firstname = rgar( $entry, '3.3' );
3798 $user_lastname = rgar( $entry, '3.6' );
3799
3800 unset($order['new_level']);
3801 $order['order_identifier'] = hash('ripemd160', $email .' - '. $order_date);
3802 write_log('Order data');
3803 write_log($order);
3804
3805 opmem_create_user_order($userdata, $level, 'success', $discount_percentage, $order, $tikon_user);
3806 opmem_post_mailerlite_new_order($email, $user_firstname, $user_lastname, $tikon_user);
3807
3808 // Compile email
3809 $email_subject = rgar( $entry, '36' );
3810 $email_top = rgar( $entry, '35' );
3811 $email_bottom = rgar( $entry, '37' );
3812
3813 $message_html = nl2br($email_top) .'
3814 <br />Käyttäjätunnus: '. $email .'
3815 <br />Salasana: '. $password .'</p>
3816
3817 <p>Kirjaudu sisään täältä: <a href="http://opinahjo.fi/login">opinahjo.fi/login</a></p>'.
3818 $email_description_html .
3819 nl2br($email_bottom);
3820
3821 $message_plain = $email_top
3822 .'
3823 Käyttäjätunnus: '. $email .'
3824 Salasana: '. $user_password .'
3825
3826 Kirjaudu sisään täältä:
3827 http://opinahjo.fi/login/
3828
3829 '. $email_description_text .'
3830 '. $email_bottom;
3831
3832/* TODO: ADD LOGGING (to the individual functions) */
3833 opcom_phpmailer_send_via_postmark($email, $email_subject, $message_html, $message_plain);
3834
3835 }
3836
3837}
3838
3839
3840
3841/**
3842 * Logging the user in after a new order, but only if there's no logged in user.
3843 * Otherwise redirects to the profile page.
3844 * @param $entry From Gform
3845 * @param $form From Gform
3846 * @param $package_id Numerical ID of a package. Used for tracking.
3847 */
3848function login_after_order($entry, $form, $package_id)
3849{
3850 if( $form['title'] == 'Tilaus 2017'
3851 || $form['title'] == 'Order 2017' )
3852 {
3853 global $opmem_profile_pages;
3854 if(!is_user_logged_in())
3855 {
3856 $email = rgar( $entry, '2' );
3857 $user = get_user_by('email', $email);
3858 autologin($user->ID, $config, $entry, $password);
3859 if ( wp_redirect( 'http://' .$_SERVER['HTTP_HOST']. '/' .$opmem_profile_pages[OPMEM_BILLING_COUNTRY_CODE]['prefix'] . '/?paketti=' . $package_id ) )
3860 {
3861 exit;
3862 }
3863 }
3864 else
3865 {
3866 if ( wp_redirect( 'http://' .$_SERVER['HTTP_HOST']. '/' .$opmem_profile_pages[OPMEM_BILLING_COUNTRY_CODE]['prefix'] . '/?paketti=' . $package_id ) )
3867 {
3868 exit;
3869 }
3870 }
3871 }
3872
3873}
3874
3875/*
3876* Cancel an order from the front end cancel form.
3877* TODO: needs to verify that the user actually can cancel their order.
3878*/
3879function opcom_cancel_order()
3880{
3881 global $sql_fields, $wpdb;
3882 $user = wp_get_current_user();
3883 $current_order = $wpdb->get_results("SELECT ". $sql_fields['order'] ."
3884 FROM wpopi_opcom_order
3885 WHERE user_id = '". $user->ID ."'
3886 AND order_status = 'success'
3887 ORDER BY order_id DESC", ARRAY_A);
3888
3889 if(opmem_get_user_basic_package($user->ID) !== false && !empty($current_order[0]))
3890 {
3891
3892 $month = intval(date('m'));
3893 $year = intval(date('Y'));
3894
3895 if(opmem_get_user_tikon_package($user->ID))
3896 {
3897 $month = $month + 3;
3898 }
3899 else
3900 {
3901 $month++;
3902 }
3903 if($month > 12)
3904 {
3905 $year++;
3906 $month = $month - 12;
3907 }
3908 $lastday = date('Y-m-t 23:59:59', strtotime($year .'-'. $month .'-01 00:00:01'));
3909
3910 $order = array(
3911 'order_status' => 'cancelled',
3912 'cancel_date' => date('Y-m-d H:i:s'),
3913 'end_date' => $lastday
3914 );
3915 $where = array(
3916 'order_id' => $current_order[0]['order_id'],
3917 );
3918 $wpdb->update('wpopi_opcom_order', $order, $where);
3919 }
3920 // TODO: MailerLite changes
3921
3922 $email = $user->user_email;
3923 write_log('Cancelling order: '. $email);
3924
3925 opmem_pipedrive_update_user($email, true);
3926 opmem_post_mailerlite_cancel($email, $user->user_firstname, $user->user_lastname);
3927}
3928
3929function opcom_update_order(&$entry, &$form)
3930{
3931 global $wpdb, $sql_fields;
3932
3933 $user = wp_get_current_user();
3934 $user_id = $user->ID;
3935 $change_date = date('Y-m-d H:i:s');
3936 $level_with_price = rgar( $entry, '31' );
3937
3938 if(strpos($level_with_price, '|'))
3939 {
3940 $level_array = explode('|', $level_with_price);
3941 $new_level = $level_with_price[0];
3942 }
3943 else
3944 {
3945 /* We're probably screwed if it hits this part, but let's try to do what we can */
3946 $new_level = $level_with_price;
3947 }
3948
3949 $cancel_delay = 30;
3950 $tikon_user = false;
3951
3952 if(rgar( $entry, '22.1' ))
3953 {
3954 $cancel_delay = 90;
3955 $tikon_user = true;
3956 }
3957
3958 $form_order = array(
3959 'user_id' => $user_id,
3960 'new_level' => $new_level,
3961 'change_date' => $change_date,
3962 'billing_period' => 1,
3963 'cancel_delay' => $cancel_delay,
3964 );
3965 if(rgar( $entry, '22.1' ))
3966 {
3967 $form_order['tikon'] = 1;
3968 }
3969
3970 if(rgar( $entry, '34' ))
3971 {
3972 /* This is apparently in the following format if you straight save it with Gforms:
3973 Procountor2016 (PROCOUNTOR2016: -15,80 €) */
3974 // $coupon = explode(' (', $user_discount_code);
3975 $campaign_info = $wpdb->get_row(
3976 'SELECT campaign_id, discount_code, discount_percentage
3977 FROM wpopi_opcom_campaign
3978 WHERE discount_code LIKE upper(\''.rgar( $entry, '34' ).'\')', ARRAY_A);
3979
3980 $form_order['campaign_id'] = $campaign_info['campaign_id'];
3981 $form_order['discount_percentage'] = $campaign_info['discount_percentage'];
3982 }
3983
3984 opcom_update_order_frontend($form_order, $user);
3985 opmem_pipedrive_update_user($user->user_email);
3986
3987 /* LEGACY: Create a PMPro order */
3988/*
3989TODO: add this
3990
3991 if(function_exists("pmpro_changeMembershipLevel"))
3992 {
3993 $level_data = array(
3994 'startdate' => date("Y-m-d H:i:s"),
3995 'user_id' => $user_id,
3996 'membership_id' => $level,
3997 'cycle_period' => 'Month'
3998 );
3999 if(rgar( $entry, '22.1' ))
4000 {
4001 add_user_meta($user_id, 'service_tikon', 1);
4002 }
4003 opmem_legacy_pmpro_create_order($level, $user);
4004 // pmpro_changeMembershipLevel( $level_data, $user_id );
4005 }
4006*/
4007 /* Post save: 3rd party integrations */
4008 // opmem_post_mailerlite($email, $user->user_firstname, $user->user_lastname);
4009
4010}
4011
4012function opcom_update_order_frontend($form_order, $user)
4013{
4014
4015 global $wpdb, $sql_fields;
4016 $user_id = $user->ID;
4017 $packages = $wpdb->get_results('SELECT '. $sql_fields['package'] .' FROM wpopi_opcom_package ORDER BY upgrade_path', OBJECT_K);
4018 $order = $wpdb->get_results("SELECT ". $sql_fields['order'] ."
4019 FROM wpopi_opcom_order
4020 WHERE user_id = '". $user_id ."'
4021 ORDER BY order_id DESC", OBJECT);
4022
4023 $order_id = $order[0]->order_id;
4024// $new_order['new_level']
4025/* if( $order[0]->order_status == 'success'
4026 || $order[0]->order_status == 'active'
4027 || ($order[0]->order_status == 'cancelled' && $order[0]->end_date < date('Y-m-d H:i:s')) ) */
4028
4029 // TODO: save log only if stuff changes?
4030
4031 // this sould always be an array
4032
4033 /* $post_rows = $_POST['rows'];
4034 $searchrows = implode (', ', $post_rows); */
4035 $oldrows = $wpdb->get_results("SELECT ". $sql_fields['order_line'] ."
4036 FROM wpopi_opcom_order_line
4037 WHERE order_id = ". $order_id);
4038 opcom_log_order('edit_rows', $oldrows, $user_id, $order_id);
4039
4040 $create_new_order = false;
4041 $active_row = 0;
4042 // trying to see if one of the rows demands an order update
4043
4044 $cancel_delay_months = 1;
4045
4046 foreach($oldrows as $line)
4047 {
4048 if($packages[$line->package_id]->type == 'normal')
4049 {
4050 $old_package_id = $line->package_id;
4051 }
4052 }
4053
4054
4055/* foreach($post_rows as $old_row_id)
4056 {
4057 // if not the same, there's a package change
4058 // lets also make sure if it's a package that can be upgraded
4059 if($_POST['row-'. $old_row_id .'-package_id'] != $_POST['row-'. $old_row_id .'-old-package_id']
4060 && ( ($packages[$_POST['row-'. $old_row_id .'-old-package_id']]->type == 'normal'
4061 && $packages[$_POST['row-'. $old_row_id .'-old-package_id']]->upgrade_path != null)
4062 || $packages[$_POST['row-'. $old_row_id .'-old-package_id']]->type == 'trial') )
4063 {
4064 $create_new_order = true;
4065 $active_row = $old_row_id;
4066 }
4067
4068 // lets collect the cancel delay data
4069 if ($cancel_delay_months < $packages[$_POST['row-'. $old_row_id .'-package_id']]->cancel_delay_months)
4070 {
4071 $cancel_delay_months = $packages[$_POST['row-'. $old_row_id .'-package_id']]->cancel_delay_months;
4072 }
4073 } */
4074
4075/*
4076NEED DETECTION FOR ORDERS THAT AREN'T
4077READY TO BE UPDATED RIGHT NOW
4078*/
4079
4080 write_log('Processing old order: '. $order_id);
4081
4082 $db_fields = str_replace('order_id, ', '', $sql_fields['order']);
4083 // copy current order
4084 $old_access_date = $wpdb->get_var('SELECT access_date FROM wpopi_opcom_order WHERE order_id = '. $order_id);
4085
4086 $old_order_query = $wpdb->get_row("SELECT ". $db_fields ." FROM wpopi_opcom_order WHERE order_id = ". $order_id, ARRAY_A);
4087 write_log('Fetch the current order. '.$wpdb->last_error);
4088
4089 $wpdb->insert( 'wpopi_opcom_order', $old_order_query );
4090 $new_order = $wpdb->insert_id;
4091
4092 /* $res = $wpdb->query("INSERT INTO wpopi_opcom_order (". $db_fields .") SELECT ". $db_fields ." FROM wpopi_opcom_order WHERE order_id = ". $order_id); */
4093
4094 write_log('Creating a new order. '.$wpdb->last_error);
4095
4096 /* Change new order to success */
4097 $wpdb->update('wpopi_opcom_order', array('order_status' => 'success'), array('order_id' => $new_order));
4098
4099 /* Update old order */
4100 $wpdb->update('wpopi_opcom_order', array('order_status' => 'history'), array('order_id' => $order_id));
4101 $old_order = $order_id;
4102
4103 $end_year = date('Y');
4104 $end_month = intval(date('m')) + $cancel_delay_months;
4105 if($end_month > 12 )
4106 {
4107 $end_year = $end_year + 1;
4108 $end_month = $end_month - 12;
4109 }
4110 $end_date = $end_year. '-' .$end_month. '-' .date('t', strtotime($end_year. '-' .$end_month. '-01')). ' 23:59:59';
4111
4112 if(strtotime($old_access_date) > strtotime($end_date))
4113 {
4114 $end_date = $old_access_date;
4115 }
4116
4117 if(!empty($packages[$old_package_id]->upgrade_path) && empty($order[0]->end_date))
4118 {
4119 if ($packages[$form_order['new_level']]->upgrade_path < $packages[$old_package_id]->upgrade_path)
4120 {
4121 write_log('Smaller package');
4122 $wpdb->update('wpopi_opcom_order',
4123 array('end_date' => $end_date, 'cancel_date' => date('Y-m-d H:i:s')),
4124 array('order_id' => $order_id));
4125
4126 $wpdb->update('wpopi_opcom_order',
4127 array('access_date' => $end_date, 'order_date' => date('Y-m-d H:i:s'), 'cancel_date' => null),
4128 array('order_id' => $new_order));
4129 }
4130 elseif ($packages[$form_order['new_level']]->upgrade_path > $packages[$old_package_id]->upgrade_path)
4131 {
4132 write_log('Larger package');
4133 $wpdb->update('wpopi_opcom_order',
4134 array('end_date' => date('Y-m-d H:i:s'), 'cancel_date' => date('Y-m-d H:i:s')),
4135 array('order_id' => $order_id));
4136
4137 $wpdb->update('wpopi_opcom_order',
4138 array('order_date' => date('Y-m-d H:i:s'), 'access_date' => date('Y-m-d H:i:s'), 'cancel_date' => null),
4139 array('order_id' => $new_order));
4140 }
4141 }
4142 else
4143 {
4144 write_log('Normal package change');
4145 $wpdb->update('wpopi_opcom_order',
4146 array('end_date' => date('Y-m-d H:i:s'), 'cancel_date' => date('Y-m-d H:i:s')),
4147 array('order_id' => $order_id));
4148
4149 $wpdb->update('wpopi_opcom_order',
4150 array('order_date' => date('Y-m-d H:i:s'), 'access_date' => date('Y-m-d H:i:s'), 'cancel_date' => null, 'end_date' => null),
4151 array('order_id' => $new_order));
4152 }
4153
4154 /* Campaign ID */
4155 if(isset($form_order['campaign_id']))
4156 {
4157 $wpdb->update('wpopi_opcom_order',
4158 array('campaign_id' => $form_order['campaign_id']),
4159 array('order_id' => $new_order));
4160 }
4161
4162/*
4163KEEP OLD DISCOUNT CODE
4164ADD PRICE CALCULATION / DISCOUNTED
4165*/
4166
4167 $row_to_insert = array(
4168 'package_id' => $form_order['new_level'],
4169 'discount_percentage' => 0,
4170 'billing_amount' => $packages[$form_order['new_level']]->price,
4171 /* 'description' => $user->display_name .', Opinahjon Akatemian '.$packages[$new_order['new_level']]->name, */
4172 'description' => opmem_create_order_line($user->display_name, $packages[$new_order['new_level']]->name),
4173 'tax_percentage' => OPMEM_INVOICE_VAT,
4174 'order_id' => $new_order,
4175 );
4176 if(isset($form_order['discount_percentage']))
4177 {
4178 $row_to_insert['discount_percentage'] = $form_order['discount_percentage'];
4179 }
4180 $wpdb->insert('wpopi_opcom_order_line', $row_to_insert);
4181 // TODO: order logging
4182
4183 if($form_order['tikon'] == 1)
4184 {
4185 $row_to_insert = array(
4186 'package_id' => 10,
4187 'discount_percentage' => 100,
4188 'billing_amount' => $packages[10]->price,
4189 'description' => 'Tikonin koulutukset',
4190 'tax_percentage' => OPMEM_INVOICE_VAT,
4191 'order_id' => $new_order,
4192 );
4193 $wpdb->insert('wpopi_opcom_order_line', $row_to_insert);
4194 // TODO: order logging
4195 }
4196
4197 /*
4198 if($create_new_order && $old_row_id2 == $active_row)
4199 {
4200
4201 $new_descr = str_replace($packages[$old_package_id]->name,
4202 $packages[$_POST['row-'. $old_row_id2 .'-package_id']]->name,
4203 $_POST['row-'. $old_row_id2 .'-description']);
4204 $row_to_insert = array(
4205 'package_id' => $_POST['row-'. $old_row_id2 .'-package_id'], // new id
4206 'discount_percentage' => $discount,
4207 'billing_amount' => $packages[$_POST['row-'. $old_row_id2 .'-package_id']]->price, // new price
4208 'description' => $new_descr,
4209 'tax_percentage' => '24',
4210 'order_id' => $new_order,
4211 );
4212 $wpdb->insert('wpopi_opcom_order_line', $row_to_insert);
4213
4214 }
4215 elseif($create_new_order)
4216 {
4217
4218 $row_to_insert = array(
4219 'package_id' => $_POST['row-'. $old_row_id2 .'-package_id'],
4220 'discount_percentage' => $discount,
4221 'billing_amount' => $_POST['row-'. $old_row_id2 .'-billing_amount'],
4222 'description' => $_POST['row-'. $old_row_id2 .'-description'],
4223 'tax_percentage' => '24',
4224 'order_id' => $new_order,
4225 );
4226 $wpdb->insert('wpopi_opcom_order_line', $row_to_insert);
4227
4228 }
4229 else
4230 {
4231
4232 // no package_id
4233 $row_to_insert = array(
4234 'discount_percentage' => $discount,
4235 'billing_amount' => $_POST['row-'. $old_row_id2 .'-billing_amount'],
4236 'description' => $_POST['row-'. $old_row_id2 .'-description'],
4237 'tax_percentage' => '24',
4238 );
4239 $wpdb->update('wpopi_opcom_order_line', $row_to_insert, array('line_id' => $old_row_id2));
4240
4241 }
4242 */
4243}
4244
4245function opmem_create_order_line($user_fullname, $package_name, $extra = false)
4246{
4247 $descr_line = '';
4248 if(!empty(OPMEM_INVOICE_ORDER_LINE_FORMAT))
4249 {
4250 $order_line_template = array('{firstname} {lastname}', '{package}');
4251 $order_line_replace = array($user_fullname, $package_name);
4252 $descr_line = str_replace($order_line_template, $order_line_replace, OPMEM_INVOICE_ORDER_LINE_FORMAT);
4253 }
4254 return $descr_line;
4255}
4256
4257function opmem_legacy_pmpro_getRandomCode()
4258{
4259 global $wpdb;
4260 while(empty($code))
4261 {
4262 $scramble = md5(AUTH_KEY . current_time('timestamp') . SECURE_AUTH_KEY);
4263 $code = substr($scramble, 0, 10);
4264 $code = apply_filters("pmpro_random_code", $code, $this); //filter
4265 $check = $wpdb->get_var("SELECT id FROM $wpdb->pmpro_membership_orders WHERE code = '$code' LIMIT 1");
4266 if($check || is_numeric($code))
4267 $code = NULL;
4268 }
4269 return strtoupper($code);
4270}
4271
4272function opmem_legacy_pmpro_create_order($membership_id, $user)
4273{
4274 global $wpdb;
4275 $transaction_id = 'PMPROLEGACY'.rand(10000, 99999);
4276 $sqlQuery = "INSERT INTO $wpdb->pmpro_membership_orders
4277 (`code`, `session_id`, `user_id`, `membership_id`, `billing_name`, `subtotal`, `couponamount`, `total`, `payment_type`, `status`, `gateway`, `gateway_environment`, `payment_transaction_id`, `subscription_transaction_id`, `timestamp`)
4278 VALUES('" . opmem_legacy_pmpro_getRandomCode() . "',
4279 '" . session_id() . "',
4280 " . $user->ID . ",
4281 " . $membership_id . ",
4282 '" . esc_sql($user->user_firstname) .' '. $user->user_lastname . "',
4283 '0',
4284 '0',
4285 '0',
4286 'Check',
4287 'success',
4288 'check',
4289 'production',
4290 '" . $transaction_id. "',
4291 '" . $transaction_id . "',
4292 '" . date("Y-m-d H:i:s") . "'
4293 )";
4294
4295 if($wpdb->query($sqlQuery) !== false)
4296 {
4297 // legacy saved
4298 }
4299
4300}
4301
4302
4303
4304/*
4305* Log an order edit. Fetches the other required info from DB.
4306* @param $order_id ID of an affected order
4307*/
4308function opcom_log_order_save($order_id)
4309{
4310 global $billing_fields, $wpdb, $logger;
4311 $order_edit = $wpdb->get_row("
4312 SELECT order_id, order_identifier, order_status, user_id, order_date, access_date, cancel_date, end_date,
4313 first_invoicing_date, first_cancel_date, campaign_id,
4314 vatcode, organization_id, contract_start, billing_period, cancel_delay, extra_info, notes, legacy_order_id
4315 FROM wpopi_opcom_order
4316 WHERE order_id = '$order_id'");
4317 $meta_edit = get_user_meta($order_edit->user_id);
4318 $user_edit = get_userdata($order_edit->user_id);
4319
4320 $user_id = $order_edit->user_id;
4321 $data_to_log = array('order' => $order_edit );
4322
4323 foreach($billing_fields as $key => $values)
4324 {
4325 if(isset($meta_edit[$key]))
4326 {
4327 $data_to_log['usermeta'][$key] = $meta_edit[$key][0];
4328 }
4329 }
4330 $logger->addInfo(serialize($data_to_log), array(
4331 'admin_id' => get_current_user_id(),
4332 'user_id' => $order_edit->user_id,
4333 'order_id' => $order_id,
4334 'action' => 'edit_order'));
4335}
4336
4337/**
4338 * Fetch the basic package (classic "non-cumulative" package)
4339 *
4340 * @param $return_info Wether the function should return an array of info
4341 * @return Package info (see above), package ID, or false if not found
4342 *
4343 * Order statuses:
4344 * - success Normal ongoing order that's shown in the billing view.
4345 * - active Active order, not individually billable. For all sort of special cases.
4346 * - history Order modified in the past, and should have been succeeded by another order.
4347 * - accountor
4348 * - cancelled Should have cancel_date and end_date. Valid until end_date.
4349 * - trial Should have end_date. Valid until end_date.
4350 *
4351 * Please note: combination of order_status == 'trial' and package type 'normal' is allowed.
4352 * (Ie. user can have XL package as his/her trial.)
4353 */
4354function opmem_get_user_basic_package($user_id, $return_info = false)
4355{
4356 global $wpdb, $sql_fields;
4357
4358 $packages = $wpdb->get_results('SELECT package_id, name, price, type FROM wpopi_opcom_package', OBJECT_K);
4359 $orders = $wpdb->get_results("SELECT ". $sql_fields['order'] ."
4360 FROM wpopi_opcom_order
4361 WHERE user_id = '". $user_id ."'
4362 ORDER BY order_id DESC", OBJECT);
4363
4364if(isset($_GET['testlevels']) && $_GET['testlevels'] = 1)
4365{
4366 echo '<br /><strong>Orders:</strong><br />';
4367 print_r($orders);
4368}
4369
4370// NOTE: not optimal
4371 if($orders[0]->order_status == 'cancelled')
4372 {
4373 foreach($orders as $order)
4374 {
4375 if ( ($order->order_status == 'history' && $order->end_date > date('Y-m-d H:i:s')) )
4376 {
4377 $rows = $wpdb->get_results("SELECT ". $sql_fields['order_line'] .", wpopi_opcom_package.name as package_name
4378 FROM wpopi_opcom_order_line, wpopi_opcom_package
4379 WHERE order_id = '". $order->order_id ."'
4380 AND wpopi_opcom_package.package_id = wpopi_opcom_order_line.package_id");
4381 foreach($rows as $row)
4382 {
4383 // todo: normal packages without hardcoding 1, 2, 6, 9
4384 if( $packages[$row->package_id]->type == 'normal' )
4385 {
4386 if($return_info)
4387 {
4388 return array(
4389 'package_name' => $row->package_name,
4390 'package_id' => $row->package_id,
4391 'order_id' => $order->order_id,
4392 'order_date' => $order->order_date,
4393 'end_date' => $order->end_date,
4394 'cancel_date' => $order->cancel_date,
4395 'order_status' => $order->order_status,
4396 'campaign_id' => $order->campaign_id);
4397 }
4398 else
4399 {
4400 return $row->package_id;
4401 }
4402
4403 }
4404 }
4405 }
4406 }
4407 }
4408
4409 if( $orders[0]->order_status == 'trial' )
4410 {
4411
4412 write_log('Found a trial order for user '. $user_id);
4413
4414 $rows = $wpdb->get_results("SELECT ". $sql_fields['order_line'] .", wpopi_opcom_package.name as package_name
4415 FROM wpopi_opcom_order_line, wpopi_opcom_package
4416 WHERE order_id = '". $orders[0]->order_id ."'
4417 AND wpopi_opcom_package.package_id = wpopi_opcom_order_line.package_id");
4418
4419 $real_trial = false;
4420 foreach($rows as $row2)
4421 {
4422 $package_name = $row2->package_name;
4423 // todo: trial packages without hardcoding
4424 if( $row2->package_id == 11
4425 || $row2->package_id == 12
4426 || $row2->package_id == 13
4427 || $row2->package_id == 14
4428 || $row2->package_id == 7 )
4429 {
4430 $real_trial = true;
4431 }
4432 else
4433 {
4434 $package_name = $package_name .' (Koeajo)';
4435 }
4436
4437 $old_package = $row2->package_id;
4438 if($row2->package_id > 10)
4439 {
4440 $old_package = $row2->package_id - 1;
4441 }
4442
4443 if($return_info === true && $orders[0]->end_date < date('Y-m-d H:i:s'))
4444 {
4445 return array(
4446 'package_name' => $package_name,
4447 'package_id' => false,
4448 'new_package_id' => false,
4449 'order_id' => $orders[0]->order_id,
4450 'order_date' => $orders[0]->order_date,
4451 'end_date' => $orders[0]->end_date,
4452 'cancel_date' => $orders[0]->cancel_date,
4453 'order_status' => $orders[0]->order_status,
4454 'campaign_id' => $orders[0]->campaign_id);
4455 }
4456 elseif($return_info === false && $orders[0]->end_date < date('Y-m-d H:i:s'))
4457 {
4458 return false;
4459 }
4460 elseif($return_info)
4461 {
4462 return array(
4463 'package_name' => $package_name,
4464 'package_id' => $old_package,
4465 'new_package_id' => $row2->package_id,
4466 'order_id' => $orders[0]->order_id,
4467 'order_date' => $orders[0]->order_date,
4468 'end_date' => $orders[0]->end_date,
4469 'cancel_date' => $orders[0]->cancel_date,
4470 'order_status' => $orders[0]->order_status,
4471 'campaign_id' => $orders[0]->campaign_id);
4472 }
4473 else
4474 {
4475 return $row2->package_id;
4476 }
4477
4478 }
4479 }
4480 elseif( $orders[0]->order_status == 'success'
4481 || $orders[0]->order_status == 'active'
4482 || $orders[0]->order_status == 'accountor'
4483 || $orders[0]->order_status == 'cancelled'
4484 || $orders[0]->order_status == 'history' )
4485 {
4486 $order_ids = $orders[0]->order_id;
4487 if(isset($orders[1]))
4488 {
4489 $order_ids .= ', '. $orders[1]->order_id;
4490 }
4491 $rows = $wpdb->get_results("SELECT ". $sql_fields['order_line'] .", wpopi_opcom_package.name as package_name, wpopi_opcom_package.upgrade_path
4492 FROM wpopi_opcom_order_line, wpopi_opcom_package
4493 WHERE order_id IN (". $order_ids .")
4494 AND wpopi_opcom_package.package_id = wpopi_opcom_order_line.package_id ORDER BY line_id DESC");
4495
4496 if( isset($rows[1]) && $return_info === false && $orders[1]->order_status == 'history'
4497 && $orders[1]->access_date > date('Y-m-d H:i:s') && $rows[1]->upgrade_path > $rows[0]->upgrade_path )
4498 {
4499 return $rows[1]->package_id;
4500 }
4501 elseif( isset($rows[1]) && $orders[1]->order_status == 'history'
4502 && $orders[1]->access_date > date('Y-m-d H:i:s') && $rows[1]->upgrade_path > $rows[0]->upgrade_path )
4503 {
4504 return array(
4505 'package_name' => $rows[1]->package_name,
4506 'package_id' => $rows[1]->package_id,
4507 'order_id' => $orders[1]->order_id,
4508 'order_date' => $orders[1]->order_date,
4509 'end_date' => $orders[1]->end_date,
4510 'cancel_date' => $orders[1]->cancel_date,
4511 'order_status' => $orders[1]->order_status,
4512 'campaign_id' => $orders[1]->campaign_id);
4513 }
4514 elseif(!empty($orders[0]->end_date) && $orders[0]->end_date < date('Y-m-d H:i:s') && $return_info === false)
4515 {
4516 return false;
4517 }
4518 elseif(!empty($orders[0]->end_date) && $orders[0]->end_date < date('Y-m-d H:i:s'))
4519 {
4520 return array(
4521 'package_name' => $rows[0]->package_name,
4522 'package_id' => $rows[0]->package_id,
4523 'order_id' => false,
4524 'order_date' => $orders[0]->order_date,
4525 'end_date' => $orders[0]->end_date,
4526 'cancel_date' => $orders[0]->cancel_date,
4527 'order_status' => $orders[0]->order_status,
4528 'campaign_id' => $orders[0]->campaign_id);
4529 }
4530
4531 foreach($rows as $row)
4532 {
4533 // todo: normal packages without hardcoding 1, 2, 6, 9
4534 if( $packages[$row->package_id]->type == 'normal' )
4535 {
4536 if($return_info)
4537 {
4538 return array(
4539 'package_name' => $row->package_name,
4540 'package_id' => $row->package_id,
4541 'order_id' => $orders[0]->order_id,
4542 'order_date' => $orders[0]->order_date,
4543 'end_date' => $orders[0]->end_date,
4544 'cancel_date' => $orders[0]->cancel_date,
4545 'order_status' => $orders[0]->order_status,
4546 'campaign_id' => $orders[0]->campaign_id);
4547 }
4548 else
4549 {
4550 return $row->package_id;
4551 }
4552 }
4553 }
4554 }
4555}
4556
4557/**
4558 * Get a list of courses that are restricted for this particular user.
4559 * This is a quick and dirty way to do this.
4560 * @return Array of course definitions OR false if all is clear
4561 */
4562function opmem_get_user_restricted_courses($user_id)
4563{
4564 global $wpdb, $sql_fields;
4565 $packages = $wpdb->get_results("SELECT package_id, name, price, type
4566 FROM wpopi_opcom_package WHERE type = 'restricted'", OBJECT_K);
4567
4568 // No such package on this site
4569 if(empty($packages))
4570 {
4571 return array();
4572 }
4573
4574 $restricted_packages = array();
4575 foreach($packages as $pack)
4576 {
4577 $restricted_packages[] = $pack->package_id;
4578 }
4579 $restricted = implode(",", $restricted_packages);
4580
4581 // Get all restricted courses, and sort them by package
4582 $all_restricted = $wpdb->get_results("SELECT *
4583 FROM wpopi_opcom_package_course WHERE package_id IN (". $restricted .")", OBJECT_K);
4584 $restricted_courses = array();
4585 foreach($all_restricted as $restr)
4586 {
4587 $restricted_courses_by_pack[$restr->package_id][] = $restr->site_id. '-' .$restr->course_id;
4588 // $restricted_courses_all[] = $restr->site_id. '-' .$restr->course_id;
4589 }
4590
4591 $order = $wpdb->get_results("SELECT ". $sql_fields['order'] ."
4592 FROM wpopi_opcom_order
4593 WHERE user_id = '". $user_id ."'
4594 ORDER BY order_id DESC", OBJECT);
4595 $rows = $wpdb->get_results("SELECT ". $sql_fields['order_line'] ."
4596 FROM wpopi_opcom_order_line
4597 WHERE order_id = '". $order[0]->order_id ."' AND package_id IN (". $restricted .")", OBJECT);
4598
4599// debug
4600// $restricted_courses_by_pack[232][] = '1-235235';
4601
4602 if(empty($rows))
4603 {
4604 // User has no packages of this type (so can't see any of the courses)
4605 return $restricted_courses_by_pack;
4606 }
4607 else
4608 {
4609 // Remove courses that the user has access to
4610 foreach($rows as $row)
4611 {
4612 unset($restricted_courses_by_pack[$row->package_id]);
4613 }
4614 return $restricted_courses_by_pack;
4615 }
4616
4617}
4618
4619
4620/**
4621 * Check if user has a Tikon order row.
4622 * @return package id or false if nothing found
4623 */
4624function opmem_get_user_tikon_package($user_id)
4625{
4626 global $wpdb, $sql_fields;
4627
4628 $order = $wpdb->get_results("SELECT ". $sql_fields['order'] ."
4629 FROM wpopi_opcom_order
4630 WHERE user_id = '". $user_id ."'
4631 ORDER BY order_id DESC", OBJECT);
4632
4633 $return = false;
4634 if( $order[0]->order_status == 'success'
4635 || $order[0]->order_status == 'active'
4636 || $order[0]->order_status == 'accountor'
4637 || ($order[0]->order_status == 'cancelled' && $order[0]->end_date > date('Y-m-d H:i:s'))
4638 || $order[0]->order_status == 'trial' )
4639 {
4640 $rows = $wpdb->get_results("SELECT ". $sql_fields['order_line'] ."
4641 FROM wpopi_opcom_order_line
4642 WHERE order_id = '". $order[0]->order_id ."'");
4643 foreach($rows as $row)
4644 {
4645 // todo: normal packages without hardcoding
4646 if( $row->package_id == 10 )
4647 {
4648 $return = $row->package_id;
4649 }
4650 }
4651 }
4652 return $return;
4653}
4654
4655/**
4656 * Check if user has extra rows
4657 * @return array of packages (with basic info) or an empty array if nothing found
4658 */
4659function opmem_get_user_extra_packages($user_id)
4660{
4661 global $wpdb, $sql_fields;
4662 $packages = $wpdb->get_results('SELECT package_id, name, price, type FROM wpopi_opcom_package', OBJECT_K);
4663 $order = $wpdb->get_results("SELECT ". $sql_fields['order'] ."
4664 FROM wpopi_opcom_order
4665 WHERE user_id = '". $user_id ."'
4666 ORDER BY order_id DESC", OBJECT);
4667
4668 $return = array();
4669 if( $order[0]->order_status == 'success'
4670 || $order[0]->order_status == 'active'
4671 || $order[0]->order_status == 'accountor'
4672 || ($order[0]->order_status == 'cancelled' && $order[0]->end_date > date('Y-m-d H:i:s'))
4673 || $order[0]->order_status == 'trial' )
4674 {
4675 $rows = $wpdb->get_results("SELECT ". $sql_fields['order_line'] ."
4676 FROM wpopi_opcom_order_line
4677 WHERE order_id = '". $order[0]->order_id ."'");
4678 foreach($rows as $row)
4679 {
4680 if( $packages[$row->package_id]->type == 'extra'
4681 || $packages[$row->package_id]->type == 'restricted' )
4682 {
4683 // $row->package_id;
4684 $return[$row->package_id] = array(
4685 'package_name' => $packages[$row->package_id]->name,
4686 'package_id' => $row->package_id,
4687 'package_type' => $packages[$row->package_id]->type,
4688 'order_id' => $order[0]->order_id,
4689 'order_date' => $order[0]->order_date,
4690 'end_date' => $order[0]->end_date,
4691 'cancel_date' => $order[0]->cancel_date,
4692 'order_status' => $order[0]->order_status,
4693 'campaign_id' => $order[0]->campaign_id
4694 );
4695 }
4696 }
4697 }
4698 return $return;
4699}
4700
4701/**
4702 * Fetch all the courses in a given package, or one that the current user has.
4703 * @param $package_id
4704 * @return false or array
4705 */
4706function opmem_get_package_courses($package_id = false)
4707{
4708 global $wpdb;
4709 /* Try to get current user's package */
4710 if($package_id === false)
4711 {
4712 $package_id = opmem_get_user_basic_package(get_current_user_id());
4713 }
4714 /* Give up */
4715 if($package_id === false)
4716 {
4717 return false;
4718 }
4719
4720 $sql_courses = "SELECT course_id, site_id FROM wpopi_opcom_package_course
4721 WHERE package_id = '". $package_id ."'";
4722 $package_courses = $wpdb->get_results($sql_courses, OBJECT_K);
4723
4724 $courses = array();
4725 foreach($package_courses as $course)
4726 {
4727 $courses[$course->site_id][] = $course->course_id;
4728 }
4729 if(empty($courses))
4730 {
4731 return false;
4732 }
4733 return $courses;
4734}
4735
4736/**
4737 * Check if a given course belongs to a specified package, or one that the current user has.
4738 * @param $course_id
4739 * @param $package_id
4740 * @return true/false
4741 */
4742function opmem_is_course_in_package($course_id, $package_id = false, $site_id = 1)
4743{
4744 global $wpdb;
4745 /* Try to get current user's package */
4746 if($package_id === false)
4747 {
4748 $package_id = opmem_get_user_basic_package(get_current_user_id());
4749 }
4750 /* Give up */
4751 if($package_id === false)
4752 {
4753 return false;
4754 }
4755
4756 $sql_courses = "SELECT course_id, site_id FROM wpopi_opcom_package_course
4757 WHERE package_id IN ('". $package_id ."') AND course_id = '". $course_id ."' AND site_id = '". $site_id ."'";
4758 $package_courses = $wpdb->get_row($sql_courses, OBJECT);
4759
4760 if(!empty($package_courses) && $package_courses->course_id == $course_id)
4761 {
4762 return true;
4763 }
4764 else
4765 {
4766 return false;
4767 }
4768}
4769
4770/**
4771 * Check if a given course belongs to a package that the user has.
4772 * Order:
4773 * - package 14 (single trial)
4774 * - normal basic package
4775 * - tikon package
4776 *
4777 * @param $course_id
4778 * @param $package_id
4779 * @return true/false (false as the "default")
4780 *
4781 * TODO: change this to loop through the order lines of a user
4782 */
4783function opmem_user_has_course_access($course_id, $user_id, $site_id = 1)
4784{
4785 global $wpdb, $sql_fields;
4786
4787 /* Try to get current user's package */
4788 $package_id = opmem_get_user_basic_package($user_id);
4789// echo '<br />package_id: '. $package_id;
4790 if($package_id === false)
4791 {
4792 /* Give up */
4793 return false;
4794 }
4795 elseif($package_id == 14)
4796 {
4797 $order = $wpdb->get_results("SELECT ". $sql_fields['order'] ."
4798 FROM wpopi_opcom_order
4799 WHERE user_id = '". $user_id ."'
4800 ORDER BY order_id DESC", OBJECT);
4801 $rows = $wpdb->get_results("SELECT ". $sql_fields['order_line'] ."
4802 FROM wpopi_opcom_order_line
4803 WHERE package_id = 14 AND order_id = '". $order[0]->order_id ."' AND description LIKE '%(". $course_id .")%'");
4804 foreach($rows as $row)
4805 {
4806 // todo: normal packages without hardcoding
4807 if( $row->package_id == 14 )
4808 {
4809 return true;
4810 }
4811 }
4812 }
4813 else
4814 {
4815 /* Normal package check */
4816 $tikon_package_id = opmem_get_user_tikon_package($user_id);
4817 $sql_courses = "SELECT course_id, site_id FROM wpopi_opcom_package_course
4818 WHERE package_id IN ('". $package_id ."') AND course_id = '". $course_id ."' AND site_id = '". $site_id ."'";
4819 $package_courses = $wpdb->get_row($sql_courses, OBJECT);
4820
4821 if(!empty($package_courses) && $package_courses->course_id == $course_id)
4822 {
4823 return true;
4824 }
4825 elseif($tikon_package_id !== false)
4826 {
4827 $sql_courses_tikon = "SELECT course_id, site_id FROM wpopi_opcom_package_course
4828 WHERE package_id IN ('". $tikon_package_id ."') AND course_id = '". $course_id ."' AND site_id = '". $site_id ."'";
4829 $package_courses_tikon = $wpdb->get_row($sql_courses_tikon, OBJECT);
4830 if(!empty($package_courses_tikon) && $package_courses_tikon->course_id == $course_id)
4831 {
4832 return true;
4833 }
4834 }
4835 }
4836 return false;
4837}
4838
4839/**
4840 * Get packages for a course.
4841 * @return Array
4842 */
4843function opmem_course_packages($course_id, $site_id = 1)
4844{
4845 global $wpdb;
4846 $sql_courses = "SELECT course_id, site_id, package_id FROM wpopi_opcom_package_course
4847 WHERE course_id = '". $course_id ."' AND site_id = '". $site_id ."'";
4848 $package_courses = $wpdb->get_results($sql_courses, OBJECT);
4849
4850 $collect = array();
4851 foreach($package_courses as $course)
4852 {
4853 $collect[$course->package_id] = array(
4854 'package_id' => $course->package_id,
4855 'site_id' => $course->site_id,
4856 'course_id' => $course->course_id
4857 );
4858 }
4859 return $collect;
4860
4861}
4862
4863
4864function opmem_array_unserialize(&$item, $key)
4865{
4866 $item = unserialize($item);
4867}
4868
4869/**
4870 * Show profile page. Does not take input. Neither does it return anything
4871 * (even though it probably should because this is not proper shortcode usage).
4872 *
4873 * Contains connections to legacy system (PMPro) in order to show
4874 * old invoices to long-standing customers. Currently disabled.
4875 */
4876function opmem_show_profile_page()
4877{
4878
4879 global $wpdb, $current_user; // , $levels;
4880 /* global $opinahjo_package_settings;
4881 global $wildcard_domains; */
4882 global $user_email, $sql_fields, $opmem_profile_pages;
4883
4884 /* Get the order */
4885 $orders = $wpdb->get_results("SELECT ". $sql_fields['order'] ."
4886 FROM wpopi_opcom_order
4887 WHERE user_id = '". $current_user->ID ."'
4888 ORDER BY order_id DESC", OBJECT);
4889
4890 $has_history = false;
4891/* if(count($orders) > 1)
4892 {
4893 foreach($orders as $order)
4894 {
4895 if($order->order_status == 'history'
4896 && strtotime($order->end_date) > time())
4897 {
4898 $has_history = $order->order_id;
4899 }
4900 }
4901 } */
4902
4903 $order_package = opmem_get_user_basic_package($current_user->ID, true);
4904
4905 if($order_package === false)
4906 {
4907 $order_name = 'Ei pakettia';
4908 }
4909 else
4910 {
4911 $order_name = $order_package['package_name'];
4912 if($order_package['end_date'])
4913 {
4914 $end_date = $order_package['end_date'];
4915 }
4916 else
4917 {
4918 $end_date = '--';
4919 }
4920 if($order_package['order_status'] == 'success'
4921 || $order_package['order_status'] == 'active')
4922 {
4923 // $order_status = 'Tilaus voimassa';
4924 $end_date = '--';
4925 }
4926 elseif($order_package['order_status'] == 'cancelled')
4927 {
4928 // $order_status = 'Tilaus peruttu '. date('d.m.Y', strtotime($order_package['cancel_date']));
4929 $end_date = $order_package['end_date'];
4930 }
4931 elseif($order_package['order_status'] == 'history')
4932 {
4933 $has_history = true;
4934 }
4935 }
4936
4937 $extra_packages = opmem_get_user_extra_packages($current_user->ID);
4938
4939 if(is_user_logged_in())
4940 {
4941 // TODO:
4942 if(strstr($_SERVER['REQUEST_URI'], '/tilaus/'))
4943 {
4944 if($_GET['msg'] == 1)
4945 {
4946 ?>
4947 <div id="order_confirmation">
4948 <h2>Kiitos tilauksestasi!</h2>
4949 <p>Siirry tutustumaan koulutuksiimme <a href="/koulutukset/">tästä</a></p>
4950 </div>
4951 <?php
4952 }
4953 }
4954 ?>
4955 <style>
4956 #opmem_profile_membership > div { float: left; width: 26%; }
4957 td.total { padding-bottom: 20px; }
4958 #opmem_profile_membership_orders td { line-height: 20px; padding-bottom: 3px; }
4959 #opmem_profile_membership_orders td:first-child { width: 190px; }
4960 #opmem_profile_membership_orders table { width: 70% !important; margin-top: 12px; }
4961 #order_confirmation { padding: 30px; background-color: #eee; width: 100%; text-align: center; }
4962 #order_confirmation h2 { margin-top: 0; }
4963 #order_confirmation p { margin-bottom: 0; }
4964 </style>
4965 <div id="opmem_profile_membership">
4966 <h3><?php _e('My Membership', 'opinahjo-members'); ?></h3>
4967
4968 <div class="left">
4969 <h4><?php _e("Package", "opinahjo-members");?></h4>
4970 <p><?php echo $order_name; ?>
4971 <?php
4972 if(!empty($extra_packages))
4973 {
4974 echo '<br />Lisäoptiot: ';
4975 foreach($extra_packages as $pack)
4976 {
4977 echo $pack['package_name'] .' ';
4978 }
4979 }
4980 ?></p>
4981 </div>
4982 <div class="middle">
4983 <h4><?php _e("Expiration", "opinahjo-members"); ?></h4>
4984 <p><?php
4985 if($end_date != '--')
4986 {
4987 echo date('d.m.Y', strtotime($end_date));
4988 }
4989 else
4990 {
4991 echo '--';
4992 }
4993 ?></p>
4994 </div>
4995 <div class="right">
4996 <p>
4997 <?php
4998// TODO: not the best idea, should be available to change cancelled order
4999 if($has_history === false && $order_package['order_status'] != 'cancelled')
5000 {
5001 ?>
5002 <br /><a href="<?php echo $opmem_profile_pages[OPMEM_BILLING_COUNTRY_CODE]['prefix'] . $opmem_profile_pages[OPMEM_BILLING_COUNTRY_CODE]['change_order']; ?>"><?php _e('Chance package', 'opinahjo-members'); ?></a>
5003 <?php
5004 }
5005 if($order_package['order_status'] != 'cancelled')
5006 {
5007 ?>
5008 <br /><a href="<?php echo $opmem_profile_pages[OPMEM_BILLING_COUNTRY_CODE]['prefix'] . $opmem_profile_pages[OPMEM_BILLING_COUNTRY_CODE]['cancel_order']; ?>"><?php _e('Cancel order', 'opinahjo-members'); ?></a>
5009 <?php
5010 }
5011 ?>
5012 <br /><a href="<?php echo $opmem_profile_pages[OPMEM_BILLING_COUNTRY_CODE]['prefix'] . $opmem_profile_pages[OPMEM_BILLING_COUNTRY_CODE]['edit_billing_info']; ?>"><?php _e('Edit billing information', 'opinahjo-members'); ?></a>
5013 <br /><a href="<?php echo $opmem_profile_pages[OPMEM_BILLING_COUNTRY_CODE]['prefix'] . $opmem_profile_pages[OPMEM_BILLING_COUNTRY_CODE]['change_password']; ?>"><?php _e('Change password', 'opinahjo-members'); ?></a>
5014 </p>
5015 </div>
5016 </div>
5017 <div class="guillotine"></div>
5018 <?php
5019
5020 /* ORDERS */
5021
5022 if($order_package['order_status'] == 'cancelled')
5023 {
5024 ?>
5025 <div id="opinahjo_order_cancelled_text">
5026 <p><?php _e('Order cancelled on', 'opinahjo-members'); ?> <?php echo date( 'd.m.Y', strtotime($order_package['cancel_date']) ); ?>.
5027 <br /><?php printf(esc_html__('Access to courses available until %1$s.', 'opinahjo-members'), date('d.m.Y', strtotime($order_package['end_date']))); ?></p>
5028 </div>
5029 <?php
5030 }
5031 elseif($order_package['order_status'] == 'history')
5032 {
5033 ?>
5034 <div id="opinahjo_order_cancelled_text">
5035 <p><?php _e('Package changed on', 'opinahjo-members'); ?> <?php echo date( 'd.m.Y', strtotime($order_package['cancel_date']) ); ?>
5036 <br /><?php printf(esc_html__('The end date for current order is %1$s after which the account will switch to the new package.', 'opinahjo-members'), date('d.m.Y', strtotime($order_package['end_date']))); ?></p>
5037 </div>
5038 <?php
5039 }
5040
5041 /* LEGACY ORDERS */
5042 if(function_exists('pmpro_hasMembershipLevel'))
5043 {
5044
5045 $ssorder = new MemberOrder();
5046 $ssorder->getLastMemberOrder();
5047 $invoices = $wpdb->get_results("SELECT *, UNIX_TIMESTAMP(timestamp) as timestamp FROM $wpdb->pmpro_membership_orders WHERE user_id = '$current_user->ID' ORDER BY timestamp DESC LIMIT 6");
5048 $user_cancelled = get_user_meta($current_user->ID, 'opinahjo_cancelled');
5049 array_walk ($user_cancelled, opmem_array_unserialize);
5050 $last_cancelled = false;
5051 if($user_cancelled)
5052 {
5053 $last_cancelled = end($user_cancelled);
5054 }
5055 }
5056
5057 if(!empty($invoices) || !empty($orders))
5058 {
5059 ?>
5060 <div id="opmem_profile_membership_orders">
5061 <h3><?php _e('Orders', 'opinahjo-members'); ?></h3>
5062 <p><?php _e("VAT is added to the prices", "opinahjo-members"); ?> ( 24% ).</p>
5063 <table cellpadding="0" cellspacing="0" border="0">
5064 <thead>
5065 <tr>
5066 <th><?php _e("Level", "opinahjo-members"); ?></th>
5067 <th><?php _e("Price", "opinahjo-members"); ?></th>
5068 <th><?php _e("Order date", "opinahjo-members"); ?></th>
5069 <th><?php _e("End date", "opinahjo-members"); ?></th>
5070 </tr>
5071 </thead>
5072 <tbody>
5073 <?php
5074 }
5075
5076 if(!empty($orders))
5077 {
5078 // print_r($order_rows);
5079 foreach($orders as $ord)
5080 {
5081 $first = true;
5082 $total = 0;
5083 $order_rows = $wpdb->get_results("SELECT ". $sql_fields['order_line'] .",
5084 wpopi_opcom_package.name as package_name, wpopi_opcom_package.type as package_type
5085 FROM wpopi_opcom_order_line, wpopi_opcom_package
5086 WHERE order_id = '". $ord->order_id ."'
5087 AND wpopi_opcom_package.package_id = wpopi_opcom_order_line.package_id");
5088
5089 foreach($order_rows as $row)
5090 {
5091
5092 ?>
5093 <tr>
5094 <td><?php /* ?>
5095 <a href="<?php echo pmpro_url("invoice", "?invoice=" . $invoice->code)?>">
5096 <?php */
5097 echo $row->package_name;
5098 ?>
5099 <!-- /a -->
5100 </td>
5101 <td>
5102 <?php
5103 if($row->package_type == 'normal'
5104 || $row->package_type == 'extra'
5105 || $row->package_type == 'restricted')
5106 {
5107 echo $row->billing_amount .' €';
5108 if($row->discount_percentage != 0)
5109 {
5110 echo ' - '. $row->discount_percentage .'%';
5111 }
5112 $row_total = $row->billing_amount - ($row->billing_amount * $row->discount_percentage / 100);
5113 $total = $total + $row_total;
5114 }
5115 ?>
5116 </td>
5117 <td>
5118 <?php
5119 if($first)
5120 {
5121 echo date('d.m.Y', strtotime($ord->order_date));
5122 }
5123 ?>
5124 </td>
5125
5126 <td>
5127 <?php
5128
5129 if($ord->end_date && $first)
5130 {
5131 echo date('d.m.Y', strtotime($ord->end_date));
5132 }
5133 elseif($first)
5134 {
5135 echo "--";
5136 }
5137 ?>
5138 </td>
5139 </tr>
5140
5141 <?php
5142 $first = false;
5143 }
5144 /*
5145 if(count($order_rows) > 1)
5146 {
5147 ?>
5148 <tr>
5149 <td></td>
5150 <td class="total"><?php echo $total; ?> €</td>
5151 <td></td>
5152 <td></td>
5153 <td></td>
5154 </tr>
5155 <?php
5156 }
5157 */
5158 }
5159 }
5160
5161/*
5162REMOVING LEGACY ORDERS FOR NOW
5163- Needs some sort of fuzzy matching of the newest order.
5164
5165
5166 if(!empty($invoices))
5167 {
5168 ?>
5169
5170 <?php
5171 $count = 0;
5172 foreach($invoices as $invoice)
5173 {
5174 if($count++ > 4)
5175 break;
5176
5177 //get an member order object
5178 $invoice_id = $invoice->id;
5179 $invoice = new MemberOrder;
5180 $invoice->getMemberOrderByID($invoice_id);
5181 $invoice->getMembershipLevel();
5182
5183 // $cancel_key = array_search($invoice_id, array_column($user_cancelled, 'order_id'));
5184 // $cancel_data = $user_cancelled[$cancel_key];
5185
5186 ?>
5187 <tr id="pmpro_account-invoice-<?php echo $invoice->code; ?>">
5188 <td><a href="<?php echo pmpro_url("invoice", "?invoice=" . $invoice->code)?>"><?php echo date(get_option("date_format"), $invoice->timestamp)?></td>
5189 <td>
5190 <?php
5191 if($custom_package && (trim($current_user->membership_level->name) == trim($invoice->membership_level->name)) )
5192 {
5193 echo $package_name;
5194 }
5195 else
5196 {
5197 echo $invoice->membership_level->name;
5198 }
5199 ?>
5200 </td>
5201 <td><?php echo pmpro_formatPrice($invoice->total); ?></td>
5202 <td>
5203 <?php
5204 $show_canceldate = false;
5205 foreach($user_cancelled as $cancel)
5206 {
5207 if ($cancel['order_id'] == $invoice_id && isset($cancel['end_date']))
5208 {
5209 $cancel_key = $iterator;
5210 $show_canceldate = true;
5211 echo date( 'd.m.Y', strtotime($cancel['end_date']) );
5212 }
5213 }
5214
5215 if($show_canceldate === false)
5216 {
5217 echo "---";
5218 }
5219
5220 ?>
5221 </td>
5222 <td></td>
5223 </tr>
5224 <?php
5225 }
5226
5227 }
5228*/
5229
5230 if(!empty($invoices) || !empty($orders))
5231 {
5232 ?>
5233 </tbody>
5234 </table>
5235 </div>
5236 <?php if($count == 6)
5237 {
5238 ?>
5239 <div class="pmpro_actionlinks"><a href="<?php echo pmpro_url("invoice"); ?>"><?php _e("View All Invoices", "pmpro");?></a></div>
5240 <?php
5241 }
5242
5243 }
5244 }
5245
5246}
5247add_shortcode('opmem_user_profile_page', 'opmem_show_profile_page');
5248
5249
5250/**
5251 * Checks if the the user is on site 1, and if they have access to recordings
5252 */
5253function opcom_can_user_watch_recording($rec_id)
5254{
5255 if(get_current_blog_id() == 1)
5256 {
5257 global $wpdb;
5258 $cur_user = wp_get_current_user();
5259/*
5260 $option_levels = get_option( '_level_course_option' );
5261 $levels = explode(',', $option_levels[$rec_id]);
5262 $cur_user_membership = opmem_get_user_basic_package($cur_user->ID);
5263*/
5264 return opmem_user_has_course_access($rec_id, $cur_user->ID, 1);
5265 }
5266 else
5267 {
5268 return false;
5269 }
5270}
5271
5272/**
5273 * Checks if the user is on site 5, and if they have access to recordings.
5274 * Note: can't be used on listings that only exist on site #1!
5275 */
5276function opcom_can_user_watch_tikon_recording()
5277{
5278 $cur_user = wp_get_current_user();
5279 if ( get_current_blog_id() == 5 && opmem_get_user_tikon_package($cur_user->ID) )
5280 {
5281 return true;
5282 }
5283 else
5284 {
5285 return false;
5286 }
5287}
5288
5289/**
5290 * Checks if the user is on site 11, and if they have access to recordings.
5291 * Note: can't be used on listings that only exist on site #1!
5292 */
5293function can_user_watch_accountor_recording()
5294{
5295 $userdata = wp_get_current_user();
5296 $service_ac = get_user_meta($userdata->ID, 'service_accountoracademy');
5297
5298 if( get_current_blog_id() == 11
5299 && (strpos($userdata->user_email, '@accountor.fi')
5300 || $service_ac[0] == 1 ) )
5301 {
5302 // The accountor user actually has a legitimate order
5303 if(opmem_get_user_basic_package(get_current_user_id()) !== false)
5304 {
5305 return true;
5306 }
5307 else
5308 {
5309 return false;
5310 }
5311 }
5312 else
5313 {
5314 return false;
5315 }
5316}
5317
5318/**
5319 * Checks if user either has an accountor.fi email address, or they've been
5320 * manually marked as Accountor user. Function_exists because there's a potentially
5321 * different version on Norway site.
5322 */
5323function opcom_is_accountor_user()
5324{
5325 $userdata = wp_get_current_user();
5326 $service_ac = get_user_meta($userdata->ID, 'service_accountoracademy');
5327
5328 if( strpos($userdata->user_email, '@accountor.fi')
5329 || $service_ac[0] == 1 )
5330 {
5331 return true;
5332 }
5333 else
5334 {
5335 return false;
5336 }
5337}
5338
5339function opcom_show_dates($order_date, $billing_year, $billing_month)
5340{
5341 $order_stamp = strtotime($order_date);
5342 $extra_days = 0;
5343 $startdate = '01.' .$billing_month. '.' .$billing_year;
5344 $enddate = date('t', strtotime($billing_year.'-'.$billing_month.'-01')). '.' .$billing_month. '.' .$billing_year;
5345 if(date('Y', $order_stamp) == $billing_year && date('n', $order_stamp) == intval($billing_month) - 1)
5346 {
5347 $first_day = date('d', $order_stamp);
5348 $last_day = date('t', $order_stamp);
5349 $extra_days = intval($last_day) - intval($first_day) + 1;
5350 $start_month = intval($billing_month) - 1;
5351 $startdate = $first_day. '.' .$start_month. '.' .$billing_year;
5352 }
5353 elseif(date('Y', $order_stamp) == $billing_year && date('n', $order_stamp) == intval($billing_month))
5354 {
5355 $first_day = date('d', $order_stamp);
5356 $last_day = date('t', $order_stamp);
5357 $startdate = $first_day. '.' .$billing_month. '.' .$billing_year;
5358 $billable_days = intval($last_day) - intval($first_day) + 1;
5359 }
5360 return $startdate. ' - ' .$enddate;
5361}
5362
5363/*
5364 Tries to get the current package to the package change form
5365 Requires a current version of Opinahjo Members to work
5366*/
5367add_filter( 'gform_field_value_level', 'opmem_gform_set_level_on_update_form' );
5368function opmem_gform_set_level_on_update_form( $value )
5369{
5370
5371 global $wpdb;
5372 $packages = $wpdb->get_results('SELECT package_id, name, price, type FROM wpopi_opcom_package', OBJECT_K);
5373 if($_GET['level'])
5374 {
5375 return $_GET['level'] .'|'. $packages[$_GET['level']]->price;
5376 }
5377 elseif(is_user_logged_in())
5378 {
5379 $user_package = opmem_get_user_basic_package(get_current_user_id());
5380 return $user_package .'|'. $packages[$user_package]->price;
5381 }
5382 else
5383 {
5384 return $value;
5385 }
5386
5387}
5388
5389/**
5390 * Populate Gform order form fields (when not using Gform user registration)
5391 */
5392add_filter( 'gform_pre_render', 'opmem_populate_gform_order_form_fields', 21 );
5393add_filter( 'gform_pre_validation', 'opmem_populate_gform_order_form_fields', 21 );
5394add_filter( 'gform_pre_submission_filter', 'opmem_populate_gform_order_form_fields', 21 );
5395add_filter( 'gform_admin_pre_render', 'opmem_populate_gform_order_form_fields', 21 );
5396function opmem_populate_gform_order_form_fields( $form )
5397{
5398 global $wpdb, $finvoice_operators;
5399 if(is_user_logged_in())
5400 {
5401 $user = wp_get_current_user();
5402 global $order_metafields;
5403 }
5404 /* Lets display a warning if an admin is logged in */
5405 if(current_user_can('manage_options') && !is_admin() && strpos($form['title'], 'Tilaus'))
5406 {
5407 echo '<p>Admin: please note that you\'re changing your own order.</p>';
5408 }
5409
5410 foreach ( $form['fields'] as $key => &$field )
5411 {
5412 $mapped_fields = array();
5413 if ( $field->type == 'select' && $field->cssClass == 'operaattorit' )
5414 {
5415 $choices = array();
5416
5417 foreach ( $finvoice_operators as $op => $text )
5418 {
5419 $choices[] = array( 'text' => $text, 'value' => $op );
5420 $cur_cat = $post->term_taxonomy_id;
5421 }
5422 unset($choices[0]);
5423 $field->placeholder = 'Valitse operaattori';
5424 $field->choices = $choices;
5425 }
5426
5427 if ( $field->type == 'username' && $field->inputName == 'kayttajatunnus' )
5428 {
5429 if(is_user_logged_in())
5430 {
5431 $field->defaultValue = $user->user_login;
5432 }
5433 else
5434 {
5435 $field->defaultValue = 'oa'. bin2hex(openssl_random_pseudo_bytes(5));
5436 }
5437 }
5438
5439 if ( $field->type == 'text' && $field->inputName == 'kayttajatunnus' )
5440 {
5441 $field->defaultValue = 'oa'. bin2hex(openssl_random_pseudo_bytes(5));
5442 }
5443
5444 if ( $field->type == 'checkbox' && $field->inputName == 'tikon' )
5445 {
5446 if( opmem_get_user_tikon_package(get_current_user_id()) )
5447 {
5448 $field->defaultValue = 'Tikonin koulutukset +0€/kk (normaalihinta 29€/kk)';
5449 }
5450 }
5451
5452 if(is_user_logged_in() && ($form['title'] == 'Tilaus 2017' || $form['title'] == 'Order 2017') && !is_admin())
5453 {
5454 if( $field->type == 'coupon' )
5455 {
5456 $order_info = opmem_get_user_basic_package($user->ID, true);
5457 global $campaigns_data;
5458 if( !empty($campaigns_data[$order_info['campaign_id']]->discount_code)
5459 && $campaigns_data[$order_info['campaign_id']]->campaign_end > date('Y-m-d') )
5460 {
5461 ?>
5462 <script>
5463 jQuery( document ).ready(function() {
5464 jQuery("input.gf_coupon_code").val('<?php echo $campaigns_data[$order_info['campaign_id']]->discount_code; ?>');
5465 jQuery("input#gf_coupon_button").click();
5466 jQuery("div#gf_coupon_info").prepend('<div> <?php _e("Applying the current discount code: ", "opinahjo_theme"); ?> <?php echo $campaigns_data[$order_info['campaign_id']]->discount_code; ?></div>');
5467 });
5468 </script>
5469 <?php
5470 }
5471 }
5472 if( $field->type == 'email' )
5473 {
5474 $field->defaultValue = $user->user_email;
5475 }
5476 if( isset($order_metafields[$field->label]) && $field->type == 'text' )
5477 {
5478 $field->defaultValue = get_user_meta($user->ID, $order_metafields[$field->label]['meta'], true);
5479 }
5480 if( isset($order_metafields[$field->label]) && ($field->type == 'select' || $field->type == 'radio') )
5481 {
5482 // print_r (get_user_meta($user->ID, $order_metafields['select'][$field->label]['meta'], true) );
5483 $default = '';
5484 for($i = 0; $i < count($field->choices); $i++)
5485 {
5486 $field->choices[$i]['isSelected'] = 0;
5487 if(get_user_meta($user->ID, $order_metafields[$field->label]['meta'], true) == $field->choices[$i]['value'])
5488 {
5489 $field->choices[$i]['isSelected'] = 1;
5490 }
5491 }
5492 }
5493
5494 if( $field->type == 'password' || ($field->type == 'email' && $field->cssClass != 'billing_email_field') )
5495 {
5496 unset($form['fields'][$key]);
5497 }
5498 if($field->type == 'section' && $field->label == 'Tilin tiedot')
5499 {
5500 unset($form['fields'][$key]);
5501 }
5502 if($field->type == 'checkbox' && $field->inputName == 'extra')
5503 {
5504 // For now this only handles Tikon package
5505 for($i = 0; $i < count($field->choices); $i++)
5506 {
5507 $field->choices[$i]['isSelected'] = 0;
5508 if($field->choices[$i]['value'] == 'tikon' && opmem_get_user_tikon_package(get_current_user_id()) !== false)
5509 {
5510 $field->choices[$i]['isSelected'] = 1;
5511 }
5512 }
5513
5514 }
5515 if( $field->type == 'name' )
5516 {
5517 $mapped_fields[$field->id.'.3'] = $user->first_name;
5518 $mapped_fields[$field->id.'.6'] = $user->last_name;
5519 opmem_gform_prepopulate_complex_field($field, $mapped_fields);
5520 }
5521 if( $field->type == 'address' )
5522 {
5523 $mapped_fields[$field->id.'.1'] = get_user_meta($user->ID, 'oa_address', true);
5524 $mapped_fields[$field->id.'.5'] = get_user_meta($user->ID, 'oa_postalcode', true);
5525 $mapped_fields[$field->id.'.3'] = get_user_meta($user->ID, 'oa_city', true);
5526 opmem_gform_prepopulate_complex_field($field, $mapped_fields);
5527 }
5528 }
5529 }
5530 return $form;
5531}
5532
5533/*
5534add_filter( 'gform_pre_render', 'populate_finvoice_operator' );
5535add_filter( 'gform_pre_validation', 'populate_finvoice_operator' );
5536add_filter( 'gform_pre_submission_filter', 'populate_finvoice_operator' );
5537add_filter( 'gform_admin_pre_render', 'populate_finvoice_operator' );
5538function populate_finvoice_operator( $form )
5539{
5540// print_r($form);
5541 global $wpdb, $finvoice_operators;
5542 foreach ( $form['fields'] as &$field )
5543 {
5544
5545 if ( $field->type == 'select' && $field->cssClass == 'operaattorit' )
5546 {
5547 $choices = array();
5548
5549 foreach ( $finvoice_operators as $op => $text )
5550 {
5551 $choices[] = array( 'text' => $text, 'value' => $op );
5552 $cur_cat = $post->term_taxonomy_id;
5553 }
5554 unset($choices[0]);
5555 $field->placeholder = 'Valitse operaattori';
5556 $field->choices = $choices;
5557 }
5558
5559 if ( $field->type == 'username' && $field->inputName == 'kayttajatunnus' )
5560 {
5561 $field->defaultValue = 'oa'. bin2hex(openssl_random_pseudo_bytes(5));
5562 }
5563
5564 if ( $field->type == 'text' && $field->inputName == 'kayttajatunnus' )
5565 {
5566 $field->defaultValue = 'oa'. bin2hex(openssl_random_pseudo_bytes(5));
5567 }
5568
5569 if ( $field->type == 'checkbox' && $field->inputName == 'tikon' )
5570 {
5571 if( opmem_get_user_tikon_package(get_current_user_id()) )
5572 {
5573 $field->defaultValue = 'Tikonin koulutukset +0€/kk (normaalihinta 29€/kk)';
5574 }
5575 }
5576
5577 }
5578 return $form;
5579} */
5580
5581function opmem_gform_prepopulate_complex_field($field, $mapped_fields)
5582{
5583 $inputs = $field->get_entry_inputs();
5584 if ( is_array( $inputs ) )
5585 {
5586 foreach ( $inputs as &$input )
5587 {
5588 $filter_name = opmem_gform_prepopulate_input( $input['id'], rgar( $mapped_fields, (string) $input['id'] ) );
5589 $field->allowsPrepopulate = true;
5590 $input['name'] = $filter_name;
5591 }
5592 $field->inputs = $inputs;
5593 }
5594 else
5595 {
5596 $value = is_array( rgar( $mapped_fields, $field->id ) ) ? implode( ',', rgar( $mapped_fields, $field->id ) ) : rgar( $mapped_fields, $field->id );
5597 }
5598}
5599
5600function opmem_gform_prepopulate_input( $input_id, $value )
5601{
5602 $filter_name = 'gfur_field_' . str_replace( '.', '_', $input_id );
5603 add_filter( "gform_field_value_{$filter_name}", create_function( "", "return maybe_unserialize('" . str_replace( "'", "\'", maybe_serialize( $value ) ) . "');" ) );
5604 return $filter_name;
5605}
5606
5607add_action("gform_after_submission", "opmem_gform_set_level_order", 107, 2);
5608function opmem_gform_set_level_order($entry, $form)
5609{
5610 if( $form['title'] == 'Tilaus 2017'
5611 || $form['title'] == 'Order 2017' )
5612 {
5613 opcom_save_order($entry, $form);
5614 }
5615}
5616
5617add_action("gform_after_submission", "opmem_gform_set_level_order_admin", 112, 2);
5618function opmem_gform_set_level_order_admin($entry, $form)
5619{
5620 if( $form['title'] == 'Admin Order 2017' )
5621 {
5622 opcom_save_order_admin($entry, $form);
5623 }
5624}
5625
5626add_action("gform_after_submission", "opmem_gform_login_redirect", 1000, 2);
5627function opmem_gform_login_redirect($entry, $form)
5628{
5629 if( $form['title'] == 'Tilaus 2017'
5630 || $form['title'] == 'Order 2017' )
5631 {
5632 $level_with_price = rgar( $entry, '31' );
5633 if(strpos($level_with_price, '|'))
5634 {
5635 $level_array = explode('|', $level_with_price);
5636 $level = $level_array[0];
5637 }
5638 else
5639 {
5640 /* We're probably screwed if it hits this part, but let's try to do what we can */
5641 $level = $level_with_price;
5642 }
5643 login_after_order($entry, $form, $level);
5644 }
5645}
5646
5647add_action("gform_after_submission", "cancel_order", 102, 2);
5648function cancel_order($entry, $form)
5649{
5650 if($form['title'] == 'Peruuta tilaus 2017'
5651 || $form['title'] == 'Cancel order 2017' )
5652 {
5653 opcom_cancel_order();
5654 }
5655}
5656
5657/**
5658 * Process order change and customer info update
5659 */
5660add_action("gform_after_submission", "update_level_order", 105, 2);
5661function update_level_order($entry, $form)
5662{
5663 if( $form['title'] == 'Vaihda tilausta 2017' || $form['title'] == 'Change order 2017' )
5664 {
5665 opcom_update_order($entry, $form);
5666 /* The call above includes pipedrive update */
5667 }
5668 if( $form['title'] == 'Muokkaa asiakastietoja 2017' || $form['title'] == 'Edit customer 2017' )
5669 {
5670 // This should probably use internal functions instead of Gravity Forms User Registration
5671 $userdata = wp_get_current_user();
5672 $user = $userdata->data;
5673 opmem_pipedrive_update_user($user->user_email, true);
5674 }
5675}
5676
5677/**
5678 * Create a user account and a basic order
5679 * @param $userdata array
5680 * @param $package_id Package ID
5681 *
5682 * Userdata array:
5683 * 'user_login' => $user_name, OPTIONAL
5684 * 'user_pass' => $user_password,
5685 * 'user_email' => $email,
5686 * 'first_name' => $user_firstname,
5687 * 'last_name' => $user_lastname,
5688 * 'display_name' => $user_firstname .' '. $user_lastname, OPTIONAL
5689 * 'meta_phone' => $phone_number
5690 */
5691function opmem_create_user_order($userdata, $package_id, $order_status, $discount_percentage = 0, $orderdata = false, $extra = false)
5692{
5693 global $wpdb, $order_metafields, $sql_fields;
5694// Check if package_id is valid
5695// Check if order status is valid
5696
5697 write_log('Creating order');
5698
5699 $phone = $userdata['meta_phone'];
5700 unset($userdata['package_id']);
5701 unset($userdata['order_status']);
5702
5703 if(empty($userdata['user_login']))
5704 {
5705 $userdata['user_login'] = 'oa'. opmem_random_str(10);
5706 }
5707 if(empty($userdata['display_name']))
5708 {
5709 $userdata['display_name'] = $userdata['first_name'] .' '. $userdata['last_name'];
5710 }
5711 if(!empty($userdata['order_enddate']))
5712 {
5713 $enddate = date("Y-m-d 23:59:59", strtotime($userdata['order_enddate']));
5714 unset($userdata['order_enddate']);
5715 }
5716 $userdata_full = $userdata;
5717 foreach($userdata as $key => $val)
5718 {
5719 if(substr($key, 0, 5) == 'meta_')
5720 {
5721 unset($userdata[$key]);
5722 }
5723 }
5724
5725 write_log('Userdata: '. $userdata['display_name'] .' '. $userdata['user_email']);
5726
5727 $user_id = false;
5728 if(get_user_by('email', $userdata['user_email']) === false)
5729 {
5730 $packages = $wpdb->get_results('SELECT '. $sql_fields['package'] .' FROM wpopi_opcom_package ORDER BY upgrade_path', OBJECT_K);
5731
5732 write_log('Trying to create a user');
5733 $user_id = wp_insert_user( $userdata );
5734 if(is_wp_error($user_id))
5735 {
5736 write_log($user_id);
5737 return false;
5738 }
5739
5740 write_log('New user id: '. $user_id);
5741 $user = get_user_by('id', $user_id);
5742
5743 write_log($user);
5744 $user_id = $user->ID;
5745 write_log('Fetched user: '. $user_id);
5746 $level_data = array(
5747 'startdate' => date("Y-m-d 23:59:59"),
5748 'user_id' => $user_id,
5749 'membership_id' => $package_id,
5750 'cycle_period' => 'Month');
5751
5752 if(function_exists('pmpro_changeMembershipLevel'))
5753 {
5754 pmpro_changeMembershipLevel( $level_data, $user_id );
5755 }
5756
5757// MailerLite
5758// Pipedrive
5759
5760 if($orderdata)
5761 {
5762 $order = $orderdata;
5763 $order['user_id'] = $user_id;
5764 }
5765 else
5766 {
5767 $order = array(
5768 'order_status' => $order_status,
5769 'order_identifier' => hash('ripemd160', $userdata['user_email'] .' - '. date("Y-m-d 23:59:59")),
5770 'user_id' => $user_id,
5771 'order_date' => date("Y-m-d 00:00:01"),
5772 'access_date' => date("Y-m-d 00:00:01"),
5773 'billing_period' => 1,
5774 'cancel_delay' => 0,
5775 );
5776 if(isset($enddate))
5777 {
5778 $order['end_date'] = $enddate;
5779 }
5780 }
5781
5782 $package_name = '';
5783 if( !empty($order['single_trial_course_title'])
5784 && !empty($order['single_trial_course_id']) )
5785 {
5786 $package_name = $order['single_trial_course_title']. ' ('. $order['single_trial_course_id'] .')';
5787 unset($order['single_trial_course_title']);
5788 unset($order['single_trial_course_id']);
5789 }
5790 else
5791 {
5792 $package_name = $packages[$package_id]->name;
5793 }
5794
5795 $wpdb->insert('wpopi_opcom_order', $order);
5796 write_log($wpdb->last_error);
5797 $new_order = $wpdb->insert_id;
5798
5799 opmem_save_user_order_meta($user_id, $userdata_full);
5800 write_log('Order inserted');
5801
5802 opcom_log_order('add_order', $order, $user_id, $new_order);
5803
5804 $row_to_insert = array(
5805 'package_id' => $package_id,
5806 'discount_percentage' => 0,
5807 'billing_amount' => $packages[$package_id]->price,
5808 'description' => opmem_create_order_line($userdata['first_name'] .' '. $userdata['last_name'], $package_name),
5809 'tax_percentage' => OPMEM_INVOICE_VAT,
5810 'order_id' => $new_order,
5811 'discount_percentage' => $discount_percentage,
5812 );
5813
5814 $wpdb->insert('wpopi_opcom_order_line', $row_to_insert);
5815 write_log('Creating a new user '. $user_id .' - '. $userdata['user_email']);
5816 write_log($wpdb->last_error);
5817
5818 $log_rows = $row_to_insert;
5819
5820 /* This to be replaced with foreach when we get more extras */
5821
5822 if($extra !== false)
5823 {
5824 $extra_to_insert = array(
5825 'package_id' => 10,
5826 'discount_percentage' => 100,
5827 'billing_amount' => 29,
5828 'description' => $packages[10]->name,
5829 'tax_percentage' => OPMEM_INVOICE_VAT,
5830 'order_id' => $new_order,
5831 );
5832 $wpdb->insert('wpopi_opcom_order_line', $extra_to_insert);
5833 write_log('Adding a Tikon extra');
5834 $log_rows = array_merge($log_rows, $extra_to_insert);
5835 }
5836 opcom_log_order('add_rows', $log_rows, $user_id, $new_order);
5837 return true;
5838 }
5839 else
5840 {
5841 write_log('User found');
5842 write_log("Couldn't create a new user ". $userdata['user_email']);
5843 return false;
5844 }
5845
5846}
5847
5848/**
5849 * Update a user account and a basic order
5850 * @param $userdata array
5851 * @param $package_id Package ID
5852 *
5853 * Userdata array:
5854 * 'user_login' => $user_name, OPTIONAL
5855 * 'user_pass' => $user_password,
5856 * 'user_email' => $email,
5857 * 'first_name' => $user_firstname,
5858 * 'last_name' => $user_lastname,
5859 * 'display_name' => $user_firstname .' '. $user_lastname, OPTIONAL
5860 * 'meta_phone' => $phone_number
5861 */
5862function opmem_update_user_order($userdata, $package_id, $order_status, $options = array())
5863{
5864 global $wpdb, $order_metafields, $sql_fields;
5865// Check if package_id is valid
5866// Check if order status is valid
5867
5868 write_log('Updating order');
5869
5870 $phone = $userdata['meta_phone'];
5871 unset($userdata['package_id']);
5872 unset($userdata['order_status']);
5873
5874 /* if(empty($userdata['user_login']))
5875 {
5876 $userdata['user_login'] = 'oa'. opmem_random_str(10);
5877 } */
5878 if(empty($userdata['display_name']))
5879 {
5880 $userdata['display_name'] = $userdata['first_name'] .' '. $userdata['last_name'];
5881 }
5882 if(!empty($userdata['order_enddate']))
5883 {
5884 $enddate = $userdata['order_enddate']. ' 23:59:59';
5885 unset($userdata['order_enddate']);
5886 write_log('Order end date set: '. $enddate);
5887 }
5888
5889 $userdata_full = $userdata;
5890 foreach($userdata as $key => $val)
5891 {
5892 if(substr($key, 0, 5) == 'meta_')
5893 {
5894 unset($userdata[$key]);
5895 }
5896 }
5897
5898 write_log('Userdata: '. $userdata['display_name'] .' '. $userdata['user_email']);
5899 // write_log($userdata);
5900
5901 $user_id = false;
5902 $user = get_user_by('email', $userdata['user_email']);
5903 if($user !== false)
5904 {
5905 $user_id = $user->ID;
5906 $packages = $wpdb->get_results('SELECT '. $sql_fields['package'] .' FROM wpopi_opcom_package ORDER BY upgrade_path', OBJECT_K);
5907
5908 write_log('Trying to update a user');
5909 // $user_id = wp_insert_user( $userdata );
5910
5911 write_log('Existing user\'s id: '. $user_id);
5912
5913 // write_log($user);
5914 $user_id = $user->ID;
5915 // write_log('Fetched user: '. $user_id);
5916/* $level_data = array(
5917 'startdate' => date("Y-m-d 23:59:59"),
5918 'user_id' => $user_id,
5919 'membership_id' => $package_id,
5920 'cycle_period' => 'Month');
5921
5922 pmpro_changeMembershipLevel( $level_data, $user_id ); */
5923
5924// MailerLite
5925// Pipedrive
5926
5927 opmem_save_user_order_meta($user_id, $userdata_full);
5928
5929 $old_package_array = opmem_get_user_basic_package($user_id, true);
5930
5931
5932 if($old_package_array['package_id'] == $package_id)
5933 {
5934 /* Do not update order if the package is exactly the same */
5935
5936 /* TODO: this is a quick fix! Need to check package statuses, end date etc */
5937 write_log('User had the same package, skipping');
5938
5939 }
5940 elseif(isset($old_package_array['package_id']) && $old_package_array['package_id'] !== false)
5941 {
5942 /* Update when old valid order/package exists */
5943 opcom_log_order('edit_order', $old_package_array, $user_id, $old_package_array['order_id']);
5944 $oldrows = $wpdb->get_results("SELECT ". $sql_fields['order_line'] ."
5945 FROM wpopi_opcom_order_line
5946 WHERE order_id = ". $old_package_array['order_id']);
5947 opcom_log_order('edit_rows', $oldrows, $user_id, $old_package_array['order_id']);
5948
5949 // Not setting any start dates for this presumably existing order
5950 $order = array(
5951 'order_status' => $order_status,
5952 'billing_period' => 1,
5953 'cancel_delay' => 0
5954 );
5955 if($enddate)
5956 {
5957 $order['end_date'] = $enddate;
5958 }
5959
5960 $row_to_insert = array(
5961 'package_id' => $package_id,
5962 'discount_percentage' => 0,
5963 'billing_amount' => $packages[$package_id]->price,
5964 'description' => opmem_create_order_line($userdata['first_name'] .' '. $userdata['last_name'], $packages[$package_id]->name),
5965 'tax_percentage' => OPMEM_INVOICE_VAT,
5966 );
5967
5968 write_log('Fecthed an old order: package_id '. $old_package_array['package_id'] .' - order-id '. $old_package_array['order_id']);
5969
5970 if( $old_package_array['order_status'] == 'success'
5971 || $old_package_array['order_status'] == 'active' )
5972 {
5973 $wpdb->update('wpopi_opcom_order', $order,
5974 array('user_id' => $user_id, 'order_id' => $old_package_array['order_id']));
5975 write_log($wpdb->last_error);
5976 write_log('Order updated');
5977
5978 $wpdb->update('wpopi_opcom_order_line', $row_to_insert,
5979 array('package_id' => $old_package_array['package_id'], 'order_id' => $old_package_array['order_id']));
5980 write_log('Order row updated: package_id '. $row_to_insert['package_id'] .' - description '. $row_to_insert['description'] );
5981 }
5982 else
5983 {
5984 $order['end_date'] = date('Y-m-d 23:59:59');
5985 $order['order_status'] = 'history';
5986 $wpdb->update('wpopi_opcom_order', $order,
5987 array('user_id' => $user_id, 'order_id' => $old_package_array['order_id']));
5988 write_log($wpdb->last_error);
5989 write_log('Expired/cancelled order marked as history');
5990
5991 $order = array(
5992 'order_status' => $order_status,
5993 'order_identifier' => hash('ripemd160', $userdata['user_email'] .' - '. date("Y-m-d 23:59:59")),
5994 'user_id' => $user_id,
5995 'order_date' => date("Y-m-d 00:00:01"),
5996 'access_date' => date("Y-m-d 00:00:01"),
5997 'billing_period' => 1,
5998 'cancel_delay' => 0,
5999 );
6000 if(isset($enddate))
6001 {
6002 $order['end_date'] = $enddate;
6003 }
6004 $wpdb->insert('wpopi_opcom_order', $order);
6005 $new_order = $wpdb->insert_id;
6006 $row_to_insert['order_id'] = $new_order;
6007 $wpdb->insert('wpopi_opcom_order_line', $row_to_insert);
6008
6009 write_log('Order row updated: package_id '. $row_to_insert['package_id'] .' - description '. $row_to_insert['description'] );
6010 }
6011
6012
6013 write_log('Updating user complete: '. $user_id .' - '. $userdata['user_email'] . ' - '. $order_status);
6014 write_log($wpdb->last_error);
6015 }
6016 else
6017 {
6018 $order = array(
6019 'order_status' => $order_status,
6020 'order_identifier' => hash('ripemd160', $userdata['user_email'] .' - '. date("Y-m-d 23:59:59")),
6021 'user_id' => $user_id,
6022 'order_date' => date("Y-m-d 00:00:01"),
6023 'access_date' => date("Y-m-d 00:00:01"),
6024 'billing_period' => 1,
6025 'cancel_delay' => 0,
6026 );
6027 if(isset($enddate))
6028 {
6029 $order['end_date'] = $enddate;
6030 }
6031 $wpdb->insert('wpopi_opcom_order', $order);
6032 $new_order = $wpdb->insert_id;
6033 $row_to_insert = array(
6034 'package_id' => $package_id,
6035 'discount_percentage' => 0,
6036 'billing_amount' => $packages[$package_id]->price,
6037 'description' => opmem_create_order_line($userdata['first_name'] .' '. $userdata['last_name'], $packages[$package_id]->name),
6038 'tax_percentage' => OPMEM_INVOICE_VAT,
6039 'order_id' => $new_order,
6040 'discount_percentage' => $discount_percentage,
6041 );
6042
6043 $wpdb->insert('wpopi_opcom_order_line', $row_to_insert);
6044 write_log('Creating a new order '. $user_id .' - '. $userdata['user_email']);
6045 write_log($wpdb->last_error);
6046
6047 opcom_log_order('add_order', $order, $user_id, $new_order);
6048 opcom_log_order('add_row', $row_to_insert, $user_id, $new_order);
6049 }
6050
6051/*
6052Original
6053 $row_to_insert = array(
6054 'package_id' => $package_id,
6055 'discount_percentage' => 0,
6056 'billing_amount' => 0,
6057 'description' => $userdata['display_name'], // INSERT PACKAGE NAME
6058 'tax_percentage' => '24',
6059 'order_id' => $new_order,
6060 ); */
6061
6062
6063
6064 /* This to be replaced with foreach when we get more extras */
6065
6066 /* if($extra !== false)
6067 {
6068 $extra_to_insert = array(
6069 'package_id' => 10,
6070 'discount_percentage' => 100,
6071 'billing_amount' => 29,
6072 'description' => 'Tikonin koulutukset',
6073 'tax_percentage' => '24',
6074 'order_id' => $new_order,
6075 );
6076 $wpdb->insert('wpopi_opcom_order_line', $extra_to_insert);
6077 write_log('Adding a Tikon extra');
6078 } */
6079
6080 return true;
6081 }
6082 else
6083 {
6084 write_log('User not found for update');
6085 write_log("Couldn't update user ". $userdata['user_email']);
6086 return false;
6087 }
6088
6089}
6090
6091function opmem_save_user_order_meta($user_id, $userdata_full)
6092{
6093 global $order_metafields;
6094 write_log('Writing usermeta');
6095 foreach($userdata_full as $meta_title => $meta_field)
6096 {
6097 if( strpos($meta_title, 'meta_') !== false && $meta_field != '' )
6098 {
6099 update_user_meta( $user_id, str_replace('meta_', '', $meta_title), $meta_field);
6100 write_log( 'Meta written: '. str_replace('meta_', '', $meta_title). ' - '. $meta_field);
6101 }
6102 }
6103}
6104
6105/**
6106 * Generate a random string, using a cryptographically secure
6107 * pseudorandom number generator (random_int) - Straight from Stack Overflow
6108 *
6109 * @param int $length How many characters do we want?
6110 * @param string $keyspace A string of all possible characters
6111 *
6112 * @return string
6113 */
6114function opmem_random_str($length, $keyspace = 'abcdefghijklmnopqrstuvwxyz')
6115{
6116 $str = '';
6117 $max = mb_strlen($keyspace, '8bit') - 1;
6118 for ($i = 0; $i < $length; ++$i) {
6119 $str .= $keyspace[random_int(0, $max)];
6120 }
6121 return $str;
6122}
6123
6124/**
6125 * Trial order for a single free course.
6126 *
6127 * NOTE: Mailerlite info defined elsewhere.
6128 * TODO: Email template to an editable and non-hardcoded one.
6129 */
6130add_action("gform_after_submission", "set_level_trial_single_course", 93, 2);
6131function set_level_trial_single_course($entry, $form)
6132{
6133 if($form['title'] == 'Trial - Free Course')
6134 {
6135 write_log('Trial course: save init');
6136 global $wpdb, $sql_fields;
6137 $packages = $wpdb->get_results('SELECT '. $sql_fields['package'] .' FROM wpopi_opcom_package ORDER BY upgrade_path', OBJECT_K);
6138
6139 $theme = rgar( $entry, '19' );
6140
6141 $email = rgar( $entry, '1' );
6142 $user = get_user_by('email', $email);
6143 if(empty($user))
6144 {
6145 $user_name = rgar( $entry, '7' );
6146 $user_password = rgar( $entry, '9' );
6147 $user_firstname = rgar( $entry, '13.3' );
6148 $user_lastname = rgar( $entry, '13.6' );
6149 // $user_id = wp_create_user( $user_name, $user_password, $email );
6150
6151
6152 /* TODO: should use the function */
6153 $userdata = array(
6154 'user_login' => $user_name,
6155 'user_pass' => $user_password,
6156 'user_email' => $email,
6157 'first_name' => $user_firstname,
6158 'last_name' => $user_lastname,
6159 'display_name' => $user_firstname .' '. $user_lastname,
6160 );
6161
6162 $user_id = wp_insert_user( $userdata );
6163 $user = get_user_by('id', $user_id);
6164
6165 if( !is_wp_error( $user_id ) && !empty($user) )
6166 {
6167 $level = 14;
6168
6169 $user_id = $user->ID;
6170 $level_data = array(
6171 'startdate' => date("Y-m-d 23:59:59"),
6172 'enddate' => date("Y-m-d 23:59:59", time() + 1209600 ),
6173 'user_id' => $user_id,
6174 'membership_id' => $level - 1,
6175 'cycle_period' => 'Month');
6176
6177 if(function_exists("pmpro_changeMembershipLevel"))
6178 {
6179 pmpro_changeMembershipLevel( $level_data, $user_id );
6180 }
6181
6182 // pmpro_changeMembershipLevel($old_level, $user_id);
6183
6184 // Mailerlite --->
6185
6186 $koulutus_valinta = rgar( $entry, '18' );
6187 $koulutus_id = rgar( $entry, '17' );
6188
6189 update_user_meta( $user_id, 'oa_phone', rgar( $entry, '3' ) );
6190 update_user_meta( $user_id, 'oa_company_sector', rgar( $entry, '15' ) );
6191
6192 $order = array(
6193 'order_status' => 'trial',
6194 'order_identifier' => hash('ripemd160', $email .' - '. date("Y-m-d 23:59:59")),
6195 'user_id' => $user_id,
6196 'order_date' => date("Y-m-d 23:59:59"),
6197 'access_date' => date("Y-m-d 23:59:59"),
6198 'end_date' => date("Y-m-d 23:59:59", time() + 1209600 ),
6199 'billing_period' => 1,
6200 'cancel_delay' => 0,
6201 'extra_info' => $koulutus_valinta
6202 );
6203
6204 $wpdb->insert('wpopi_opcom_order', $order);
6205 $new_order = $wpdb->insert_id;
6206
6207 $row_to_insert = array(
6208 'package_id' => $level,
6209 'discount_percentage' => 0,
6210 'billing_amount' => 0,
6211 'description' => 'Koulutus: '. $koulutus_valinta .' ('. $koulutus_id .')',
6212 'tax_percentage' => OPMEM_INVOICE_VAT,
6213 'order_id' => $new_order,
6214 );
6215
6216 $phone = rgar($entry, '3');
6217 $sms_sending_time = date("Y-m-d 15:00", strtotime("+7 days"));
6218 $sms_sending_time = str_replace(' ', '%20', $sms_sending_time);
6219 $sms_message = "Olethan muistanut katsoa valitsemasi Opinahjon ilmaisen koulutuksen? Koulutus on katsottavissa vielä 7 päivää. Saat tehdä myös kurssitestin koulutuksen jälkeen!\nTerveisin Opinahjo\nhttp://opinahjo.fi";
6220
6221 if(!empty($phone))
6222 {
6223 queue_sms_notification($phone, $sms_message, $sms_sending_time);
6224 }
6225
6226 $wpdb->insert('wpopi_opcom_order_line', $row_to_insert);
6227 write_log('Koeajo: no user, created one with id '. $user_id);
6228
6229$message_html =
6230'<p>Hienoa, kun päätit aloittaa ilmaisen kokeilun! Valitsemasi koulutus on käytössäsi seuraavat 2 viikkoa.</p>
6231
6232<p><strong>Tunnuksesi Akatemiaan:</strong>
6233<br />Käyttäjätunnus: '. $email .'
6234<br />Salasana: '. $user_password .'</p>
6235
6236<p>Kirjaudu sisään täältä: <a href="http://opinahjo.fi/login/">opinahjo.fi/login/</a></p>
6237
6238<p><strong>Valitsemasi koulutus:Â </strong><a href="'. get_permalink($koulutus_id) .'">'. $koulutus_valinta .'</a></p>
6239
6240<p><strong>Seuraavaksi:</strong>
6241<br />1) Lataa itsellesi koulutusmateriaali
6242<br />2) Katso tallenne
6243<br />3) Tee kurssitesti ja tulosta itsellesi kurssitodistus
6244<br />4) Koeajosi on valmis</p>
6245
6246<p>Tiesithän, että voit koska tahansa koeajon aikana tehdä tilauksen ja valita pakettisi neljästä eri vaihtoehdosta.
6247Lisätietoja paketeista: <a href="http://opinahjo.fi/paketit">opinahjo.fi/paketit</a></p>
6248
6249<p>Terveisin
6250<br />Opinahjon tiimi</p>';
6251
6252$message_plain =
6253'Hienoa, kun päätit aloittaa ilmaisen kokeilun! Valitsemasi koulutus on käytössäsi seuraavat 2 viikkoa.
6254
6255Tunnuksesi Akatemiaan:
6256Käyttäjätunnus: '. $email .'
6257Salasana: $user_password
6258
6259Kirjaudu sisään täältä:
6260http://opinahjo.fi/login/
6261
6262Valitsemasi koulutus:Â '. $koulutus_valinta .'
6263'. get_permalink($koulutus_id) .'">
6264
6265Seuraavaksi:
62661) Lataa itsellesi koulutusmateriaali
62672) Katso tallenne
62683) Tee kurssitesti ja tulosta itsellesi kurssitodistus
62694) Koeajosi on valmis
6270
6271Tiesithän, että voit koska tahansa koeajon aikana tehdä tilauksen ja valita pakettisi neljästä eri vaihtoehdosta.
6272Lisätietoja paketeista:Â
6273http://opinahjo.fi/paketit
6274
6275Terveisin
6276Opinahjon tiimi';
6277
6278
6279/* TODO: ADD LOGGING (to the individuel functions) */
6280
6281 opcom_phpmailer_send_via_postmark($email, __('Welcome to try [service name]', 'opinahjo-members'), $message_html, $message_plain);
6282
6283 /* Add to mailerlite */
6284 $fields = array('key' => 'courselink', 'value' => get_permalink($koulutus_id));
6285 if(defined( 'OPCOM_MAILERLITE_THEME_WORK' ) && $theme == 'Tasapainota työ ja vapaa-aika')
6286 {
6287 opmem_post_mailerlite($email, $user_firstname, $user_lastname, OPCOM_MAILERLITE_THEME_WORK, $fields);
6288 }
6289 elseif(defined( 'OPCOM_MAILERLITE_TRIAL_SINGLE' ))
6290 {
6291 opmem_post_mailerlite($email, $user_firstname, $user_lastname, OPCOM_MAILERLITE_TRIAL_SINGLE, $fields);
6292 }
6293
6294 opmem_pipedrive_update_user($email);
6295
6296// $course = get_page_by_title( $koulutus_valinta, OBJECT, 'sfwd-courses' );
6297
6298 wp_set_auth_cookie($user_id, false, '');
6299 wp_redirect( get_permalink($koulutus_id) );
6300 exit();
6301
6302 }
6303 else
6304 {
6305 write_log('Koeajo: unknown error');
6306 }
6307
6308 }
6309 else
6310 {
6311 $package = opmem_get_user_basic_package($user->ID, true);
6312 if( isset($package) && !empty($package) )
6313 {
6314 write_log('Koeajo: user exists, has package');
6315 if ( wp_redirect( 'http://' .$_SERVER['HTTP_HOST']. '/rekisteroity/' ) )
6316 {
6317 exit;
6318 }
6319 }
6320 else
6321 {
6322 $usermeta = get_user_meta($user->ID);
6323 $emails = 'heikki@opinahjo.fi, opinahjo@jmg.fi, info@opinahjo.fi';
6324 $subject = 'Käyttäjällä ei oikeutta koeajoon';
6325
6326 $orders = $wpdb->get_results("SELECT ". $sql_fields['order'] ."
6327 FROM wpopi_opcom_order
6328 WHERE user_id = '". $user->ID ."'
6329 ORDER BY order_id DESC", OBJECT);
6330 $previous_order = array(
6331 'Tilauspäivä' => $orders[0]->order_date,
6332 'Peruutuspäivä' => $orders[0]->cancel_date,
6333 'Loppupäivä' => $orders[0]->end_date,
6334 );
6335
6336 $rows = $wpdb->get_results("SELECT ". $sql_fields['order_line'] .", wpopi_opcom_package.name as package_name
6337 FROM wpopi_opcom_order_line, wpopi_opcom_package
6338 WHERE order_id = '". $orders[0]->order_id ."'
6339 AND wpopi_opcom_order_line.package_id IN (2, 6, 9, 1)
6340 AND wpopi_opcom_package.package_id = wpopi_opcom_order_line.package_id");
6341 $previous_order['Paketti'] = $rows[0]->package_name;
6342
6343 $message_html_sales =
6344 '<p>Käyttäjä oli kiinnostunut koeajosta, mutta hänellä jo tunnus järjestelmään.
6345 <br />Tilaus on umpeutunut seuraavasti:</p>
6346
6347 <p>Nimi: '. $user->display_name .'
6348 <br />Email: '. $user->user_email .'
6349 <br />Puhelin: '. $usermeta['oa_phone'][0] .'</p><p>';
6350 foreach($previous_order as $key => $val)
6351 {
6352 $message_html_sales .= $key .': '. $val .'<br />';
6353 }
6354 $message_html_sales .= '</p>';
6355
6356 opcom_phpmailer_send_via_postmark($emails, $subject, $message_html_sales, '');
6357 write_log('Koeajo: user exists, no package');
6358 if ( wp_redirect( 'http://' .$_SERVER['HTTP_HOST']. '/rekisteroity-tarjous/' ) )
6359 {
6360 exit;
6361 }
6362 }
6363
6364 // SEND MAIL TO JMG
6365
6366 }
6367 }
6368}
6369
6370/**
6371 * Shortcode to add a visually pleasing course snippet to the trial form.
6372 *
6373 * TODO: perhaps remove the second paragraph from the custom excerpt.
6374 */
6375function trial_chosen_course()
6376{
6377 $post = trial_get_course_offer();
6378 if(!empty($post))
6379 {
6380 // $thump_id = get_post_thumbnail_id($post->ID);
6381 $thumb_url = get_the_post_thumbnail($post->ID);
6382 $thumb_url = preg_replace('/ width="\d+" height="\d+"/', '', $thumb_url);
6383 return '
6384 <div class="trial_order_heading">'. __('The Course You Chose', 'opinahjo-members') .'</div>
6385 <div>
6386 <div class="trial_order_course_image" style="width: 20%">'. $thumb_url .'</div>
6387 <div class="trial_order_course_text" style="width: 70%">
6388 <h3>'. $post->post_title .'</h3>
6389 <p>'. get_field('lyhyt_kuvaus', $post->ID) .'</p>
6390 <p>
6391 <a href="'. get_permalink($post->ID) .'" target="_blank">'. __('[Link to] Course Page', 'opinahjo-members') .'</a>
6392 </p>
6393 </div>
6394 <div class="guillotine"></div>
6395 </div>
6396 ';
6397 }
6398 else
6399 {
6400 return '<p><br /><strong>'. __('Apologies! We can\'t seem to find this course.', 'opinahjo-members') .'</strong>
6401 <br />'. __('The link you followed might be old or broken.', 'opinahjo-members') .'</p>';
6402 }
6403}
6404add_shortcode('trial_chosen_course', 'trial_chosen_course');
6405
6406/**
6407 * Get the course that's offered on the trial form. Either by GET parameter,
6408 * or the latest one with a recording from the ajankohtaiskatsaukset category.
6409 *
6410 * NOTE: the category needs to be customizable.
6411 */
6412function trial_get_course_offer()
6413{
6414 global $wpdb;
6415 if(isset($_GET['c']) && is_numeric($_GET['c']))
6416 {
6417 $args = array(
6418 'post_type' => 'sfwd-courses',
6419 'p' => $_GET['c'],
6420 'post_status' => 'publish',
6421 'posts_per_page' => '1'
6422 );
6423 }
6424 else
6425 {
6426 $args = array(
6427 'post_type' => 'sfwd-courses',
6428 'post_status' => 'publish',
6429 'posts_per_page' => '1',
6430 'tax_query' => array(
6431 array(
6432 'taxonomy' => 'category',
6433 'field' => 'slug',
6434 'terms' => 'ajankohtaiskatsaukset',
6435 ),
6436 ),
6437 'meta_query' => array(
6438 'relation' => 'AND',
6439 array(
6440 'key' => 'tallenteen_embed',
6441 'compare' => 'EXISTS'
6442 ),
6443 array(
6444 'key' => 'tallenteen_embed',
6445 'value' => '',
6446 'compare' => '!='
6447 )
6448 ),
6449 'orderby' => 'date',
6450 'order' => 'DESC',
6451 );
6452 }
6453 // 'meta_compare' => 'NOT EXISTS',
6454 $post_query = new WP_Query($args);
6455 $post = $post_query->posts[0];
6456 return $post;
6457}
6458
6459/**
6460 * Get all courses that you can order a trial for
6461 * @return Array of query objects
6462 */
6463function trial_get_courses()
6464{
6465 $args = array(
6466 'post_type' => 'sfwd-courses',
6467 'post_status' => 'publish',
6468 'posts_per_page' => '-1',
6469 /* 'tax_query' => array(
6470 array(
6471 'taxonomy' => 'category',
6472 'field' => 'slug',
6473 'terms' => 'ajankohtaiskatsaukset',
6474 ),
6475 ), */
6476 'meta_query' => array(
6477 'relation' => 'AND',
6478 array(
6479 'key' => 'tallenteen_embed',
6480 'compare' => 'EXISTS'
6481 ),
6482 array(
6483 'key' => 'tallenteen_embed',
6484 'value' => '',
6485 'compare' => '!='
6486 ),
6487 array(
6488 'key' => 'tallenteen_voimassaolo',
6489 'value' => date('Ymd'),
6490 'compare' => '>=',
6491 ),
6492 ),
6493 'orderby' => 'date',
6494 'order' => 'DESC',
6495 );
6496
6497 $post_query = new WP_Query($args);
6498 foreach($post_query->posts as $single)
6499 {
6500 $all_courses[$single->ID] = $single->post_title;
6501 }
6502 return $all_courses;
6503}
6504
6505
6506/**
6507 * Get the post info to populate the trial form hidden fields. These are
6508 * crucial for the functionality to work.
6509 */
6510add_filter( 'gform_pre_render', 'trial_chosen_course_populate_id', 43 );
6511add_filter( 'gform_pre_validation', 'trial_chosen_course_populate_id', 43 );
6512add_filter( 'gform_pre_submission_filter', 'trial_chosen_course_populate_id', 43 );
6513add_filter( 'gform_admin_pre_render', 'trial_chosen_course_populate_id', 43 );
6514function trial_chosen_course_populate_id( $form )
6515{
6516 if($form['title'] == 'Trial - Free Course')
6517 {
6518 $post = trial_get_course_offer();
6519 if(!empty($post))
6520 {
6521 foreach ( $form['fields'] as &$field )
6522 {
6523
6524 if ( $field->inputName == 'kurssi_id' )
6525 {
6526 $field->defaultValue = $post->ID;
6527 }
6528
6529 if ( $field->inputName == 'kurssi_nimi' )
6530 {
6531 $field->defaultValue = $post->post_title;
6532 }
6533
6534 }
6535 }
6536 }
6537 return $form;
6538}
6539
6540
6541add_filter( 'gform_pre_render', 'trial_populate_course_dropdown', 87 );
6542add_filter( 'gform_pre_validation', 'trial_populate_course_dropdown', 87 );
6543add_filter( 'gform_pre_submission_filter', 'trial_populate_course_dropdown', 87 );
6544add_filter( 'gform_admin_pre_render', 'trial_populate_course_dropdown', 87 );
6545function trial_populate_course_dropdown( $form )
6546{
6547 if($form['title'] == 'Admin Order 2017')
6548 {
6549 $courses = trial_get_courses();
6550 foreach ( $form['fields'] as $key => &$field )
6551 {
6552 if ( $field->type == 'select' && $field->inputName == 'trial_recordings' )
6553 {
6554 $choices = array();
6555
6556 foreach ( $courses as $id => $text )
6557 {
6558 $choices[] = array( 'text' => $text, 'value' => $id );
6559 }
6560 $field->placeholder = 'Please choose a course';
6561 $field->choices = $choices;
6562 }
6563 }
6564 }
6565 return $form;
6566}
6567
6568function opcom_add_user_form()
6569{
6570 global $wpdb;
6571 $res = $wpdb->get_var("SELECT id FROM wpopi_rg_form WHERE title = 'Admin Order 2017'");
6572 if($res)
6573 {
6574 echo '<div class="wrap" style="max-width: 850px;"><h1>Add user / order</h1>';
6575 echo do_shortcode('[gravityform id="'. $res .'" title="false" description="false"]');
6576 echo '</div>';
6577 }
6578}
6579
6580
6581/**
6582 * Mass Import/Update from CSV
6583 * TODO: More sanity checking on the values.
6584 * TODO: Add options as a form field, and process CSV row options from comma separated string to array
6585 */
6586function opmem_users_mass_import()
6587{
6588 if(current_user_can('manage_options'))
6589 {
6590 echo '<div class="wrap">';
6591
6592 $show_form = true;
6593 if(isset($_POST["Go"]) && "" != $_POST["Go"]
6594 && $_FILES['file_source']['size'] > 0)
6595 {
6596 $csv = array_map('str_getcsv', file($_FILES['file_source']['tmp_name']));
6597 array_walk($csv, function(&$a) use ($csv) {
6598 $a = array_combine($csv[0], $a);
6599 });
6600 array_shift($csv);
6601
6602 write_log('------------------------------');
6603 write_log('- Mass user import requested -');
6604 write_log('------------------------------');
6605
6606 echo '<table>';
6607 echo '<tr><td>Action</td><td>Status</td><td>User</td><td>Package ID</td><td>Order status</td>';
6608 foreach($csv as $user_row)
6609 {
6610 echo '<tr>';
6611 $package_id = $user_row['package_id'];
6612 $order_status = $user_row['order_status'];
6613 $extra_tikon = $user_row['extra_tikon'];
6614 $options = array();
6615 if(!empty($user_row['options']))
6616 {
6617 $options[] = $user_row['options'];
6618 }
6619
6620 // If user exist try to create a new one.
6621 if(get_user_by('email', $user_row['user_email']) === false)
6622 {
6623 $action = 'create';
6624 if(!empty($extra_tikon))
6625 {
6626 $res = opmem_create_user_order($user_row, $package_id, $order_status, 0, false, true);
6627 $action .= ' (with tikon)';
6628 }
6629 else
6630 {
6631 $res = opmem_create_user_order($user_row, $package_id, $order_status);
6632 }
6633 }
6634 else
6635 {
6636 $action = 'update';
6637 $res = opmem_update_user_order($user_row, $package_id, $order_status, $options);
6638 }
6639
6640 if($res === true)
6641 {
6642 echo '<td>'. ucfirst($action) .'</td><td>Success</td><td><a target="_blank" href="/wp-admin/users.php?s='. urlencode($user_row['user_email']). '">'. $user_row['user_email']. '</a></td><td>' .$user_row['package_id'] .'</td><td>'. $user_row['order_status'] .'</td>';
6643 write_log('User '. $action .'d: ' .$user_row['user_email']);
6644 }
6645 elseif($res === false)
6646 {
6647 echo '<td>'. ucfirst($action) .'</td><td>Failure</td><td><a target="_blank" href="/wp-admin/users.php?s='. urlencode($user_row['user_email']). '">'. $user_row['user_email']. '</a></td><td>' .$user_row['package_id'] .'</td><td>'. $user_row['order_status'] .'</td>';
6648 write_log('User '. $action .' failed: ' .$user_row['user_email']);
6649 }
6650 write_log('------------------------------');
6651 echo '</tr>';
6652 }
6653 echo '</table>';
6654 $show_form = false;
6655
6656 }
6657 elseif(isset($_POST["Go"]))
6658 {
6659 echo '<p>Please choose a file</p>';
6660 }
6661
6662 if($show_form)
6663 {
6664 ?>
6665 <h1>User accounts with CSV import</h1>
6666 <p>This feature is very much work in progress. Please use the structure exactly as shown below.
6667 <br />Package field should contain an integer that matches an existing package. Phone is optional.</p>
6668 <p>File structure:<br />
6669 <table>
6670 <tr>
6671 <td>user_email</td><td>first_name</td><td>last_name</td><td>user_pass</td><td>package_id</td><td>order_status</td><td>meta_phone</td><td>order_enddate</td>
6672 </tr>
6673 <tr>
6674 <td>heikki.hyppanen@opinahjo.fi</td><td>Heikki</td><td>Hyppänen</td><td>asdf</td><td>2</td><td>trial</td><td>0441234567</td><td></td>
6675 </tr>
6676 <tr>
6677 <td>totte.partanen@opinahjo.fi</td><td>Totte</td><td>Partanen</td><td>qwerty</td><td>6</td><td>active</td><td>04098765432</td><td>2017-06-01</td>
6678 </tr>
6679 </table> </p>
6680
6681 <div class="wrap">
6682 <form method="post" enctype="multipart/form-data">
6683
6684 <p>Source CSV file
6685 <br /><input type="file" name="file_source" id="file_source" class="edt" value="" /></p>
6686
6687 <br /><input type="Submit" class="button-primary" name="Go" value="Import" />
6688 </form>
6689 </div>
6690 <?php
6691
6692 }
6693 echo '</div>';
6694 }
6695}
6696
6697/**
6698 * Potentially temporary structure ahead.
6699 */
6700function opcom_user_profile_course_list( $user )
6701{
6702 if ( !current_user_can( 'edit_users' ) ) {
6703 return '';
6704 }
6705 $network_metas = opcom_get_user_course_enroll_metas($user->ID);
6706 $quiz_attempts = opcom_get_quiz_attempts($user->ID);
6707 $opcom_quizzes = opcom_get_coma_multisite_quiz_scores($user->ID);
6708 $user_courses = opcom_get_user_courses($user->ID);
6709
6710
6711if($_GET['show_user_quizzes'] == 1)
6712{
6713 print_r($quiz_attempts);
6714 echo '<br /><br />';
6715 print_r($opcom_quizzes);
6716}
6717
6718// print_r(opcom_coma_new_scores($user));
6719// print_r($quiz_attempts);
6720 ?>
6721 <div class="wrap">
6722 <?php
6723 if(!function_exists('switch_to_blog'))
6724 {
6725 echo '<p>Please note: this doesn\'t seem to be a network site. Course list is not accurate.</p>';
6726 }
6727 echo '<p>Please note: the list only includes Coma results for site #1.</p>';
6728 ?>
6729 <table class="wp-list-table widefat striped">
6730 <thead>
6731 <tr>
6732 <th>Course</th>
6733 <th>Enroll date</th>
6734 <th>Course format</th>
6735 <th>Progress</th>
6736 </tr>
6737 </thead>
6738 <tbody>
6739 <?php
6740
6741 foreach($user_courses as $title => $site_course_id)
6742 {
6743 $status = 'Pending';
6744 if(isset($quiz_attempts[$site_course_id]))
6745 {
6746 foreach($quiz_attempts[$site_course_id] as $attempt)
6747 {
6748 if($attempt['pass'] == 1)
6749 {
6750 $compare_pass = date('Y-m-d', $attempt['time']);
6751 $status = 'Completed on '. date('Y-m-d', $attempt['time']);
6752 }
6753 }
6754 }
6755 if(isset($opcom_quizzes[$site_course_id]))
6756 {
6757 if($opcom_quizzes[$site_course_id]['status'] == 'passed')
6758 {
6759 $compare_pass = $opcom_quizzes[$site_course_id]['date'];
6760 $status = 'Completed on '. $opcom_quizzes[$site_course_id]['date'];
6761 }
6762 }
6763 $date = 'n/a';
6764 $type = 'n/a';
6765 if($network_metas[$site_course_id])
6766 {
6767 $compare_enroll = date('Y-m-d', strtotime($network_metas[$site_course_id]['date']. ' 23:59:59'));
6768 $date = $network_metas[$site_course_id]['date'];
6769 $type = $network_metas[$site_course_id]['type'];
6770 }
6771 if($compare_enroll > $compare_pass)
6772 {
6773 $date = 'n/a';
6774 }
6775
6776 echo '<tr>';
6777 echo '<td>'. str_replace(array('-z-5', '-zz-11'), '', $title) .'</td>';
6778 echo '<td>'. $date .'</td>';
6779 echo '<td>'. $type .'</td>';
6780 echo '<td>'. $status .'</td>';
6781 echo '</tr>';
6782 }
6783
6784 ?>
6785 </tbody>
6786 </table>
6787 </div>
6788 <?php
6789}
6790// add_action( 'show_user_profile', 'learndash_delete_user_data_link', 1000, 1 );
6791add_action( 'edit_user_profile', 'opcom_user_profile_course_list', 997, 1 );
6792
6793
6794function opcom_get_user_course_enroll_metas($user_id)
6795{
6796 global $wpdb;
6797 $network_metas = array();
6798 $metas = $wpdb->get_results("SELECT * FROM wpopi_usermeta WHERE
6799 user_id = ". $user_id ." AND
6800 (meta_key LIKE 'network_course_sub_for_%'
6801 OR meta_key LIKE 'network_recording_sub_for_%'
6802 OR meta_key LIKE 'course_%_access_from')");
6803
6804 // echo $wpdb->last_error;
6805 foreach($metas as $row)
6806 {
6807 // print_r($row);
6808 if(preg_match('/network_recording_sub_for_(\d+)_(\d+)_rec/', $row->meta_key, $matches1))
6809 {
6810 $network_metas[$matches1[1].'-'.$matches1[2]] = array(
6811 'date' => date('d.m.Y', strtotime($row->meta_value)),
6812 'type' => 'recording'
6813 );
6814
6815 }
6816 elseif(preg_match('/network_course_sub_for_(\d+)_(\d+)_rec_(\d+)/', $row->meta_key, $matches2))
6817 {
6818 $network_metas[$matches2[1].'-'.$matches2[2]] = array(
6819 'date' => date('d.m.Y', $matches2[3]),
6820 'type' => 'webinar'
6821 );
6822 }
6823 elseif(preg_match('/course_(\d+)_access_from/', $row->meta_key, $matches3))
6824 {
6825 $sites = array(11, 5, 1);
6826 foreach($sites as $site)
6827 {
6828 $network_metas[$site.'-'.$matches3[1]] = array(
6829 'date' => date('d.m.Y', $row->meta_value),
6830 'type' => 'n/a'
6831 );
6832 }
6833 }
6834 }
6835 return $network_metas;
6836}
6837
6838/**
6839 * Get LD quiz attempts. WORK IN PROGRESS, should rely on user metas more than fetching from sites.
6840 *
6841 */
6842function opcom_get_quiz_attempts($user_id)
6843{
6844 $usermeta = get_user_meta( $user_id, '_sfwd-quizzes', true );
6845
6846 global $wpdb;
6847
6848 $quiz_post_ids = $wpdb->get_results("SELECT * FROM wpopi_opcom_quiz_course");
6849 $quiz_post = array();
6850 foreach($quiz_post_ids as $res)
6851 {
6852 $quiz_post[$res->quiz_id] = array( 'site_id' => $res->site_id, 'course_id' => $res->course_id );
6853 }
6854 $quiz_attempts_meta = empty($usermeta) ? false : $usermeta;
6855 $quiz_attempts = array();
6856 if(!empty($quiz_attempts_meta))
6857 {
6858 foreach($quiz_attempts_meta as $quiz_attempt)
6859 {
6860 // getting the site/post ID
6861 if(isset($quiz_post[$quiz_attempt['quiz']]))
6862 {
6863 write_log('Found quiz/course from opcom table');
6864 $site_post_ids = $quiz_post[$quiz_attempt['quiz']];
6865 }
6866 else
6867 {
6868 $site_post_ids = opinahjo_find_quiz($quiz_attempt['quiz']);
6869 }
6870
6871 if($site_post_ids['site_id'] != 1 && function_exists('switch_to_blog'))
6872 {
6873 switch_to_blog($site_post_ids['site_id']);
6874 }
6875
6876 $c = learndash_certificate_details($quiz_attempt['quiz'], $user_id);
6877 $quiz_attempt['post'] = get_post($quiz_attempt['quiz']);
6878 $quiz_attempt["percentage"] = !empty($quiz_attempt["percentage"])? $quiz_attempt["percentage"]:(!empty($quiz_attempt["count"])? $quiz_attempt["score"]*100/$quiz_attempt["count"]:0 );
6879 $cert_threshold = $c["certificate_threshold"] * 100;
6880 if(!empty($c["certificateLink"])
6881 && (isset($quiz_attempt['percentage'])
6882 && ($quiz_attempt['percentage'] >= $cert_threshold)))
6883 {
6884 $quiz_attempt['certificate'] = $c;
6885 }
6886 $quiz_attempt['course_id'] = $site_post_ids['course_id'];
6887
6888 $quiz_attempts[$site_post_ids['site_id'] .'-'. $site_post_ids['course_id']][] = $quiz_attempt;
6889
6890 if($site_post_ids['site_id'] != 1 && function_exists('switch_to_blog'))
6891 {
6892 restore_current_blog();
6893 }
6894 write_log('site_id: '. $site_post_ids['site_id'] .' - course_id:'. $site_post_ids['course_id']);
6895 }
6896 }
6897 return $quiz_attempts;
6898}
6899
6900function opcom_get_user_courses($user_id)
6901{
6902 $user_courses_pre = ld_get_mycourses($user_id);
6903 $site_courses = array();
6904
6905 foreach ($user_courses_pre as $course_sort_id)
6906 {
6907 $post_pre = get_post($course_sort_id);
6908 $user_courses[$post_pre->post_title] = '1-'.$course_sort_id;
6909 $site_courses[$course_sort_id] = 1;
6910 }
6911
6912 if ( opmem_get_user_tikon_package($user_id) !== false && function_exists('switch_to_blog') )
6913 {
6914 $user_courses_ext = array();
6915 switch_to_blog(5);
6916 $user_courses_ext = ld_get_mycourses($user_id);
6917 if($user_courses_ext)
6918 {
6919 foreach($user_courses_ext as $course_id_ext)
6920 {
6921 $post = get_post($course_id_ext);
6922 $user_courses[$post->post_title.'-z-5'] = '5-'.$course_id_ext;
6923 $site_courses[$course_id_ext] = 5;
6924 }
6925 }
6926 restore_current_blog();
6927 }
6928
6929 if( opcom_is_accountor_user() && function_exists('switch_to_blog') )
6930 {
6931 switch_to_blog(11);
6932 $user_courses_ext2 = ld_get_mycourses($user_id);
6933 if($user_courses_ext2)
6934 {
6935 foreach($user_courses_ext2 as $course_id_ext)
6936 {
6937 $post = get_post($course_id_ext);
6938 $user_courses[$post->post_title.'-zz-11'] = '11-'.$course_id_ext;
6939 $site_courses[$course_id_ext] = 11;
6940 }
6941 }
6942 restore_current_blog();
6943 }
6944
6945 if($user_courses !== null)
6946 {
6947 ksort($user_courses);
6948 }
6949 return $user_courses;
6950}
6951
6952/**
6953 * Gets quiz information for all sites. This is basically an ugly hack.
6954 * Stores results for a user for half an hour in order to not hammer Coma constantly.
6955 */
6956function opcom_get_coma_multisite_quiz_scores($user_id, $sites = array(11, 5, 1))
6957{
6958 $results = get_transient( 'coma_network_scores_for_'. $user_id );
6959 if($results === false)
6960 {
6961 write_log('Polling Coma for results in '. count($sites) .' sites');
6962 $results = array();
6963 foreach($sites as $site)
6964 {
6965 $res = array();
6966 $res = opcom_get_coma_quiz_scores($user_id, $site);
6967 $results = array_merge($results, $res);
6968 }
6969 $results = set_transient( 'coma_network_scores_for_'. $user_id, $results, 2 * HOUR_IN_SECONDS );
6970 }
6971 else
6972 {
6973 write_log('Found transient: Coma network scores for '. $user_id);
6974 }
6975 return $results;
6976}
6977
6978/**
6979 * Fetch quiz information from COMA
6980 */
6981function opcom_get_coma_quiz_scores($user_id, $site = 1)
6982{
6983 $cu = get_user_by('id', $user_id);
6984 $email = $cu->data->user_email;
6985 $hash = md5(COCO_API_KEY.$cu->data->user_email);
6986 $url = COCO_URL."service/scores/$email/$hash"."_site_".COCO_WP_INSTANCE.$site;
6987 $f = file_get_contents($url); // REST GET made easy
6988 if (gettype($f) != "string") return array(); // no error processing at this point
6989 $res = json_decode($f,true);
6990 if ($res == null) return array();
6991 $out = array();
6992 for ($i=0; $i<sizeof($res); $i++) {
6993 if ($res[$i]["status"] == "passed") { // we are only interested in passed quiz attempts
6994 $res[$i]["results"] = json_decode($res[$i]["results"],true);
6995 $res[$i]["cert_details"] = json_decode($res[$i]["cert_details"],true);
6996 if (array_key_exists("post_id",$res[$i]["cert_details"]) && (strlen($res[$i]["cert_details"]["post_id"]) > 1))
6997 $out[$res[$i]["cert_details"]["post_id"]] = $res[$i]; // we index output array with post_id:s
6998 }
6999 }
7000 return $out;
7001}
7002
7003/**
7004 * This rather ludicrous contraption tries to find courses for quizzes.
7005 * Unfortunately this data has not been saved in a consistent way.
7006 */
7007function opinahjo_find_quiz($quiz_id)
7008{
7009 write_log('Searching for course that matches the quiz '. $quiz_id);
7010 $sites = array(11, 5, 1);
7011 foreach($sites as $site)
7012 {
7013 write_log('Searching site '.$site);
7014 /* metas */
7015 $course_id = opinahjo_quiz_to_post($site, $quiz_id);
7016 if($course_id)
7017 {
7018 write_log('Found a course: '. $course_id);
7019 return array('site_id' => $site, 'course_id' => $course_id);
7020 }
7021 }
7022}
7023
7024function opinahjo_quiz_to_post($site_id, $quiz_id)
7025{
7026 global $wpdb;
7027 /* $replace = array(' - Kurssitesti', ' -Kurssitesti', ' – Kurssitesti', ' –Kurssitesti',
7028 '-kurssitesti', ' -kurssitesti'); */
7029
7030 $replace = '/(–|-)( |)(K|k)(urssitesti|urssitodistus)/';
7031
7032 if($site_id != 1)
7033 {
7034 $table = 'wpopi_'. $site_id .'_posts';
7035 $meta_table = 'wpopi_'. $site_id .'_postmeta';
7036 }
7037 else
7038 {
7039 $table = 'wpopi_posts';
7040 $meta_table = 'wpopi_postmeta';
7041 }
7042
7043 // SELECT meta_value FROM wpopi_postmeta WHERE post_id = 14444 AND meta_key = 'course_id'
7044 $quiz_meta_sql = "SELECT meta_value FROM ". $meta_table ."
7045 WHERE post_id = ". $quiz_id ." AND meta_key = 'course_id'";
7046 $quiz_meta = $wpdb->get_var($quiz_meta_sql);
7047
7048 if(!empty($quiz_meta))
7049 {
7050 write_log('Found meta course_id '. $quiz_meta .' for: site '. $site_id .' - quiz '. $quiz_id);
7051 // storing this info for quicker access
7052 $exists = $wpdb->get_var("SELECT quiz_id FROM wpopi_opcom_quiz_course
7053 WHERE course_id = ". $quiz_meta ." AND site_id = ". $site_id);
7054 if(empty($exists))
7055 {
7056 $wpdb->insert('wpopi_opcom_quiz_course', array('course_id' => $quiz_meta, 'site_id' => $site_id, 'quiz_id' => $quiz_id ));
7057 write_log('Saving quiz/course for future reference');
7058 }
7059 return $quiz_meta;
7060 }
7061
7062 $quiz_title_sql = "SELECT post_title FROM ". $table ."
7063
7064 WHERE ID = ". $quiz_id ." AND post_type LIKE 'sfwd-quiz'";
7065 $quiz_title = $wpdb->get_var($quiz_title_sql);
7066
7067 if(!empty($quiz_title))
7068 {
7069 $quiz_title = trim(preg_replace($replace, '', $quiz_title));
7070 $post_sql = "SELECT ID FROM ". $table ."
7071 WHERE post_title LIKE '". $quiz_title ."' AND post_status = 'publish' AND post_type LIKE 'sfwd-courses'";
7072 $post_id = $wpdb->get_var($post_sql);
7073
7074 write_log('Course title: '. $quiz_title .' - '. $post_id);
7075
7076 $exists2 = $wpdb->get_var("SELECT quiz_id FROM wpopi_opcom_quiz_course
7077 WHERE course_id = ". $post_id ." AND site_id = ". $site_id);
7078 if(empty($exists2))
7079 {
7080 $wpdb->insert('wpopi_opcom_quiz_course', array('course_id' => $post_id, 'site_id' => $site_id, 'quiz_id' => $quiz_id ));
7081 write_log('Saving quiz/course for future reference');
7082 }
7083 /* $sql = "SELECT post_id FROM ". $table ." WHERE meta_key = 'course_id'
7084 AND meta_value = ". $quiz_id ." AND post_id = ID AND post_type = 'sfwd-courses'";
7085 write_log($sql);
7086 $query = $wpdb->get_var($sql);
7087 write_log($query); */
7088 return $post_id;
7089 }
7090
7091}
7092
7093
7094/**
7095 * MAILERLITE add to group (mailing list)
7096 * Group SHOULD be defined. The default value is there because of possible old calls to this function.
7097 *
7098 * @param $custom_fields Exactly one pair of 'key' => $key, 'value' => $value. Could not get multiples to work.
7099 */
7100
7101 function opmem_post_mailerlite($email, $firstname, $lastname, $group = '5627463', $custom_fields = array('key' => '', 'value' => ''))
7102 {
7103 if ( defined('OPCOM_MAILERLITE_SECRET' ) )
7104 {
7105 $groupsApi = (new \MailerLiteApi\MailerLite(OPCOM_MAILERLITE_SECRET))->groups();
7106
7107 $subscriber = [
7108 'email' => $email,
7109 'name' => $firstname,
7110 'fields' => [
7111 'last_name' => $lastname,
7112 $custom_fields['key'] => $custom_fields['value']
7113 ]
7114 ];
7115
7116 $response = $groupsApi->addSubscriber($group, $subscriber);
7117 $response1_1 = $groupsApi->addSubscriber(OPCOM_MAILERLITE_NEW_ORDER_ARTICLES, $subscriber);
7118
7119 write_log($subscriber);
7120
7121 write_log($response);
7122 }
7123 }
7124
7125function opmem_post_mailerlite_new_order($email, $firstname, $lastname, $tikon_user)
7126{
7127 if ( defined('OPCOM_MAILERLITE_SECRET' ) )
7128 {
7129 $groupsApi = (new \MailerLiteApi\MailerLite(OPCOM_MAILERLITE_SECRET))->groups();
7130
7131 $subscriber = [
7132 'email' => $email,
7133 'fields' => [
7134 'name' => $firstname,
7135 'last_name' => $lastname
7136 ]
7137 ];
7138
7139 $response = $groupsApi->addSubscriber(OPCOM_MAILERLITE_NEW_ORDER, $subscriber);
7140 // Opinahjo artikkelit talks / Opinahjo articles talks (GroupID - 4585865)
7141 $response1_1 = $groupsApi->addSubscriber(OPCOM_MAILERLITE_NEW_ORDER_ARTICLES, $subscriber);
7142
7143
7144
7145 // Tikon-käyttäjä
7146 if($tikon_user == true && defined('OPCOM_MAILERLITE_NEW_ORDER_TIKON'))
7147 {
7148 $subscriber_tikon = [
7149 'email' => $email,
7150 'fields' => [
7151 'name' => $firstname,
7152 'last_name' => $lastname
7153 ]
7154 ];
7155 // Opinahjo koulutuspaketin tilaajat Tikon / Opinahjo subscribers Tikon (GroupID - 4510031)
7156 $response2 = $groupsApi->addSubscriber(OPCOM_MAILERLITE_NEW_ORDER_TIKON, $subscriber_tikon);
7157 }
7158
7159 // Accountor-käyttäjä
7160 if (filter_var($email, FILTER_VALIDATE_EMAIL) && defined('OPCOM_MAILERLITE_NEW_ORDER_ACCOUNTOR'))
7161 {
7162 $explodedEmail = explode('@', $email);
7163 $domain = array_pop($explodedEmail);
7164 $allowed = array('accountor.fi');
7165 // $allowed = array('opinahjo.fi');
7166
7167 if ( in_array($domain, $allowed) )
7168 {
7169 $subscriber_accountor = [
7170 'email' => $email,
7171 'fields' => [
7172 'name' => $firstname,
7173 'last_name' => $lastname
7174 ]
7175 ];
7176
7177 $response3 = $groupsApi->addSubscriber(OPCOM_MAILERLITE_NEW_ORDER_ACCOUNTOR, $subscriber_accountor); // Opinahjo koulutuspaketin tilaajat Accountor / Opinahjo subscribers Accountor (GroupID - 4509915)
7178
7179 $accontor_user = true;
7180 }
7181 else
7182 {
7183 $accontor_user = false;
7184 }
7185 }
7186
7187 // Muut käyttäjät
7188 if ($tikon_user == false && $accountor_user == false && defined('OPCOM_MAILERLITE_NEW_ORDER_OTHER'))
7189 {
7190 $subscriber_other = [
7191 'email' => $email,
7192 'fields' => [
7193 'name' => $firstname,
7194 'last_name' => $lastname
7195 ]
7196 ];
7197 // Opinahjo koulutuspaketin tilaajat / Opinahjo subscribers (GroupID - 4510017)
7198 $response4 = $groupsApi->addSubscriber(OPCOM_MAILERLITE_NEW_ORDER_OTHER, $subscriber_other);
7199 }
7200
7201 // Tarkistetaan entiset ei-tilaajat ja prospektit
7202 $subscribersApi = (new \MailerLiteApi\MailerLite(OPCOM_MAILERLITE_SECRET))->subscribers();
7203
7204 $subscriberEmail = $email;
7205 $subscriber_info = $subscribersApi->find($subscriberEmail); // returns object of subscriber by its email
7206 $subscriberID = $subscriber_info->id;
7207 $subscriberGroups = $subscribersApi->getGroups($subscriberEmail); // returns array of group objects subscriber belongs to
7208 $groups = array();
7209
7210 foreach ($subscriberGroups as $group)
7211 {
7212 $groupID = $group->id;
7213 $groups[] = $groupID;
7214 }
7215
7216 if(defined('OPCOM_MAILERLITE_NO_ORDER') && in_array(OPCOM_MAILERLITE_NO_ORDER, $groups))
7217 {
7218 $groupsApi->removeSubscriber(OPCOM_MAILERLITE_NO_ORDER, $subscriberID);
7219 }
7220
7221 // Akatemian tilauksen peruuttanut (GroupID - 5649029)
7222 if (defined('OPCOM_MAILERLITE_CANCELLED_ORDER') && in_array(OPCOM_MAILERLITE_CANCELLED_ORDER, $groups))
7223 {
7224 $groupsApi->removeSubscriber(OPCOM_MAILERLITE_CANCELLED_ORDER, $subscriberID);
7225 }
7226
7227 // Opinahjo asiakasrekisteri / Opinahjo prospects (GroupID - 4494611)
7228 if (defined('OPCOM_MAILERLITE_PROSPECTS') && in_array(OPCOM_MAILERLITE_PROSPECTS, $groups))
7229 {
7230 $groupsApi->removeSubscriber(OPCOM_MAILERLITE_PROSPECTS, $subscriberID);
7231 }
7232
7233 /* if(!empty($custom_fields) && is_array($custom_fields))
7234 {
7235 foreach($custom_fields as $field => $val)
7236 {
7237 write_log('Custom field to MailerLite API call: '. $field .' -> '. $val);
7238 $subscriber['fields'][$field] = $val;
7239 }
7240 } */
7241 write_log($subscriber);
7242
7243 // $response = $groupsApi->addSubscriber($groupID, $subscriber);
7244 write_log($response);
7245 }
7246}
7247
7248function opmem_post_mailerlite_change($email, $firstname, $lastname, $tikon_user)
7249{
7250 if ( defined('OPCOM_MAILERLITE_SECRET' ) )
7251 {
7252 // Tarkistetaan, millä listoilla käyttäjä on
7253 $subscribersApi = (new \MailerLiteApi\MailerLite(OPCOM_MAILERLITE_SECRET))->subscribers();
7254 $subscriberEmail = $email;
7255 $subscriber_info = $subscribersApi->find($subscriberEmail); // returns object of subscriber by its email
7256 $subscriberID = $subscriber_info->id;
7257 $subscriberGroups = $subscribersApi->getGroups($subscriberEmail); // returns array of group objects subscriber belongs to
7258 $groupsApi = (new \MailerLiteApi\MailerLite(OPCOM_MAILERLITE_SECRET))->groups();
7259 $groups = array();
7260
7261 foreach ($subscriberGroups as $group)
7262 {
7263 $groupID = $group->id;
7264 $groups[] = $groupID;
7265 }
7266
7267 // Jos käyttäjä ottaa Tikon-paketin eikä ole vielä Tikon asiakas
7268 if(defined('OPCOM_MAILERLITE_NEW_ORDER_TIKON'))
7269 {
7270 if ($tikon_user == true && (!in_array(OPCOM_MAILERLITE_NEW_ORDER_TIKON, $groups)))
7271 {
7272 $subscriber_tikon = [
7273 'email' => $email,
7274 'fields' => [
7275 'name' => $firstname,
7276 'last_name' => $lastname
7277 ]
7278 ];
7279 $response = $groupsApi->addSubscriber(OPCOM_MAILERLITE_NEW_ORDER_TIKON, $subscriber_tikon); // Opinahjo koulutuspaketin tilaajat Tikon / Opinahjo subscribers Tikon (GroupID - 4510031)
7280 }
7281 }
7282
7283 // Jos käyttäjä ei valitse Tikonia, mutta on aiemmin ollut Tikon-käyttäjä
7284 if(defined('OPCOM_MAILERLITE_NEW_ORDER_TIKON'))
7285 {
7286 if ($tikon_user == false && (in_array(OPCOM_MAILERLITE_NEW_ORDER_TIKON, $groups)))
7287 {
7288 $groupsApi->removeSubscriber(OPCOM_MAILERLITE_NEW_ORDER_TIKON, $subscriberID);
7289
7290 if (!in_array(OPCOM_MAILERLITE_NEW_ORDER_ACCOUNTOR, $groups)) // Jos ei Accountor-käyttäjä, lisätään muut käyttäjät-listalle
7291 {
7292 $subscriber_other = [
7293 'email' => $email,
7294 'fields' => [
7295 'name' => $firstname,
7296 'last_name' => $lastname
7297 ]
7298 ];
7299 $response4 = $groupsApi->addSubscriber(OPCOM_MAILERLITE_NEW_ORDER_OTHER, $subscriber_other); // Opinahjo koulutuspaketin tilaajat / Opinahjo subscribers (GroupID - 4510017)
7300 }
7301 }
7302 }
7303
7304 // Jos käyttäjä valitsee Tikon-paketin, poistetaan muut käyttäjät-listalta
7305 if ($tikon_user == true && (in_array(OPCOM_MAILERLITE_NEW_ORDER_OTHER, $groups))) //Opinahjo koulutuspaketin tilaajat / Opinahjo subscribers (GroupID - 4510017)
7306 {
7307 $groupsApi->removeSubscriber(OPCOM_MAILERLITE_NEW_ORDER_OTHER, $subscriberID);
7308 }
7309
7310 // Poistetaan tilauksen aloittaneista
7311 if (in_array(OPCOM_MAILERLITE_NEW_ORDER, $groups)) // Akatemian tilauksen aloittanut (GroupID - 5627463)
7312 {
7313 $groupsApi->removeSubscriber(OPCOM_MAILERLITE_NEW_ORDER, $subscriberID);
7314 }
7315
7316 // Lisätään Akatemian tilauksen vaihtanut-listalle
7317 $subscriber = [
7318 'email' => $email,
7319 'fields' => [
7320 'name' => $firstname,
7321 'last_name' => $lastname
7322 ]
7323 ];
7324 $response = $groupsApi->addSubscriber(OPCOM_MAILERLITE_CHANGED_ORDER, $subscriber); // Akatemian tilauksen vaihtanut (GroupID - 5834947)
7325 }
7326}
7327
7328// Mailerlite tilauksen peruutus
7329function opmem_post_mailerlite_cancel($email, $firstname, $lastname)
7330{
7331 if ( defined('OPCOM_MAILERLITE_SECRET' ) )
7332 {
7333 // Tarkistetaan, millä listoilla käyttäjä on
7334 $subscribersApi = (new \MailerLiteApi\MailerLite(OPCOM_MAILERLITE_SECRET))->subscribers();
7335 $subscriberEmail = $email;
7336 $subscriber = $subscribersApi->find($subscriberEmail); // returns object of subscriber by its email
7337 $subscriberID = $subscriber->id;
7338 $subscriberGroups = $subscribersApi->getGroups($subscriberEmail); // returns array of group objects subscriber belongs to
7339 $groupsApi = (new \MailerLiteApi\MailerLite(OPCOM_MAILERLITE_SECRET))->groups();
7340 $groups = array();
7341
7342 foreach ($subscriberGroups as $group)
7343 {
7344 $groupID = $group->id;
7345 $groups[] = $groupID;
7346 }
7347
7348 // Poistetaan käyttäjä listoilta
7349 if(defined('OPCOM_MAILERLITE_NEW_ORDER_TIKON'))
7350 {
7351 if (in_array(OPCOM_MAILERLITE_NEW_ORDER_TIKON, $groups)) //Opinahjo koulutuspaketin tilaajat Tikon / Opinahjo subscribers Tikon (GroupID - 4510031)
7352 {
7353 $groupsApi->removeSubscriber(OPCOM_MAILERLITE_NEW_ORDER_TIKON, $subscriberID);
7354 }
7355 }
7356
7357 if(defined('OPCOM_MAILERLITE_NEW_ORDER_ACCOUNTOR'))
7358 {
7359 if (in_array(OPCOM_MAILERLITE_NEW_ORDER_ACCOUNTOR, $groups)) //Opinahjo koulutuspaketin tilaajat Accountor / Opinahjo subscribers Accountor (GroupID - 4509915)
7360 {
7361 $groupsApi->removeSubscriber(OPCOM_MAILERLITE_NEW_ORDER_ACCOUNTOR, $subscriberID);
7362 }
7363 }
7364
7365 if (in_array(OPCOM_MAILERLITE_NEW_ORDER_OTHER, $groups)) //Opinahjo koulutuspaketin tilaajat / Opinahjo subscribers (GroupID - 4510017)
7366 {
7367 $groupsApi->removeSubscriber(OPCOM_MAILERLITE_NEW_ORDER_OTHER, $subscriberID);
7368 }
7369
7370 if (in_array(OPCOM_MAILERLITE_CHANGED_ORDER, $groups)) // Akatemian tilauksen vaihtanut (GroupID - 5834947)
7371 {
7372 $groupsApi->removeSubscriber(OPCOM_MAILERLITE_CHANGED_ORDER, $subscriberID);
7373 }
7374
7375 if (in_array(OPCOM_MAILERLITE_NEW_ORDER, $groups)) // Akatemian tilauksen aloittanut (GroupID - 5627463)
7376 {
7377 $groupsApi->removeSubscriber(OPCOM_MAILERLITE_NEW_ORDER, $subscriberID);
7378 }
7379
7380 // Lisätään ei-tilaaja-listoille
7381 $subscriber = [
7382 'email' => $email,
7383 'fields' => [
7384 'name' => $firstname,
7385 'last_name' => $lastname
7386 ]
7387 ];
7388
7389 $response = $groupsApi->addSubscriber(OPCOM_MAILERLITE_NO_ORDER, $subscriber); //Opinahjo ei voimassa olevaa tilausta / Opinahjo no subscribtion (GroupID - 4494625)
7390 $response = $groupsApi->addSubscriber(OPCOM_MAILERLITE_CANCELLED_ORDER, $subscriber); //Akatemian tilauksen peruuttanut (GroupID - 5649029)
7391 }
7392}
7393
7394
7395/**
7396 * List OPS courses. NOTE: this is work-in-progress.
7397 */
7398function opcom_studyplan_list()
7399{
7400 if( current_user_can( 'manage_options' ) )
7401 {
7402 error_reporting(1);
7403 global $wpdb;
7404
7405 if(isset($_GET['mailto']))
7406 {
7407 $single_user_page = true;
7408 }
7409 else
7410 {
7411 $single_user_page = false;
7412 }
7413 if(isset($_GET['send']))
7414 {
7415 $single_user_mailto = true;
7416 }
7417 else
7418 {
7419 $single_user_mailto = false;
7420 }
7421
7422 $names_only = false;
7423 if(isset($_GET['namesonly']))
7424 {
7425 $names_only = true;
7426 }
7427
7428 $compare_start_date = date('Y-t-01 23:59:59');
7429 $compare_end_date = date('Y-m-t 23:59:59');
7430
7431 $sqlQuery3 = "SELECT wpopi_ops.ops_id, ops_title, wpopi_ops.user_id, start_date, end_date, user_email
7432 FROM wpopi_ops, wpopi_users WHERE wpopi_ops.user_id = wpopi_users.id";
7433 /* , wpopi_users
7434 WHERE wpopi_users.ID = wpopi_ops.user_id"; */
7435
7436/*
7437// if($names_only === false)
7438// {
7439 $sqlQuery3 .= " WHERE (end_date = '0000-00-00 00:00:00'
7440 OR end_date = '1970-01-01 12:00:00'
7441 OR end_date > '2017-02-01 00:00:00') "; // , user_email, display_name
7442// }
7443*/
7444
7445 if(isset($_GET['email_filter']))
7446 {
7447 $email_filter = $_GET['email_filter'];
7448 $sqlQuery3 .= " AND user_email LIKE '%". $_GET['email_filter'] ."%'";
7449 }
7450 else
7451 {
7452 $email_filter = 'vr.fi';
7453 $sqlQuery3 .= " AND user_email LIKE '%vr.fi%'";
7454 }
7455
7456 if($single_user_page)
7457 {
7458 $sqlQuery3 .= ' AND user_id = '. $_GET['mailto'];
7459 }
7460 else
7461 {
7462 $sqlQuery3 .= ' ORDER BY wpopi_ops.ops_id DESC';
7463 }
7464
7465 write_log('-------------------');
7466 write_log('- Study plan list -');
7467 write_log('-------------------');
7468
7469 // $sqlQuery3 .= ' LIMIT 100 ';
7470
7471 // end_date >= '". $compare_end_date ."' AND end_date != '0000-00-00 00:00:00' AND
7472 // start_date >= '". $compare_start_date ."',
7473 $res3 = $wpdb->get_results($sqlQuery3);
7474
7475// print_r($res3);
7476
7477 foreach($res3 as $u)
7478 {
7479 if( opmem_get_user_basic_package($u->user_id) !== false ) // && strpos($u->user_email, $email_filter) !== false
7480 {
7481 if( $wpdb->get_var("SELECT COUNT(course_id) FROM wpopi_ops_course
7482 WHERE user_id = ". $u->user_id ." AND ops_id = ". $u->ops_id) > 0)
7483 {
7484 $res_new[$u->user_id][] = array(
7485 'user_id' => $u->user_id,
7486 'ops_id' => $u->ops_id,
7487 'ops_title' => $u->ops_title,
7488 'start_date' => $u->start_date,
7489 'end_date' => $u->end_date,
7490 'user_email' => $u->user_email
7491 );
7492 write_log('Listing plan '. $u->ops_id .' for '. $u->user_email);
7493 }
7494 else
7495 {
7496 write_log('Skipping plan '. $u->ops_id .' for '. $u->user_email .': empty plan');
7497 }
7498 }
7499 else
7500 {
7501 write_log('Skipping plan '. $u->ops_id .' for '. $u->user_email .': no package');
7502 }
7503 }
7504
7505 $debug_users = '';
7506
7507 $show_ops = array();
7508 $content_letter = array();
7509 $log_data = array();
7510
7511 if($single_user_page === false)
7512 {
7513 echo '<div class="wrap"><h1>Study plans</h1>';
7514 echo '
7515 <script type="text/javascript" language="javascript" src="/wp-content/plugins/opinahjo-common/js/DataTables/datatables.js"></script>
7516 <script type="text/javascript" src="/wp-content/plugins/opinahjo-common/js/DataTables/date-euro-mod.js"></script>';
7517
7518 echo '
7519 <link rel="stylesheet" type="text/css" href="/wp-content/plugins/opinahjo-common/js/DataTables/datatables.min.css" />
7520 <script type="text/javascript">
7521
7522 jQuery( document ).ready(function() {
7523 jQuery("#userlist").DataTable({
7524 select: true,
7525 "order": [[ 0, "asc" ]],
7526 "lengthMenu": [ [50, 100, -1], [50, 100, "All"] ],
7527 dom: "lBfrtip",
7528 buttons: [
7529 "copyHtml5",
7530 {
7531 extend: "copyHtml5",
7532 text: "Copy selected",
7533 exportOptions: {
7534 modifier: {
7535 selected: true
7536 }
7537 }
7538 },
7539 {
7540 extend: "excelHtml5",
7541 text: "Export all",
7542 },
7543 {
7544 extend: "excelHtml5",
7545 text: "Export selected",
7546 exportOptions: {
7547 modifier: {
7548 selected: true
7549 }
7550 }
7551 }
7552 ]
7553 });
7554 });
7555
7556 </script>';
7557
7558 echo '<p>List only contains study plans that have courses for users that have a valid membership.</p>
7559 <p>Please note: Coma results may take up to two hours to refresh.</p>';
7560 echo '<form method="get" action="/wp-admin/admin.php">
7561 <input type="text" name="email_filter" value="'. $email_filter .'" />
7562 <input type="hidden" name="page" value="opcom_studyplans" />
7563 <input type="submit" />
7564 </form><br /><br />';
7565 echo '
7566 <table class="userlist widefat striped" id="userlist">
7567 <thead class="billing_head">
7568 <tr>
7569 <th>Last name</th>
7570 <th>First name</th>
7571 <th>Email</th>
7572 <th>Start date</th>
7573 <th>End date</th>
7574 <th>Title</th>
7575 <th>Passed</th>
7576 <th>Pending</th>
7577 <th>Total</th>
7578
7579 </tr>
7580 </thead>
7581 <tbody>';
7582 foreach ($res_new as $uo)
7583 {
7584 foreach ($uo as $user_ops)
7585 {
7586 write_log('- - - - - - - - ');
7587 write_log('Processing user '. $user_ops['user_email']);
7588 echo '<tr>';
7589 // $userdata = get_userdata($user_ops['user_id']);
7590 $cur_user = get_userdata($user_ops['user_id']);
7591 // $cur_user_meta = get_user_meta($user_ops['user_id']);
7592 // $cur_user_membership = $cur_user->membership_level;
7593
7594 $quiz_res = opcom_count_user_quiz_results($user_ops['ops_id'], $user_ops['user_id']);
7595
7596 echo '<td>'. $cur_user->user_lastname .'</td>';
7597 echo '<td>'. $cur_user->user_firstname .'</td>';
7598 echo '<td>'. $cur_user->user_email .'</td>';
7599 echo '<td>'. substr($user_ops['start_date'], 0, 10) .'</td>';
7600 echo '<td>'. substr($user_ops['end_date'], 0, 10) .'</td>';
7601 if(strlen($user_ops['ops_title']) > 22)
7602 {
7603 $user_ops['ops_title'] = substr($user_ops['ops_title'], 0, 22). '...';
7604 }
7605 echo '<td>'. $user_ops['ops_title'] .'</td>';
7606 echo '<td>'. $quiz_res['passed'] .'</td>';
7607 echo '<td>'. $quiz_res['pending'] .'</td>';
7608 echo '<td>'. $quiz_res['total'] .'</td>';
7609
7610 /* if(!isset($_GET['mailto']))
7611 {
7612 echo '<td><!-- a href="/wp-admin/admin.php?page=opcom_studyplans&mailto='. $user_ops['user_id'] .'">Tiedot</a --></td>';
7613 } */
7614 echo '</tr>';
7615 }
7616 }
7617 echo '</tbody></table></div>';
7618
7619 write_log('--------------------');
7620 write_log('- End of plan list -');
7621 write_log('--------------------');
7622 }
7623 }
7624}
7625
7626/**
7627 * Count quiz results from a bunch of courses.
7628 * @return Array of passed and pending attempts
7629 */
7630
7631function opcom_count_user_quiz_results($ops_id, $user_id)
7632{
7633 global $wpdb;
7634 $resuts = array();
7635 $sqlQuery4 = "SELECT course_id, site_id FROM wpopi_ops_course WHERE
7636 ops_id = ". $ops_id ." AND user_id = ". $user_id;
7637 $user_courses = $wpdb->get_results($sqlQuery4);
7638
7639 $user_sites = array();
7640 foreach($user_courses as $where)
7641 {
7642 if(!in_array($where->site_id, $user_sites))
7643 {
7644 $user_sites[] = $where->site_id;
7645 }
7646 }
7647 $opcom_quizzes = array();
7648
7649 if(!empty($user_courses))
7650 {
7651 // Lets not bother if the user has no courses to begin with
7652 if(!empty($user_sites))
7653 {
7654 $opcom_quizzes = opcom_get_coma_multisite_quiz_scores($user_id, $user_sites);
7655 }
7656 $quiz_attempts = opcom_get_quiz_attempts($user_id);
7657 foreach ($user_courses as $ops_course)
7658 {
7659 $quiz_complete = false;
7660 if(isset($quiz_attempts[$ops_course->site_id .'-'. $ops_course->course_id]))
7661 {
7662 foreach($quiz_attempts[$ops_course->site_id .'-'. $ops_course->course_id] as $attempt)
7663 {
7664 if($attempt['pass'] == 1)
7665 {
7666 $quiz_complete = true;
7667 }
7668 }
7669 }
7670 elseif(isset($opcom_quizzes[$ops_course->site_id .'-'. $ops_course->course_id]))
7671 {
7672 if($opcom_quizzes[$ops_course->site_id .'-'. $ops_course->course_id]['status'] == 'passed')
7673 {
7674 $quiz_complete = true;
7675 }
7676 }
7677
7678 if($quiz_complete === true)
7679 {
7680 $results['passed']++;
7681 }
7682 else
7683 {
7684 $results['pending']++;
7685 }
7686 $results['total']++;
7687 }
7688 }
7689 return $results;
7690}
7691
7692
7693
7694/**
7695 * Gravity Wiz // Gravity Forms // Create Coupons with Gravity Forms for Gravity Forms
7696 * This is a heavily modified version intended to populate Gravity Forms' discount codes
7697 * from the data we've got in our own systems.
7698 *
7699 * @license GPL-2.0+ (original license, please Google for complete code)
7700 */
7701class GW_Create_Coupon {
7702
7703 public function __construct( $args = array() ) {
7704
7705 // set our default arguments, parse against the provided arguments, and store for use throughout the class
7706 $this->_args = wp_parse_args( $args, array(
7707 'form_id' => false,
7708 'coupon_code' => false,
7709 'plugin' => 'gf',
7710 'amount' => 0,
7711 'type' => '', // accepts: 'fixed_cart', 'percent', 'fixed_product', 'percent_product'
7712 'start' => '',
7713 'expire' => '',
7714 'meta' => array()
7715 ) );
7716
7717 // do version check in the init to make sure if GF is going to be loaded, it is already loaded
7718 add_action( 'init', array( $this, 'init' ) );
7719
7720 }
7721
7722 public function init() {
7723
7724 // make sure we're running the required minimum version of Gravity Forms and that WooCommerce is active
7725 if( ! property_exists( 'GFCommon', 'version' ) || ! version_compare( GFCommon::$version, '1.8', '>=' ) ) {
7726 return;
7727 }
7728 $this->create_coupon();
7729
7730 }
7731
7732 public function create_coupon() {
7733
7734 $coupon_code = $this->_args['coupon_code'];
7735 $amount = $this->_args['amount'];
7736 $type = $this->_args['type'];
7737 $start = $this->_args['start'];
7738 $expire = $this->_args['expire'];
7739
7740 if( ! $coupon_code ) {
7741 return;
7742 }
7743
7744 $plugin_func = array( $this, sprintf( 'create_coupon_%s', $this->_args['plugin'] ) );
7745
7746 if( is_callable( $plugin_func ) ) {
7747 call_user_func( $plugin_func, $coupon_code, $amount, $type, $start, $expire );
7748 }
7749
7750 }
7751
7752 public function create_coupon_gf( $coupon_code, $amount, $type, $start, $expire ) {
7753
7754 if( ! class_exists( 'GFCoupons' ) ) {
7755 return;
7756 }
7757
7758 // hack to load GF Coupons data.php file
7759 if( is_callable( 'gf_coupons' ) ) {
7760 gf_coupons()->get_config( array( 'id' => 0 ), false );
7761 } else {
7762 GFCoupons::get_config( array( 'id' => 0 ), false );
7763 }
7764
7765 $meta = wp_parse_args( $this->_args['meta'], array(
7766 'form_id' => false,
7767 'coupon_name' => $coupon_code,
7768 'coupon_code' => strtoupper( $coupon_code ),
7769 'coupon_type' => $type, // 'flat', 'percentage'
7770 'coupon_amount' => $amount,
7771 'coupon_start' => $start, // MM/DD/YYYY
7772 'coupon_expiration' => $expire, // MM/DD/YYYY
7773 'coupon_limit' => false,
7774 'coupon_stackable' => false
7775 ) );
7776
7777 $form_id = $meta['form_id'] ? $meta['form_id'] : 0;
7778 unset( $meta['form_id'] );
7779
7780 $feed = gf_coupons()->get_feeds($form_id);
7781 $exists = false;
7782 foreach($feed as $feeditem)
7783 {
7784 if($feeditem['meta']['coupon_code'] == strtoupper( $coupon_code ))
7785 {
7786 $exists = true;
7787 }
7788 }
7789
7790 // Lets not save multiple copies of the same discount code
7791 if($exists === false)
7792 {
7793 if( is_callable( 'gf_coupons' ) ) {
7794 $meta['gravityForm'] = $form_id ? $form_id : 0;
7795 $meta['couponName'] = $meta['coupon_name'];
7796 $meta['couponCode'] = $meta['coupon_code'];
7797 $meta['couponAmountType'] = $meta['coupon_type'];
7798 $meta['couponAmount'] = $meta['coupon_amount'];
7799 $meta['startDate'] = $meta['coupon_start'];
7800 $meta['endDate'] = $meta['coupon_expiration'];
7801 $meta['usageLimit'] = $meta['coupon_limit'];
7802 $meta['isStackable'] = $meta['coupon_stackable'];
7803 $meta['usageCount'] = 0;
7804 gf_coupons()->insert_feed( $form_id, true, $meta );
7805 } else {
7806 GFCouponsData::update_feed( 0, $form_id, true, $meta );
7807 }
7808 }
7809
7810 }
7811
7812}
7813
7814?>