my-maxi-skirt /wp-content/plugins/wp-invoice/core/wpi_functions.php

Language PHP Lines 3033
MD5 Hash 255ba36bcefeac09f578acca1ffeb4b1 Estimated Cost $51,163 (why?)
Repository https://bitbucket.org/sanders_nick/my-maxi-skirt.git View Raw File
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
<?php
/**
 *
 * Handles all functions
 *
 */
setlocale(LC_MONETARY, 'en_US');

class WPI_Functions {


  /**
   * PHP function to echoing a message to JS console
   * Ported from WP-Property
   *
   * @since 3.0.3
   */
  function console_log($text = false) {
    global $wpi_settings;

    if(isset($wpi_settings['developer_mode']) && $wpi_settings['developer_mode'] != 'true') {
      return;
    }

    if(empty($text)) {
      return;
    }

    if(is_array($text) || is_object($text)) {
      $text = str_replace("\n", '', print_r($text, true));
    }

    //** Cannot use quotes */
    $text = str_replace('"', '-', $text);

    add_filter('wp_footer', create_function('$nothing,$echo_text = "'. $text .'"', 'echo \'<script type="text/javascript">if(typeof console == "object"){console.log("\' . $echo_text . \'");}</script>\'; '));
    add_filter('admin_footer', create_function('$nothing,$echo_text = "'. $text .'"', 'echo \'<script type="text/javascript">if(typeof console == "object"){console.log("\' . $echo_text . \'");}</script>\'; '));

  }


  /**
   * Retreives API key from UD servers.
   *
   * @todo Add loggin functionality so user can reference some log to see why key may not be updating.
   * @since 3.0.2
   *
   */
  function get_api_key($args = false){

    $defaults = array(
      'return_all' => false,
      'force_check' => false
    );

    $args = wp_parse_args( $args, $defaults );

    //** check if API key already exists */
    $ud_api_key = get_option('ud_api_key');

    //** if key exists, and we are not focing a check, return what we have */
    if($ud_api_key && !$args['force_check']) {
      return $ud_api_key;
    }

    $blogname = urlencode(str_replace(array('http://', 'https://'), '', get_bloginfo('url')));
    $system = 'wpi';
    $wpp_version = WP_INVOICE_VERSION_NUM;

    $check_url = "http://updates.usabilitydynamics.com/key_generator.php?system=$system&site=$blogname&system_version=$wpp_version";

    $response = @wp_remote_get($check_url);

    if(!$response) {
      return false;
    }

    //** Check for errors */
    if(is_object($response) && !empty($response->errors)) {
      /*
      foreach($response->errors as $errors) {
        $error_string .= implode(",", $errors);
        UD_F::log("API Check Error: " . $error_string);
      }
      */
      return false;
    }

    //** Quit if failture */
    if($response['response']['code'] != '200') {
      return false;
    }

    $response['body'] = trim($response['body']);

    //** If return is not in MD5 format, it is an error */
    if(strlen($response['body']) != 40) {

      if($args['return']) {
        return $response['body'];
      } else {
        /* UD_F::log("API Check Error: " . sprintf(__('An error occured during premium feature check: <b>%s</b>.','wpp'), $response['body'])); */
        return false;
      }
    }

    //** update wpi_key is DB */
    update_option('ud_api_key', $response['body']);

    // Go ahead and return, it should just be the API key
    return $response['body'];
  }

  /**
   * Function for performing a wpi_object search
   *
   *
   * @todo This function is not ready at all, it doesn't do any searching, just returns all invoices for testing datatables
   * @since 3.0
   *
   */
  static function query($search_vars = false) {
    global $wpdb;

    $sort_by = " ORDER BY post_modified DESC ";
    /** Start our SQL */
    $sql = "SELECT * FROM {$wpdb->posts} AS p WHERE post_type = 'wpi_object' ";

    if (!empty($search_vars)) {

      if (is_string($search_vars)) {
        $args = array();
        parse_str($search_vars, $args);
        $search_vars = $args;
      }

      /*
        $use_status_filter = false;
        if ( !empty( $search_vars['status'] ) ) {
        $use_status_filter = true;
        }
       */
      foreach ($search_vars as $primary_key => $key_terms) {

        //** Handle search_string differently, it applies to all meta values */
        if ($primary_key == 's') {
          /* First, go through the posts table */
          $tofind = strtolower($key_terms);
          $sql .= " AND (";
          $sql .= " p.ID IN (SELECT ID FROM {$wpdb->posts} WHERE LOWER(post_title) LIKE '%$tofind%')";
          /* Now go through the post meta table */
          $sql .= " OR p.ID IN (SELECT post_id FROM {$wpdb->postmeta} WHERE LOWER(meta_value) LIKE '%$tofind%')";
          $sql .= ")";
          continue;
        }

        // Type
        if ($primary_key == 'type') {
          if (empty($key_terms)) {
            continue;
          }

          if (is_array($key_terms)) {
            $key_terms = implode("','", $key_terms);
          }
          $sql .= " AND ";
          $sql .= " p.ID IN (SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = 'type' AND meta_value IN ('{$key_terms}'))";
          continue;
        }

        // Status
        if ($primary_key == 'status') {
          if (empty($key_terms)) {
            continue;
          }

          if (is_array($key_terms)) {
            $sql .= " AND (";
            $i = 0;
            foreach ($key_terms as $term) {
              if (empty($term)) {
                continue;
              }
              if ($i > 0) {
                $sql .= " OR ";
              }
              $sql .= " post_status = '{$term}' ";
              $i++;
            }
            $sql .= ")";
          }
        }
        /*
          if ( !$use_status_filter ) {
          $sql .= " AND ( post_status = 'active' ) ";
          }
         */
        // Recipient
        if ($primary_key == 'recipient') {
          if (empty($key_terms)) {
            continue;
          }

          $user = get_user_by('id', $key_terms);

          $sql .= " AND ";
          $sql .= " p.ID IN (SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = 'user_email' AND meta_value = '{$user->user_email}')";

          continue;
        }

        // Sorting
        if ($primary_key == 'sorting') {
          $sort_by = " ORDER BY {$key_terms['order_by']} {$key_terms['sort_dir']} ";
        }

        /* Date */
        if ($primary_key == 'm') {
          if (empty($key_terms) || (int) $key_terms == 0) {
            continue;
          }

          $key_terms = '' . preg_replace('|[^0-9]|', '', $key_terms);
          $sql .= " AND YEAR(post_date)=" . substr($key_terms, 0, 4);
          if (strlen($key_terms) > 5) {
            $sql .= " AND MONTH(post_date)=" . substr($key_terms, 4, 2);
          }
          if (strlen($key_terms) > 7) {
            $sql .= " AND DAYOFMONTH(post_date)=" . substr($key_terms, 6, 2);
          }
          if (strlen($key_terms) > 9) {
            $sql .= " AND HOUR(post_date)=" . substr($key_terms, 8, 2);
          }
          if (strlen($key_terms) > 11) {
            $sql .= " AND MINUTE(post_date)=" . substr($key_terms, 10, 2);
          }
          if (strlen($key_terms) > 13) {
            $sql .= " AND SECOND(post_date)=" . substr($key_terms, 12, 2);
          }
        }
      }
    }

    $sql = $sql . $sort_by;
    //echo $sql;
    $results = $wpdb->get_results($sql);

    return $results;
  }

  /**
   *
   * @global object $wpdb
   * @param array $search_vars
   * @param string $interval
   * @return mixed
   * @author odokienko@UD
   */
  static function get_sales_by ($search_vars = false, $interval="weekly") {
    global $wpdb;

    switch ($interval){
      case "weekly":
        $interval_function = 'WEEK';
        break;
      case 'daily':
        $interval_function = 'DAYOFYEAR';
        break;
      case 'monthly':
      default:
        $interval_function = 'MONTH';
        break;
    }

    if (!empty($search_vars)) {

      if (is_string($search_vars)) {
        $args = array();
        parse_str($search_vars, $args);
        $search_vars = $args;
      }

      foreach ($search_vars as $primary_key => $key_terms) {

        //** Handle search_string differently, it applies to all meta values */
        if ($primary_key == 's' && !empty($key_terms)) {
          /* First, go through the posts table */
          $tofind = strtolower($key_terms);
          $sql .= " AND (";
          $sql .= " LOWER(`{$wpdb->posts}`.post_title) LIKE '%$tofind%'";
          /* Now go through the post meta table */
          $sql .= " OR
                    `{$wpdb->posts}`.ID IN (SELECT post_id FROM {$wpdb->postmeta} WHERE LOWER(meta_value) LIKE '%$tofind%')";
          $sql .= ")";
          continue;
        }

        // Type
        if ($primary_key == 'type') {
          if (empty($key_terms)) {
            continue;
          }

          if (is_array($key_terms)) {
            $key_terms = implode("','", $key_terms);
          }
          $sql .= " AND ";
          $sql .= " `{$wpdb->posts}`.ID IN (SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = 'type' AND meta_value IN ('{$key_terms}'))";
          continue;
        }

        // Status
        if ($primary_key == 'status') {
          if (empty($key_terms)) {
            continue;
          }

          if (is_array($key_terms)) {
            $sql .= " AND (";
            $i = 0;
            foreach ($key_terms as $term) {
              if (empty($term)) {
                continue;
              }
              if ($i > 0) {
                $sql .= " OR ";
              }
              $sql .= " `{$wpdb->posts}`.post_status = '{$term}' ";
              $i++;
            }
            $sql .= ")";
          }
        }
        /*
          if ( !$use_status_filter ) {
          $sql .= " AND ( post_status = 'active' ) ";
          }
         */
        // Recipient
        if ($primary_key == 'recipient') {
          if (empty($key_terms)) {
            continue;
          }

          $user = get_user_by('id', $key_terms);

          $sql .= " AND ";
          $sql .= " `{$wpdb->posts}`.ID IN (SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = 'user_email' AND meta_value = '{$user->user_email}')";

          continue;
        }

        /* Date */
        if ($primary_key == 'm') {
          if (empty($key_terms) || (int) $key_terms == 0) {
            continue;
          }

          $key_terms = '' . preg_replace('|[^0-9]|', '', $key_terms);
          $sql .= " AND YEAR(`{$wpdb->posts}`.post_date)=" . substr($key_terms, 0, 4);
          if (strlen($key_terms) > 5) {
            $sql .= " AND MONTH(`{$wpdb->posts}`.post_date)=" . substr($key_terms, 4, 2);
          }
          if (strlen($key_terms) > 7) {
            $sql .= " AND DAYOFMONTH(`{$wpdb->posts}`.post_date)=" . substr($key_terms, 6, 2);
          }
          if (strlen($key_terms) > 9) {
            $sql .= " AND HOUR(`{$wpdb->posts}`.post_date)=" . substr($key_terms, 8, 2);
          }
          if (strlen($key_terms) > 11) {
            $sql .= " AND MINUTE(`{$wpdb->posts}`.post_date)=" . substr($key_terms, 10, 2);
          }
          if (strlen($key_terms) > 13) {
            $sql .= " AND SECOND(`{$wpdb->posts}`.post_date)=" . substr($key_terms, 12, 2);
          }
        }
      }
    }

    $date_table = "
        select @maxDate - interval (a.a+(10*b.a)+(100*c.a)) day aDate from
        (select 0 as a union all select 1 union all select 2 union all select 3
        union all select 4 union all select 5 union all select 6 union all
        select 7 union all select 8 union all select 9) a, /*10 day range*/
        (select 0 as a union all select 1 union all select 2 union all select 3
        union all select 4 union all select 5 union all select 6 union all
        select 7 union all select 8 union all select 9) b, /*100 day range*/
        (select 0 as a union all select 1 union all select 2 union all select 3
        union all select 4 union all select 5 union all select 6 union all
        select 7 union all select 8 union all select 9) c, /*1000 day range*/
        (select
          @minDate := date_format(FROM_UNIXTIME((select min(time) from `{$wpdb->prefix}wpi_object_log` mn join {$wpdb->posts} on (mn.object_id=`{$wpdb->posts}`.id and `{$wpdb->posts}`.post_type = 'wpi_object' {$sql}))),'%Y-%m-%d'),
          @maxDate := date_format(FROM_UNIXTIME((select max(time) from `{$wpdb->prefix}wpi_object_log` mx join {$wpdb->posts} on (mx.object_id=`{$wpdb->posts}`.id and `{$wpdb->posts}`.post_type = 'wpi_object' {$sql}))),'%Y-%m-%d')
        ) e
      ";

    $sql = "
      SELECT distinct
      YEAR(datetable.aDate) as int_year,
      {$interval_function}(datetable.aDate) int_erval,
      sum(COALESCE(if (payment.action='refund',payment.value*-1,payment.value),0)) as sum_interval
      FROM ($date_table) datetable
      left join `{$wpdb->prefix}wpi_object_log` as payment on (
        datetable.aDate=date_format(FROM_UNIXTIME(payment.time),'%Y-%m-%d')
        and (
          payment.object_id in (
            select `{$wpdb->posts}`.id from `{$wpdb->posts}` where `{$wpdb->posts}`.post_type = 'wpi_object' {$sql}
          )
        )
        AND (payment.action = 'add_payment' or payment.action = 'refund')
        AND payment.attribute = 'balance'
      )

      WHERE datetable.aDate between @minDate and @maxDate
      GROUP BY 1,2
    ";

    $results = $wpdb->get_results($sql);

    return $results;
  }

  /**
   * Get Search filter fields
   *
   * @global array $wpi_settings
   * @global object $wpdb
   * @return type
   */
  function get_search_filters() {
    global $wpi_settings, $wpdb;

    $filters = array();

    $default = array(array(
            'key' => 'all',
            'label' => __('All'),
            'amount' => 0
            ));

    if (isset($wpi_settings['types'])) {
      $f = $default;
      $i = 1;
      $all = 0;
      foreach ($wpi_settings['types'] as $key => $value) {
        $amount = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->postmeta} WHERE meta_key = 'type' AND meta_value = '{$key}'");
        $all = $all + $amount;
        if ($amount > 0) {
          $f[$i]['key'] = $key;
          $f[$i]['label'] = $value['label'];
          $f[$i]['amount'] = $amount;
          $i++;
        }
      }
      if ($all > 0) {
        $f[0]['amount'] = $all;
        $filters['type'] = $f;
      }
      // If there is only 1 type - hide Types option
      if ($i == 2) {
        unset($filters['type']);
      }
    }

    if (!empty($wpi_settings['statuses'])) {
      $f = array();
      $amount = 0;
      $i = 1;
      $all = 0;
      foreach ($wpi_settings['statuses'] as $status) {
        $amount = $wpdb->get_var("SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_status = '{$status}' AND post_type = 'wpi_object'");
        $all = $all + $amount;
        if ($amount > 0) {
          $f[$i]['key'] = $status;
          $f[$i]['label'] = strtoupper(substr($status, 0, 1)) . substr($status, 1);
          $f[$i]['amount'] = $amount;
          $i++;
        }
      }
      if ($all > 0) {
        $filters['status'] = $f;
      }
    }

    return $filters;
  }

  /**
   * Convert a string to a url-like slug
   *
   * @param type $slug
   * @return type
   */
  function slug_to_label($slug = false) {

    if (!$slug)
      return;

    $slug = str_replace("_", " ", $slug);
    $slug = ucwords($slug);
    return $slug;
  }

  /**
   * Convert a string into a number. Allow invoice ID to be passed for currency symbol localization
   *
   * @global array $wpi_settings
   * @param type $amount
   * @param type $invoice_id
   * @return type
   */
  static function currency_format($amount, $invoice_id = false) {
    global $wpi_settings;

    if ($invoice_id) {
      $invoice = get_invoice($invoice_id);
    }

    $currency_symbol = !empty($wpi_settings['currency']['symbol'][$invoice['default_currency_code']]) ? $wpi_settings['currency']['symbol'][$invoice['default_currency_code']] : '$';

    $amount = (float) $amount;

    $thousands_separator_symbol = !isset( $wpi_settings['thousands_separator_symbol'] )?',':($wpi_settings['thousands_separator_symbol'] == '0'?'':$wpi_settings['thousands_separator_symbol']);

    return $currency_symbol . number_format($amount, 2, '.', $thousands_separator_symbol);
  }

  /**
   * Run numbers for reporting purposes.
   *
   * @global object $wpdb
   * @global type $wpi_reports
   * @return type
   */
  static function run_reports() {
    global $wpdb, $wpi_reports;

    //* Get all invoices */
    $invoice_ids = $wpdb->get_col("SELECT ID FROM {$wpdb->posts} WHERE post_type = 'wpi_object' ");

    $totals = array();
    $objects = array();
    $r = array(
        'line_item_counts' => array()
    );

    foreach ($invoice_ids as $post_id) {
      $wpi_invoice_object = new WPI_Invoice();
      $wpi_invoice_object->load_invoice("id=$post_id");
      $objects[$post_id] = $wpi_invoice_object->data;
    }

    foreach ($objects as $object) {

      //** Total paid invoices per client  */
      if ($object['post_status'] == 'paid') {
        $r['collected_client_value'][$object['user_email']] = !empty($r['client_value'][$object['user_email']]) ? $r['client_value'][$object['user_email']] : 0 + $object['subtotal'] + $object['total_tax'] - $object['total_discount'];
        $r['total_paid'][] = $objects[$object['ID']]['subtotal'] + $objects[$object['ID']]['total_tax'] - $objects[$object['ID']]['total_discount'];;

        foreach ($object['itemized_list'] as $list_item) {
          $r['collected_line_items'][$list_item['name']] = !empty($r['collected_line_items'][$list_item['name']]) ? $r['collected_line_items'][$list_item['name']] : 0 + $list_item['line_total_after_tax'];
          if (!empty($r['line_item_counts'][$list_item['name']])) {
            $r['line_item_counts'][$list_item['name']]++;
          } else {
            $r['line_item_counts'][$list_item['name']] = 1;
          }
        }
      }

      if ($object['post_status'] == 'active') {
        $r['uncollected_client_value'][$object['user_email']] = !empty($r['uncollected_client_value'][$object['user_email']]) ? $r['uncollected_client_value'][$object['user_email']] : 0 + $object['subtotal'] + $object['total_tax'] - $object['total_discount'];
        $r['total_unpaid'][] = $objects[$object['ID']]['subtotal'] + $objects[$object['ID']]['total_tax'] - $objects[$object['ID']]['total_discount'];
      }

    }

    if (isset($r['collected_line_items']) && is_array($r['collected_line_items'])) {
      arsort($r['collected_line_items']);
    }

    if (isset($r['uncollected_client_value']) && is_array($r['uncollected_client_value'])) {
      arsort($r['uncollected_client_value']);
    }

    if (isset($r['collected_client_value']) && is_array($r['collected_client_value'])) {
      arsort($r['collected_client_value']);
    }

    if (isset($r['total_paid']) && is_array($r['total_paid'])) {
      $r['total_paid'] = array_sum($r['total_paid']);
    }

    if (isset($r['total_unpaid']) && is_array($r['total_unpaid'])) {
      $r['total_unpaid'] = array_sum($r['total_unpaid']);
    }

    $wpi_reports = $r;
    return $r;
  }

  /**
   * Check if theme-specific stylesheet exists.
   *
   * get_option('template') seems better choice than get_option('stylesheet'), which returns the current theme's slug
   * which is a problem when a child theme is used. We want the parent theme's slug.
   *
   * @since 3.0
   *
   */
  static function has_theme_specific_stylesheet() {

    $theme_slug = get_option('template');

    if (file_exists(WPI_Path . "/core/template/theme-specific/{$theme_slug}.css")) {
      return true;
    }

    return false;
  }

  /**
   * Check if Payment method allowed
   * @param String $param
   * @return bool
   */
  function is_true($param) {
    if (empty($param))
      return false;
    return ( $param == 'true' || $param == 'on' || $param == 'yes' ) ? true : false;
  }

  /**
   * Fixes billing structure
   * @param array $wpi_settings_billings
   * @param array &$invoice_billings
   */
  function merge_billings($wpi_settings_billings, $invoice_billings) {
    if (!isset($invoice_billings) || !is_array($invoice_billings)) {
      $invoice_billings = array();
    }
    if (is_array($wpi_settings_billings)) {
      foreach ($wpi_settings_billings as $key => $value) {
        // TODO: Refactor on|yes|true off|no|false
        // WPI_Functions::is_true() used temporary
        if (!WPI_Functions::is_true($value['allow'])) {
          unset($invoice_billings[$key]);
        } else {
          if (!empty($invoice_billings[$key])) {
            if (!isset($invoice_billings[$key]['name'])) {
              $invoice_billings[$key]['name'] = $value['name'];
            }
            if (!isset($invoice_billings[$key]['allow'])) {
              $invoice_billings[$key]['allow'] = $value['allow'];
            }
            if (!isset($invoice_billings[$key]['default_option'])) {
              $invoice_billings[$key]['default_option'] = $value['default_option'];
            }
            if (!empty($value['settings'])) {
              foreach ($value['settings'] as $setting_key => $setting_value) {
                foreach ($setting_value as $setting_key_field => $setting_value_field) {
                  if (!isset($invoice_billings[$key]['settings'][$setting_key][$setting_key_field])) {
                    $invoice_billings[$key]['settings'][$setting_key][$setting_key_field] = $setting_value_field;
                  }
                }
              }
            }
          } else {
            $invoice_billings[$key] = $value;
          }
        }
      }
    }
  }

  function set_default_payment_method($wpi_settings_billings, $invoice_data) {
    $settings_dpm = '';

    if (!empty($wpi_settings_billings) && is_array($wpi_settings_billings)) {
      foreach ($wpi_settings_billings as $method => $value) {
        if ($value['default_option'] == 'true') {
          $settings_dpm = $method;
        }
      }
    }

    $invoice_data['default_payment_method'] = $settings_dpm;
  }

  /**
   * Returns an array of users
   * Used for user-email auto-completion.
   * @uses $wpdb
   * @since 3.0
   * @return array. Users List
   *
   */
  function build_user_array() {
    global $wpdb;

    return $wpdb->get_results("SELECT display_name,user_email,ID FROM {$wpdb->prefix}users", ARRAY_A);
  }

  /**
   * Handle user data updating
   *
   * Typically called when saving an invoice.
   * @since 3.0
   */
  function update_user($userdata) {

    $user_id = email_exists($userdata['user_email']);

    if ($user_id) {
      $userdata['ID'] = $user_id;
    }

    if (empty($userdata['ID']) && empty($userdata['user_email'])) {
      return false;
    }

    if ($user_id) {
      $user_id = wp_update_user($userdata);
    } else {
      if (empty($userdata['user_login'])) {
        if (!empty($userdata['first_name']) && !empty($userdata['last_name'])) {
          $userdata['display_name'] = $userdata['first_name'] . ' ' . $userdata['last_name'];
        } else {

        }
      }

      $userdata['user_login'] = $userdata['user_email'];

      if(empty($userdata['user_pass'])) {
        $userdata['user_pass'] = wp_generate_password( 12, false);
      }

      $user_id = wp_insert_user($userdata);
    }

    // Prevent entering of wrong phone number to avoid errors on front-end
    if (!preg_match('/\A[\d.+?]{0,3}-[\d.+?]{0,3}-[\d.+?]{0,4}\Z/si', $userdata['phonenumber'])) {
      if (preg_match('/\A[\d.+?]{0,10}\Z/si', $userdata['phonenumber'])) {
        $phonenumber = $userdata['phonenumber'];
        $userdata['phonenumber'] = substr($phonenumber, 0, 3) . '-' . substr($phonenumber, 3, 3) . '-' . substr($phonenumber, 6, 4);
      } else {
        $userdata['phonenumber'] = '';
      }
    }

    if (!is_object($user_id) && $user_id > 0) {
      /* Update user's meta data */
      $non_meta_data = array(
          'ID',
          'first_name',
          'last_name',
          'nickname',
          'description',
          'user_pass',
          'user_email',
          'user_url',
          'user_nicename',
          'display_name',
          'user_registered',
          'role'
      );
      foreach ($userdata as $key => $value) {
        if (!in_array($key, $non_meta_data)) {
          update_user_meta($user_id, $key, $value);
        }
      }

      return $user_id;
    }

    return $user_id;
  }

  /**
   * Add itemized charge like itemized list item
   *
   * @param int $invoice_id
   * @param string $name
   * @param float $amount
   * @param float $tax
   * @return array
   */
  function add_itemized_charge($invoice_id, $name, $amount, $tax) {

    $post_id = wpi_invoice_id_to_post_id($invoice_id);
    $charge_items = get_post_meta($post_id, 'itemized_charges', true);

    $new_item = array(
        'name' => $name,
        'amount' => $amount,
        'tax' => $tax,
        'before_tax' => $amount,
        'after_tax' => $amount + ($amount / 100 * $tax)
    );

    if (!empty($charge_items)) {
      $charge_items[] = $new_item;
    } else {
      $charge_items[0] = $new_item;
    }

    update_post_meta($post_id, 'itemized_charges', $charge_items);

    return end($charge_items);
  }

  /**
   * Loads invoice variables into post if it is a wpi_object
   *
   * @hooked_into setup_postdata()
   * @uses $wpdb
   * @since 3.0
   *
   */
  function the_post(&$post) {
    global $post;

    if ($post->post_type == 'wpi_object') {
      $this_invoice = new WPI_Invoice();
      $invoice_id = $post->ID;
      $this_invoice->load_invoice("id=$invoice_id");

      $t_post = (array) $post;
      $t_data = (array) $this_invoice->data;

      $t_post = WPI_Functions::array_merge_recursive_distinct($t_post, $t_data);
      $post = (object) $t_post;
    }
  }

  function objectToArray($object) {
    if (!is_object($object) && !is_array($object)) {
      return $object;
    }
    if (is_object($object)) {
      $object = get_object_vars($object);
    }
    return array_map(array('WPI_functions', 'objectToArray'), $object);
  }

  /**
    Generates a slug
   */
  function generateSlug($title) {
    $slug = preg_replace("/[^a-zA-Z0-9 ]/", "", $title);
    $slug = str_replace(" ", "_", $slug);
    return $slug;
  }

  /**
   * Figure out current page for front-end AJAX function
   */
  function current_page() {
    $pageURL = 'http';
    if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
      $pageURL .= "s";
    }
    $pageURL .= "://";
    if ($_SERVER["SERVER_PORT"] != "80") {
      $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
    } else {
      $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    }
    return $pageURL;
  }

  /**
    Get users paid and pending invoices
   */
  function get_user_invoices($args) {
    global $wpdb;

    $defaults = array('user_id' => false, 'status' => false);
    extract(wp_parse_args($args, $defaults), EXTR_SKIP);

    // User email and id are the same thing
    if (!$user_id && isset($user_email))
      $user_id = $user_email;

    // If nothing is set, nothing we can do
    if (!isset($user_id))
      return;

    $users_invoices = $wpdb->get_col("
          SELECT post_id
          FROM {$wpdb->postmeta} postmeta
          JOIN {$wpdb->posts} posts ON posts.ID = postmeta.post_id
          WHERE postmeta.meta_key = 'user_email'
            AND postmeta.meta_value = '" . $user_id . "'
            AND posts.post_type = 'wpi_object'
            AND posts.post_status = '$status'
        ");

    // Nothing found
    if (!is_array($users_invoices))
      return false;

    $return = array();

    foreach ($users_invoices as $post_id) {

      $invoice_id = wpi_post_id_to_invoice_id($post_id);

      $this_invoice = new WPI_Invoice();
      $this_invoice->load_invoice("id={$invoice_id}");

      if (!empty($status) && $status != $this_invoice->data['post_status'])
        continue;

      // Do not include quotes
      if ($this_invoice->data['type'] != 'invoice') {
        continue;
      }

      $return[] = $this_invoice;
    }

    return $return;
  }

  /**
    Add message to notice queve
   */
  function add_message($message, $type = 'good', $class = '') {
    global $wpi_messages;
    if (!is_array($wpi_messages))
      $wpi_messages = array();

    array_push($wpi_messages, array('message' => $message, 'type' => $type, 'class' => $class));
  }

  /**
    Display messages in queve
   */
  function print_messages() {
    global $wpi_messages;

    if (count($wpi_messages) < 1)
      return;

    $update_messages = array();
    $warning_messages = array();

    echo "<div id='wpi_message_stack'>";

    foreach ($wpi_messages as $message) {

      if ($message['type'] == 'good') {
        array_push($update_messages, array('message' => $message['message'], 'class' => $message['class']));
      }

      if ($message['type'] == 'bad') {
        array_push($warning_messages, array('message' => $message['message'], 'class' => $message['class']));
      }
    }

    if (count($update_messages) > 0) {
      echo "<div class='wpi_message wpi_yellow_notification'>";
      foreach ($update_messages as $u_message)
        echo "<div class='wpi_message_holder {$message['class']}' >{$u_message['message']}</div>";
      echo "</div>";
    }

    if (count($warning_messages) > 0) {
      echo "<div class='wpi_message wpi_red_notification'>";
      foreach ($warning_messages as $w_message)
        echo "<div class='wpi_message_holder {$w_message['class']}' >{$w_message['message']}</div>";
      echo "</div>";
    }

    echo "</div>";
  }

  /**
   * Checks if particular template exists in the template folder
   *
   * @global array $wpi_settings
   * @param type $template
   * @return type
   */
  function wpi_use_custom_template($template) {
    global $wpi_settings;

    /* if custom templates are turned off, don't bother checking */
    if (!isset($wpi_settings['use_custom_templates']) || $wpi_settings['use_custom_templates'] != 'yes') {
      return false;
    }

    if (file_exists($wpi_settings['frontend_template_path'] . "$template")) {
      return true;
    }

    return false;
  }

  /**
   * Determine WPI front-end template path
   *
   * @global array $wpi_settings
   * @return type
   */
  function template_path() {
    global $wpi_settings;
    $use_custom_templates = false;

    if (file_exists(STYLESHEETPATH . "/wpi/")) {
      return STYLESHEETPATH . "/wpi/";
    }
  }

  /**
   * Display invoice status formatted for back-end
   *
   * @param type $invoice_id
   */
  function get_status($invoice_id) {

    $this_invoice = new WPI_Invoice();
    $this_invoice->load_invoice("id=$invoice_id");

    if (is_array($this_invoice->data['log'])) {
      foreach (array_reverse($this_invoice->data['log']) as $event) {

        if (empty($event['text'])) {
          continue;
        }

        ?>
        <tr class="wpi_event_<?php echo $event['action']; ?> <?php if ($event['action'] == 'add_charge' || $event['action'] == 'do_adjustment')
          echo "wpi_not_for_recurring"; ?>">
          <th><?php echo date(get_option('time_format') . ' ' . get_option('date_format'), $event['time']); ?> </th>
          <td><?php echo $event['text']; ?></td>
        </tr>
        <?php
      }
    } else {
      ?>
      <tr class="wpi_event_error">
        <th colspan='2'>No log entries.</th>
      </tr>

      <?php
    }
  }

  /**
   * Render itemized charges list
   *
   * @param int $post_id
   */
  function get_charges($post_id) {

    $charges_list = get_post_meta($post_id, 'itemized_charges', true);

    $result = '';

    ob_start();

    if (!empty($charges_list)) {
      foreach ($charges_list as $key => $value) {
        ?>
        <li class="wp_invoice_itemized_charge_row clearfix" id="wp_invoice_itemized_charge_row_<?php echo $key; ?>">
          <span class="id hidden"><?php echo $key; ?></span>

          <div class="flexible_width_holder">
            <div class="flexible_width_holder_content">
              <span class="row_delete">&nbsp;</span>
              <input class="item_name input_field" name="wpi_invoice[itemized_charges][<?php echo $key; ?>][name]" value="<?php echo stripslashes($value['name']); ?>" />
            </div>
          </div>

          <span class="fixed_width_holder">
            <span class="row_amount">
              <input autocomplete="off" value="<?php echo stripslashes($value['amount']); ?>" name="wpi_invoice[itemized_charges][<?php echo $key; ?>][amount]" id="amount_item_<?php echo $key; ?>"  class="item_amount input_field">
            </span>
            <span class="row_charge_tax">
              <input autocomplete="off" value="<?php echo stripslashes($value['tax']); ?>"  name="wpi_invoice[itemized_charges][<?php echo $key; ?>][tax]" id="charge_tax_item_<?php echo $key; ?>"  class="item_charge_tax input_field">
            </span>
            <span class="row_total" id="total_item_<?php echo $key; ?>" ><?php echo $value['after_tax']; ?></span>
          </span>

        </li>
        <?php
      }

      $result .= ob_get_contents();
      ob_end_clean();
    }

    echo $result;
  }

  /**
   * Returns highest invoice ID
   *
   * @global object $wpdb
   * @return longint
   * @author korotkov@ud
   */
  function get_highest_custom_id() {
    global $wpdb;

    $invoices = get_posts(
      array(
        'post_type' => 'wpi_object',
        'numberposts' => 0,
        'post_status' => 'any'
      )
    );

    if (!count($invoices)) {
      return false;
    }

    $id_array = array();

    foreach ($invoices as $invoice) {
      $id_array[] = get_post_meta($invoice->ID, 'invoice_id', true);
      /** Get custom IDs too */
      $custom_id = get_post_meta($invoice->ID, 'custom_id', true);
      if ( $custom_id ) {
        $id_array[] = $custom_id;
      }
    }

    return @max($id_array);
  }

  /**
   * Removes empty values from array
   *
   * @param array $array
   * @return array
   * @author korotkov@ud
   */
  function remove_blank_values($array) {
    if (!is_array($array))
      return false;
    foreach ($array as $key => $value) {
      if (!empty($value))
        $return[$key] = $value;
    }
    return $return;
  }

  /**
   * Run when a plugin is being activated
   * Handles the task of migrating from old version of WPI to new
   */
  function Activate() {
    global $wpdb, $wpi_settings;
    /* check if scheduler already sheduled */
    if(!wp_next_scheduled('wpi_hourly_event')){
      /* Setup WPI schedule to handle recurring invoices */
      wp_schedule_event(time(), 'hourly', 'wpi_hourly_event');
    }
    if(!wp_next_scheduled('wpi_update')){
      /* Scheduling daily update event */
      wp_schedule_event(time(), 'daily', 'wpi_update');
    }

    WPI_Functions::log(__("Schedule created with plugin activation.", WPI));

    /* Try to create new schema tables */
    WPI_Functions::create_new_schema_tables();

    /* Get previous activated version */
    $current_version = get_option('wp_invoice_version');

    /* If no version found at all, we do new install */
    if ($current_version == WP_INVOICE_VERSION_NUM) {
      WPI_Functions::log(__("Plugin activated. No older versions found, installing version ", WPI) . WP_INVOICE_VERSION_NUM . ".");
    } else if ((int) $current_version < 3) {
      /* Determine if legacy data exist */
      WPI_Legacy::init();
      WPI_Functions::log(__("Plugin activated.", WPI));
    }

    /* Update version */
    update_option('wp_invoice_version', WP_INVOICE_VERSION_NUM);

		WPI_Functions::check_for_premium_features();

    update_option('wpi_activation_time', time());
  }

  function Deactivate() {
    wp_clear_scheduled_hook('wpi_hourly_event');
    wp_clear_scheduled_hook('wpi_update');
    WPI_Functions::log(__("Plugin deactivated.", WPI));
  }

  /**
   * Called by profile_update action/hook
   * Used to save profile settings for WP Users.
   * @param int $user_id User ID
   * @param object $old_user_data old value.
   * @return bool True on successful update, false on failure.
   */
  function save_update_profile($user_id, $old_user_data) {
    global $wpi_settings;

    if (empty($user_id) || $user_id == 0) {
      return false;
    }

    $custom_user_information = apply_filters('wpi_user_information', $wpi_settings['user_meta']['custom']);
    $user_information = array_merge($wpi_settings['user_meta']['required'], $custom_user_information);

    // On Adding/Editing Invoice user data exists in ['wpi_invoice']['user_data']
    $data = !empty($_POST['wpi_invoice']['user_data']) ? $_POST['wpi_invoice']['user_data'] : $_POST;

    if (!is_array($data)) {
      return false;
    }

    foreach ($user_information as $field_id => $field_name) {
      if (isset($data[$field_id])) {
        update_user_meta($user_id, $field_id, $data[$field_id]);
      }
    }
  }

  /**
   * Called by profile_update action/hook
   * If user_email changed then it updates user invoices with new user_email
   * @param type $user_id
   * @param type $old_user_data
   * @return boolean
   * @author odokienko@UD
   */
  function protect_user_invoices($user_id, $old_user_data) {
    global $wpdb;

    if (empty($user_id) || $user_id == 0) {
      return false;
    }

    $userdata = get_userdata($user_id);

    if ($userdata->user_email != $old_user_data->user_email){

      $wpdb->query("
        UPDATE {$wpdb->postmeta} postmeta, {$wpdb->posts} posts
        SET postmeta.meta_value = '" . $userdata->user_email . "'
        WHERE posts.ID = postmeta.post_id
          AND postmeta.meta_key = 'user_email'
          AND postmeta.meta_value = '" . $old_user_data->user_email . "'
          AND posts.post_type = 'wpi_object'
      ");

      WPI_Functions::console_log('WPI_Invoice::protect_user_invoices() '.__('user_email changed.', WPI));

    }

  }

  /*
   * Set Custom Screen Options
   */

  function wpi_screen_options() {
    global $current_screen;

    $output = '';

    switch ($current_screen->id) {

      case 'toplevel_page_wpi_main':

        break;

      case 'invoice_page_wpi_page_manage_invoice':
        $output .= '
        <div id="wpi_screen_meta" class="metabox-prefs">
          <label for="wpi_itemized-list-tax">
          <input type="checkbox" ' . (get_user_option('wpi_ui_display_itemized_tax') == 'true' ? 'checked="checked"' : '') . ' value="" id="wpi_itemized-list-tax" name="wpi_ui_display_itemized_tax" class="non-metabox-option">
          Row Tax</label>
        </div>';
        break;
    }

    return $output;
  }

  /**
   * Called by template_redirect to validate whether an invoice should be displayed
   */
  function validate_page_hash($md5_invoice_id) {
    global $wpdb, $wpi_settings, $post, $invoice_id;

    $invoice_id = $wpdb->get_var("SELECT meta_value FROM {$wpdb->postmeta} WHERE meta_key='invoice_id' AND MD5(meta_value) = '{$md5_invoice_id}'");

    if (!$invoice_id) {
      return false;
    }

    if ($wpi_settings['web_invoice_page'] != $post->ID) {
      return false;
    }


    // Verify HTTPS.  If its enforced, but not active, we reload page, and do the process again
    //print_r( $_SERVER );

    if (!function_exists('wp_https_redirect')) {
      session_start();
      if (!isset($_SESSION['https'])) {
        if ( $wpi_settings['force_https'] == 'true' && (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")) {
          $_SESSION['https'] = 1;
          header("Location: https://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']);
          @session_destroy();
          exit;
        } else {
          if (session_id() != '')
            @session_destroy();
        }
      }
      //Added to see how the invoice looks once it is created...
      if ($wpi_settings['force_https'] == 'false') {
        if (session_id() != '')
          @session_destroy();
        // Nothing should be done here, this function is simply for validating.
        // If we got this far, means invoice_id and page are validated, and HTTPS is NOT enforced
        return true;
        //print $_SERVER['SERVER_NAME']; print $_SERVER['REQUEST_URI']; die;
        //header("Location: http://" . $_SERVER['SERVER_NAME']'/wp-login.php');
        //header("Location: http://localhost/wordpress/wp-login.php");
        //exit;
      }
    }

    // 5. Validation passed
    return true;
  }

  /**
    Displayed how many days it has been since a certain date.

   */
  function days_since($date1, $return_number = false) {
    if (empty($date1))
      return "";

    if (is_array($date1))
      $date1 = $date1[year] . "-" . $date1[month] . "-" . $date1[day];

    $date2 = date("Y-m-d");
    $date1 = date("Y-m-d", strtotime($date1));


    // determine if future or past
    if (strtotime($date2) < strtotime($date1))
      $future = true;

    $difference = abs(strtotime($date2) - strtotime($date1));
    $days = round(((($difference / 60) / 60) / 24), 0);

    if ($return_number)
      return $days;

    if ($days == 0) {
      return __('Today', WPI);
    } elseif ($days == 1) {
      return($future ? __(" Tomorrow ", WPI) : __(" Yesterday ", WPI));
    } elseif ($days > 1 && $days <= 6) {
      return ($future ? __sprintf(__(" in %s days ", WPI), $days) : " ".$days." ".__("days ago", WPI));
    } elseif ($days > 6) {
      return date(get_option('date_format'), strtotime($date1));
    }
  }

  /**
   * Render money in format.
   *
   * @refactoring korotkov@ud
   * @global array $wpi_settings
   * @param type $number
   * @return type
   */
  function money_format( $number ) {
    global $wpi_settings;
    return number_format( (float)$number, 2, '.', $wpi_settings['thousands_separator_symbol']?$wpi_settings['thousands_separator_symbol']:'' );
  }

  /**
    We use this to merge two arrays.
    Used when loading default billing data, and then being updated by invoice-specific data
    Awesome function from http://us2.php.net/manual/en/function.array-merge-recursive.php
   */
  function &array_merge_recursive_distinct() {
    $aArrays = func_get_args();
    $aMerged = $aArrays[0];

    for ($i = 1; $i < count($aArrays); $i++) {
      if (is_array($aArrays[$i])) {
        foreach ($aArrays[$i] as $key => $val) {
          if (is_array($aArrays[$i][$key])) {
            $aMerged[$key] = (isset($aMerged[$key]) && is_array($aMerged[$key]) ) ? WPI_Functions::array_merge_recursive_distinct($aMerged[$key], $aArrays[$i][$key]) : $aArrays[$i][$key];
          } else {
            $aMerged[$key] = $val;
          }
        }
      }
    }

    return $aMerged;
  }

  /** @TODO: Update it to show Settings page link */
  function set_plugin_page_settings_link($links) {
    /* $settings_link = "<a href='{$core->options['links']['settings_page']}'>Settings</a>";
      array_unshift($links, $settings_link); */
    return $links;
  }

  // Checks whether all plugin tables exist via tables_exist function
  function check_tables() {
    global $wpdb;
    if (!WPI_Functions::tables_exist()) {
      $message = __("The plugin database tables are gone, deactivate and reactivate plugin to re-create them.", WPI);
    }
    WPI_UI::error_message($message);
  }

  function tables_exist() {
    global $wpdb;
    if (!$wpdb->query("SHOW TABLES LIKE '{$wpdb->base_prefix}wpi_object_log';"))
      return false;
    return true;
  }

  // Used for displaying variables in the UI, mostly for debugging
  function qc($what, $force = false) {
    global $wp_invoice_debug;

    if (is_array($what)) {
      $what = WPI_Functions::pretty_print_r($what, false);
    }

    if (is_array($what) || is_string($what)) { // this way we don't try and show classess
      if ($wp_invoice_debug || $force) {
        ?>
        <div  class="ui-state-error ui-corner-all" style="padding: 0 .7em;">
          <p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>
            <span class="message_content"><?php echo $what; ?></span></p>
        </div>
        <?php
      }
    } else {
      ?>
      <div  class="ui-state-error ui-corner-all" style="padding: 0 .7em;">
        <p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>
          <span class="message_content"><pre><?php print_r($what); ?></pre></span></p>
      </div>
      <?php
    }

    // Add QC Message to Log
    //WPI_Functions::log($what)
  }

  // Logs events and saved them into WordPress option 'wpi_log'
  // This function is intended to ease troubleshooting later
  function log($what) {
    $wpi_log = get_option('wpi_log');

    // If no session log created yet, create one
    if (!is_array($wpi_log)) {
      $wpi_log = array();
      array_push($wpi_log, array(time(), "Log Started."));
    }

    // Insert event into session
    array_push($wpi_log, array(time(), $what));

    update_option('wpi_log', $wpi_log);

    return true;
  }

  // Alternative to print_r
  function pretty_print_r($data, $echo = false) {
    // Clean $_REQUEST array
    $result = '';
    if ($data == $_REQUEST) {
      foreach ($data as $key => $value) {
        $pattern = "/PHPSESSID|ui-tab/";
        if (preg_match($pattern, $key)) {
          unset($data[$key]);
        }
      }
    }
    if (is_array($data)) { //If the given variable is an array, print using the print_r function.
      $result .= "<pre class='wpi_class_pre'>\n";
      $result .= print_r($data, true);
      $result .= "</pre>";
    } elseif (is_object($data)) {
      $result .= "<pre>\n";
      var_dump($data, true);
      $result .= "</pre>";
    } else {
      $result .= "=========&gt; ";
      $result .= var_dump($data, true);
      $result .= " &lt;=========";
    }
    if ($echo == false)
      return $result;
    $echo;
  }

  function check_settings() {
    global $wpi_settings;
    if ($wpi_settings['web_invoice_page'] == '') {
      $message .= __('Invoice page not selected. ', WPI);
      $message .= __("Visit ", WPI) . "<a href='admin.php?page=wpi_page_settings'>".__('settings page', WPI)."</a>" . __(" to configure.", WPI);
    }

    if (!function_exists('curl_exec'))
      $message .= __("cURL is not turned on on your server, credit card processing will not work. If you have access to your php.ini file, activate <b>extension=php_curl.dll</b>.", WPI);

    WPI_UI::error_message($message);
  }

  function settings_action() {

    if(isset($_REQUEST['wpi_settings']) ) {

      if ($_REQUEST['page'] == 'wpi_page_settings') {
        unset($_REQUEST);
        wp_redirect(admin_url("admin.php?page=wpi_page_settings&message=updated"));
        exit;
      }

    }

  }

  /**
    Handles saving and updating
    Can also handle AJAX save/update function
   */
  function save_invoice($invoice, $args = '') {
    //die( json_encode($invoice) );

    /* Set function additional params */
    $defaults = array(
        'type' => 'default'
    );
    extract(wp_parse_args($args, $defaults), EXTR_SKIP);

    if ($type != 'import') {
      if (!wp_verify_nonce($_REQUEST['nonce'], 'wpi-update-invoice')) {
        die('Security check');
      }
    }

    /* Init New Invoice object from passed variables */
    $ni = new WPI_Invoice();

    $ni->set("ID={$invoice['ID']}");
    $ni->set("invoice_id={$invoice['invoice_id']}");

    //$ni->set("terms_acceptance_required={$invoice['terms_acceptance_required']}");

    $ni->set("subject={$invoice['subject']}");
    $ni->set("description={$invoice['description']}");

    //$ni->set("watermark={$invoice['meta']['watermark']}");

    if ($invoice['deposit'] == 'on' || $invoice['deposit'] == 'true') {
      $ni->set("deposit_amount={$invoice['deposit_amount']}");
    } else {
      $ni->set("deposit_amount=0");
    }

    $ni->set("due_date_year={$invoice['due_date_year']}");
    $ni->set("due_date_month={$invoice['due_date_month']}");
    $ni->set("due_date_day={$invoice['due_date_day']}");

    $ni->set("default_currency_code={$invoice['default_currency_code']}");

    if (!empty($invoice['meta']['terms'])) {
      $ni->set("terms={$invoice['meta']['terms']}");
    }
    $ni->set("tax={$invoice['meta']['tax']}");

    $ni->set("custom_id={$invoice['meta']['custom_id']}");

    /**
     * DETECTING INVOICE TYPE
     * (Changes for ability to use premium feature Quotes)
     *
     * @author Anton Korotkov
     *
     * There are three available types by default:
     *    - invoice
     *    - recurring
     */
    // 'invoice' is by default
    $invoice_type = 'invoice';

    // If $invoice object has type definition then use it
    if ( !empty( $invoice['type'] ) ) {
      $invoice_type = $invoice['type'];
    }

    // Save status of invoice (quote or not quote)
    if(isset ($invoice['quote'])) {
      if($invoice['quote'] == "on") {
        $ni->set("status=quote");
        $ni->set("is_quote=true");
        $invoice_type = 'quote';
      } else {
        $ni->set("status=null");
      }
    }

    // But if recurring settings are defined then invoice type should be recurring
    if ($invoice['recurring']['active'] == 'on' && !empty($invoice['recurring']['cycles'])) {
      $ni->create_schedule("unit={$invoice['recurring']['unit']}&length={$invoice['recurring']['length']}&cycles={$invoice['recurring']['cycles']}&send_invoice_automatically={$invoice['recurring']['send_invoice_automatically']}&start_date[month]={$invoice['recurring']['start_date']['month']}&start_date[day]={$invoice['recurring']['start_date']['day']}&start_date[year]={$invoice['recurring']['start_date']['year']}");
      $invoice_type = 'recurring';
    }

    // Finally set invoice type
    $ni->set("type=$invoice_type");

    /* Set invoice status */
    $status = (!empty($invoice['post_status']) ? $invoice['post_status'] : 'active');
    $ni->set("post_status={$status}");

    /* Add discounts if exist */
    if (is_array($invoice['meta']['discount'])) {
      foreach ($invoice['meta']['discount'] as $discount) {
        if (!empty($discount['name']) && !empty($discount['amount'])) {
          $ni->add_discount("name={$discount['name']}&type={$discount['type']}&amount={$discount['amount']}");
        }
      }
    }

    if (!empty($invoice['client_change_payment_method'])) {
      $ni->set("client_change_payment_method={$invoice['client_change_payment_method']}");
    }
    $ni->set("default_payment_method={$invoice['default_payment_method']}");

    $ni->set("tax_method={$invoice['tax_method']}");

    // It's bad idea to clear log, because all neccessary data such as payment information exist there
    //$ni->admin("clear_log={$invoice['admin']['clear_log']}");

    /* Manually set billing settings due to the complexity of the hierarchy */
    $ni->data['billing'] = !empty($invoice['billing']) ? $invoice['billing'] : array();

    /* Add line items */
    foreach ($invoice['itemized_list'] as $line_item) {
      $ni->line_item("name={$line_item['name']}&description={$line_item['description']}&quantity={$line_item['quantity']}&price={$line_item['price']}&tax_rate={$line_item['tax']}");
    }

    /* Add line items for charges */
    if (!empty($invoice['itemized_charges'])) {
      foreach ($invoice['itemized_charges'] as $charge_item) {
        $ni->line_charge("name={$charge_item['name']}&amount={$charge_item['amount']}&tax={$charge_item['tax']}");
      }
    }

    /*
     * Save Invoice Object to DB and update user
     * (trimming is a precaution because it could cause problems in inserted in DB w/ whitespace on end)
     */
    $ni->set("user_email=" . trim($invoice['user_data']['user_email']));

    if ($type != 'import') {
      WPI_Functions::update_user($invoice['user_data']);
    }

    $invoice_id = $ni->save_invoice();
    if ($invoice_id) {
      return $invoice_id;
    } else {
      return false;
    }
  }

  function SendNotificationInvoice() {

    $ni = new WPI_Invoice();
    $ni->SendNotificationLog($_REQUEST);
  }

  /**
   * It's a callback function. It calls on a option "wpi_options" changes
   *
   * @param mixed $new_value
   * @param mixed $old_value (do not used)
   * @return $new_value
   * @author odokienko@UD
   */
  function pre_update_option_wpi_options($new_value,$old_value){
    global $wpdb;


    $default_currency_code = $new_value['currency']["default_currency_code"];
    $protected_currencies = array();

    /* check for curency with default_currency_code*/
    $protected_currencies[] = $default_currency_code;

    /* check for currencies that are already used in invoices */
    $results = $wpdb->get_results("
      SELECT DISTINCT `{$wpdb->prefix}postmeta`.meta_value
      FROM `{$wpdb->posts}`
      JOIN `{$wpdb->prefix}postmeta` ON ( `{$wpdb->posts}`.id = `{$wpdb->prefix}postmeta`.post_id )
      WHERE `{$wpdb->posts}`.post_type = 'wpi_object'
      AND `{$wpdb->prefix}postmeta`.meta_key = 'default_currency_code'
    ");
    foreach($results as $curr_row){
      $protected_currencies[] = $curr_row->meta_value;
    }

    foreach ($protected_currencies as $curr){
      if (empty($new_value['currency']['types'][$curr])){
        $new_value['currency']['types'][$curr] = $old_value['currency']['types'][$curr];
      }
      if (empty($new_value['currency']['symbol'][$curr])){
        $new_value['currency']['symbol'][$curr] = $old_value['currency']['symbol'][$curr];
      }
    }



    foreach ($new_value['currency']['symbol'] as &$symbol){
      $symbol = base64_encode($symbol);
    }


    /**
     * and checking the option "use_wp_crm_to_send_notifications". If it is set to true
     * than retrieves an option 'wp_crm_settings' and check it for containing
     * a default WPI notification templates and add them if necessary
     */
    if(!empty($new_value['use_wp_crm_to_send_notifications'])){

      $wp_crm_settings = get_option('wp_crm_settings');
      $update_needed = false;
      if (empty($wp_crm_settings['notifications']['wpi_send_thank_you_email'])){
        $wp_crm_settings['notifications']['wpi_send_thank_you_email']['subject'] = __('Invoice #[invoice_id] has been paid', 'wp_crm');
        $wp_crm_settings['notifications']['wpi_send_thank_you_email']['to'] = '[user_email]';
        $wp_crm_settings['notifications']['wpi_send_thank_you_email']['send_from'] = '[business_name] <[from]>';
        $wp_crm_settings['notifications']['wpi_send_thank_you_email']['message'] = __("Dear [user_name],\n[business_name] has received your payment for the invoice.\n\nYou can overview invoice status and payment history by clicking this link:\n[permalink]\n\nThank you very much for your patronage.\n\nBest regards,\n[business_name] ([from])", 'wp_crm');
        $wp_crm_settings['notifications']['wpi_send_thank_you_email']['fire_on_action'] = array('wpi_send_thank_you_email');
        $update_needed = true;
      }
      if(empty($wp_crm_settings['notifications']['wpi_cc_thank_you_email'])){
        $wp_crm_settings['notifications']['wpi_cc_thank_you_email']['subject'] = __('Invoice #[invoice_id] has been paid by [user_name]', 'wp_crm');
        $wp_crm_settings['notifications']['wpi_cc_thank_you_email']['to'] = '[admin_email]';
        $wp_crm_settings['notifications']['wpi_cc_thank_you_email']['send_from'] = '[business_name] <[from]>';
        $wp_crm_settings['notifications']['wpi_cc_thank_you_email']['message'] = __("[user_name] has paid invoice #[invoice_id].\n[invoice_title]\nTotal payments: [default_currency_code] [total_payments] of [default_currency_code] [total].\n\nYou can overview invoice status and payment history by clicking this link:\n[permalink]\n\nUser information:\n\nID: [user_id]\nName: [user_name]\nEmail: [user_email]\n\n--------------------\n[site]", 'wp_crm');
        $wp_crm_settings['notifications']['wpi_cc_thank_you_email']['fire_on_action'] = array('wpi_cc_thank_you_email');
        $update_needed = true;
      }
      if(empty($wp_crm_settings['notifications']['wpi_send_invoice_creator_email'])){
        $wp_crm_settings['notifications']['wpi_send_invoice_creator_email']['subject'] = __('Invoice #[invoice_id] has been paid by [user_name]', 'wp_crm');
        $wp_crm_settings['notifications']['wpi_send_invoice_creator_email']['to'] = '[creator_email]';
        $wp_crm_settings['notifications']['wpi_send_invoice_creator_email']['send_from'] = '[business_name] <[from]>';
        $wp_crm_settings['notifications']['wpi_send_invoice_creator_email']['message'] = __("Dear [creator_name],\n[user_name] has paid invoice #[invoice_id].\n\n[invoice_title]\nTotal payments: [default_currency_code] [total_payments] of [default_currency_code] [total].\n\nYou can overview invoice status and payment history by clicking this link:\n[permalink]\n\nUser information:\n\nID: [user_id]\nName: [user_name]\nEmail: [user_email]\n\n--------------------\n[site]", 'wp_crm');
        $wp_crm_settings['notifications']['wpi_send_invoice_creator_email']['fire_on_action'] = array('wpi_send_invoice_creator_email');
        $update_needed = true;
      }
      if($update_needed){
        update_option('wp_crm_settings', $wp_crm_settings);
      }
    }



    return $new_value;
  }


  /**
   * It's a callback function. It calls on a option "wpi_options" get_option
   *
   * @param mixed $new_value
   * @param mixed $old_value (do not used)
   * @return $new_value
   * @author odokienko@UD
   */
  function option_wpi_options($value){

    if (empty($value['currency']['symbol'])) return $value;

    foreach ($value['currency']['symbol'] as $key => $symbol){
      $value['currency']['symbol'][$key] = base64_decode($symbol);
    }
    return $value;
  }

  /**
   * Creates post type.
   *
   * Ran everytime.
   *
   * @since 3.0
   *
   */
  function register_post_type() {
    global $wpdb, $wpi_settings, $wp_properties;

    $wpi_settings['statuses'] = array();

    $labels = array(
        'name' => __('Invoices', WPI),
        'singular_name' => __('Invoice', WPI),
        'add_new' => __('Add New', WPI),
        'add_new_item' => __('Add New Invoice', WPI),
        'edit_item' => __('Edit Invoice', WPI),
        'new_item' => __('New Invoice', WPI),
        'view_item' => __('View Invoice', WPI),
        'search_items' => __('Search Invoices', WPI),
        'not_found' => __('No invoices found', WPI),
        'not_found_in_trash' => __('No invoices found in Trash', WPI),
        'parent_item_colon' => ''
    );


    // Register custom post types
    register_post_type('wpi_object', array(
        'labels' => $labels,
        'singular_label' => __('Invoice', WPI),
        'public' => false,
        'show_ui' => false,
        '_builtin' => false,
        '_edit_link' => $wpi_settings['links']['manage_invoice'] . '&wpi[existing_invoice][invoice_id]=%d',
        'capability_type' => 'post',
        'hierarchical' => false,
        'rewrite' => array('slug' => $wp_properties['configuration']['base_slug']),
        'query_var' => $wp_properties['configuration']['base_slug'],
        'supports' => array('title', 'editor', 'thumbnail'),
        'menu_icon' => WPI_URL . "/core/css/images/wp_invoice.png"
    ));

    register_post_status('archived', array(
        'label' => _x('Archived', 'wpi_object'),
        'public' => false,
        '_builtin' => false,
        'label_count' => _n_noop('Archived <span class="count">(%s)</span>', 'Archived <span class="count">(%s)</span>'),
    ));
    $wpi_settings['statuses'][] = 'archived';

    register_post_status('active', array(
        'label' => _x('Active', 'wpi_object'),
        'public' => false,
        '_builtin' => false,
        'label_count' => _n_noop('Due Invoices <span class="count">(%s)</span>', 'Due Invoices <span class="count">(%s)</span>'),
    ));
    $wpi_settings['statuses'][] = 'active';

    register_post_status('paid', array(
        'label' => _x('Paid', 'wpi_object'),
        'public' => false,
        '_builtin' => false,
        'label_count' => _n_noop('Paid <span class="count">(%s)</span>', 'Paid <span class="count">(%s)</span>'),
    ));
    $wpi_settings['statuses'][] = 'paid';

    register_post_status('trash', array(
        'label' => _x('Trash', 'wpi_object'),
        'public' => false,
        '_builtin' => false,
        'label_count' => _n_noop('Trash  <span class="count">(%s)</span>', 'Trash <span class="count">(%s)</span>'),
    ));
    $wpi_settings['statuses'][] = 'trash';

    register_post_status('pending', array(
        'label' => _x('Pending', 'wpi_object'),
        'public' => false,
        '_builtin' => false,
        'label_count' => _n_noop('Pending  <span class="count">(%s)</span>', 'Pending <span class="count">(%s)</span>'),
    ));
    $wpi_settings['statuses'][] = 'pending';

    register_post_status('refund', array(
        'label' => _x('Refund', 'wpi_object'),
        'public' => false,
        '_builtin' => false,
        'label_count' => _n_noop('Refund  <span class="count">(%s)</span>', 'Refund <span class="count">(%s)</span>'),
    ));
    $wpi_settings['statuses'][] = 'refund';

    do_action('wpi_register_object');
  }

  /**
   * Creates WPI 3.0 Database Schema
   *
   * Creates
   *
   * @uses $wpdb
   * @since 3.0
   *
   */
  function create_new_schema_tables() {
    global $wpdb;

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

    dbDelta("CREATE TABLE {$wpdb->base_prefix}wpi_object_log (
      ID mediumint(9) NOT NULL auto_increment,
      blog_id mediumint(9) NOT NULL,
      object_id mediumint(9) NOT NULL,
      user_id mediumint(9) NOT NULL,
      attribute varchar(255) collate utf8_unicode_ci NOT NULL,
      action varchar(255) collate utf8_unicode_ci NOT NULL,
      value varchar(255) collate utf8_unicode_ci NOT NULL,
      text text collate utf8_unicode_ci NOT NULL,
      time bigint(11) NOT NULL default '0',
      UNIQUE KEY id (ID),
      KEY time (time),
      KEY object_id (object_id),
      KEY user_id (user_id),
      KEY event_type (action)
    ) ");

    WPI_Functions::log("Installation SQL queries ran.");
  }

  /**
   * This function loads our payment gateways
   * @since 3.0
   */
  function load_gateways() {
    global $wpi_settings;

    $default_headers = array(
        'Name' => __('Name', 'wpi_gateway'),
        'Version' => __('Version', 'wpi_gateway'),
        'Description' => __('Description', 'wpi_gateway')
    );

    if (!is_dir(WPI_Gateways_Path)) {
      return;
    }

    if ($premium_dir = opendir(WPI_Gateways_Path)) {

      if(file_exists(WPI_Gateways_Path . "/index.php")) {
        if(WP_DEBUG) {
          include_once(WPI_Gateways_Path . "/index.php");
        } else {
          @include_once(WPI_Gateways_Path . "/index.php");
        }
      }

      while (false !== ($file = readdir($premium_dir))) {
        if ($file == 'index.php')
          continue;

        if (end(explode(".", $file)) == 'php') {
          $slug = str_replace(array('.php'), '', $file);
          if (substr($slug, 0, 6) == "class_") {
            $t = split("class_", $slug);
            $slug = $t[1];
          }

          $plugin_data = @get_file_data(WPI_Gateways_Path . "/" . $file, $default_headers, 'plugin');
          $wpi_settings['installed_gateways'][$slug]['name'] = $plugin_data['Name'];
          $wpi_settings['installed_gateways'][$slug]['version'] = $plugin_data['Version'];
          $wpi_settings['installed_gateways'][$slug]['description'] = $plugin_data['Description'];

          if(WP_DEBUG) {
            include_once(WPI_Gateways_Path . "/" . $file);
          } else {
            @include_once(WPI_Gateways_Path . "/" . $file);
          }

          // Disable plugin if class does not exists - file is empty
          if (!class_exists($slug)) {
            unset($wpi_settings['installed_gateways'][$slug]);
          } else {
            /** Initialize the object, then update the billing permissions to show whats in the object */
            eval("\$wpi_settings['installed_gateways']['" . $slug . "']['object'] = new " . $slug . "();");
          }
        }
      }

      /** Sync our options */
      WPI_Gateway_Base::sync_billing_objects();
    }
  }

  /**
   * Check for premium features and load them
   * @since 3.0
   */
  function load_premium() {
    global $wpi_settings;

    $default_headers = array(
        'Name' => __('Name', WPI),
        'Version' => __('Version', WPI),
        'Description' => __('Description', WPI),
        'Minimum Core Version' => __('Minimum Core Version', WPI)
    );

    $wpi_settings['installed_features'] = array();

    if (!is_dir(WPI_Premium))
      return;

    if ($premium_dir = opendir(WPI_Premium)) {

      if (file_exists(WPI_Premium . "/index.php"))
        @include_once(WPI_Premium . "/index.php");

      while (false !== ($file = readdir($premium_dir))) {
        if ($file == 'index.php')
          continue;

        if (end(@explode(".", $file)) == 'php') {

          $plugin_slug = str_replace(array('.php'), '', $file);
          if (substr($plugin_slug, 0, 6) == "class_") {
            $t = split("class_", $plugin_slug);
            $plugin_slug = $t[1];
          }

          $plugin_data = @get_file_data(WPI_Premium . "/" . $file, $default_headers, 'plugin');
          $wpi_settings['installed_features'][$plugin_slug]['name'] = $plugin_data['Name'];
          $wpi_settings['installed_features'][$plugin_slug]['version'] = $plugin_data['Version'];
          $wpi_settings['installed_features'][$plugin_slug]['description'] = $plugin_data['Description'];

          if($plugin_data['Minimum Core Version']) {
            $wpi_settings['installed_features'][$plugin_slug]['minimum_wpi_version'] = $plugin_data['Minimum Core Version'];
          }

          //** If feature has a Minimum Core Version and it is more than current version - we do not load **/
          $feature_requires_upgrade = (!empty($wpi_settings['installed_features'][$plugin_slug]['minimum_wpi_version']) && (version_compare(WP_INVOICE_VERSION_NUM, $wpi_settings['installed_features'][$plugin_slug]['minimum_wpi_version']) < 0) ? true : false);

          if($feature_requires_upgrade) {
            //** Disable feature if it requires a higher WPI version**/
            $wpi_settings['installed_features'][$plugin_slug]['disabled'] = 'true';
            $wpi_settings['installed_features'][$plugin_slug]['needs_higher_wpi_version'] = 'true';
          } else {
            $wpi_settings['installed_features'][$plugin_slug]['needs_higher_wpi_version'] = 'false';
						//$wpi_settings['installed_features'][$plugin_slug]['disabled'] = 'false';
          }

          // Check if the plugin is disabled
          if (empty($wpi_settings['installed_features'][$plugin_slug]['disabled'])) {
            $wpi_settings['installed_features'][$plugin_slug]['disabled'] = 'false';
          }
          if ($wpi_settings['installed_features'][$plugin_slug]['disabled'] != 'true') {

            include_once(WPI_Premium . "/" . $file);

            // Disable plugin if class does not exists - file is empty
            if (!class_exists($plugin_slug))
              unset($wpi_settings['installed_features'][$plugin_slug]);
            else
              $wpi_settings['installed_features'][$plugin_slug]['disabled'] = 'false';
          } else {
            // Feature not loaded because it is disabled
          }
        }
      }
    }
  }

  /**
   * Run manually when a version mismatch is detected.
   *
   * Holds official current version designation.
   * Called in admin_init hook.
   *
  **/
  function manual_activation() {

    $installed_ver = get_option( "wp_invoice_version" );
    $wpi_version = WP_INVOICE_VERSION_NUM;

    if(@version_compare($installed_ver, $wpi_version) == '-1') {
      //** We are upgrading */

      //** Update option to latest version so this isn't run on next admin page load */
      update_option( "wp_invoice_version", $wpi_version );

      //** Try to create new schema tables */
      WPI_Functions::create_new_schema_tables();

      //** Get premium features on activation */
      WPI_Functions::check_for_premium_features();

    }

    return;

  }

  /**
   * Checks for, and downloads, any premium features from TCT servers
   *
   * @uses $wpdb
   * @since 3.0
   *
   */
  function check_for_premium_features($return = false) {
    global $wpi_settings;

    $blogname = get_bloginfo('url');
    $blogname = urlencode(str_replace(array('http://', 'https://'), '', $blogname));
    $system = 'wpi';
    $wpi_version = WP_INVOICE_VERSION_NUM;

    $api_key = WPI_Functions::get_api_key(array('force_check' => true, 'return' => true));

    if(empty($api_key) || strlen($api_key) != 40) {
      if($return) {
        if(empty($api_key)) {
          $api_key = __("The API key could not be generated.", WPI);
        }
        return sprintf(__('An error occured during premium feature check: <b>%s</b>.',WPI), $api_key);
      } else {
        return;
      }
    }

    $check_url = "http://updates.usabilitydynamics.com/?system={$system}&site={$blogname}&system_version={$wpi_version}&api_key={$api_key}";

    $response = @wp_remote_get($check_url);

    if (!$response) {
      return;
    }

    // Check for errors
    if (is_object($response) && !empty($response->errors)) {

      foreach ($response->errors as $update_errrors) {
        $error_string .= implode(",", $update_errrors);
        WPI_Functions::log("Feature Update Error: " . $error_string);
      }

      if ($return) {
        return sprintf(__('An error occured during premium feature check: <b> %s </b>.', WPI), $error_string);
      }

      return;
    }

    //** Quit if failure */
    if ($response['response']['code'] != '200') {
      return;
    }

    $response = @json_decode($response['body']);

    if (is_object($response->available_features)) {

      $response->available_features = WPI_Functions::objectToArray($response->available_features);

      //** Update the database */
      $wpi_settings = get_option('wpi_options');

      $wpi_settings['available_features'] = WPI_Functions::objectToArray($response->available_features);
      update_option('wpi_options', $wpi_settings);
    } // available_features


    if ($response->features == 'eligible' && $wpi_settings['disable_automatic_feature_update'] != 'true') {

      // Try to create directory if it doesn't exist
      if (!is_dir(WPI_Premium)) {
        @mkdir(WPI_Premium, 0755);
      }

      // If didn't work, we quit
      if (!is_dir(WPI_Premium)) {
        return;
      }

      // Save code
      if (is_object($response->code)) {
        foreach ($response->code as $code) {

          $filename = $code->filename;
          $php_code = $code->code;
          $version = $code->version;

          //** Check version */

          $default_headers = array(
              'Name' => __('Feature Name', WPI),
              'Version' => __('Version', WPI),
              'Description' => __('Description', WPI)
          );

          $current_file = @get_file_data(WPI_Premium . "/" . $filename, $default_headers, 'plugin');

          if (@version_compare($current_file[Version], $version) == '-1') {
            $this_file = WPI_Premium . "/" . $filename;
            $fh = @fopen($this_file, 'w');
            if ($fh) {
              fwrite($fh, $php_code);
              fclose($fh);

              if ($current_file[Version]) {
                //UD_F::log(sprintf(__('WP-Invoice Premium Feature: %s updated to version %s from %s.', WPI), $code->name, $version, $current_file[Version]));
              } else {
                //UD_F::log(sprintf(__('WP-Invoice Premium Feature: %s updated to version %s.', WPI), $code->name, $version));
              }

              $updated_features[] = $code->name;
            }
          } else {

          }
        }
      }
    }

    // Update settings
    //WPI_Functions::settings_action(true);

    if ($return && $wpi_settings['disable_automatic_feature_update'] == 'true') {
      return __('Update ran successfully but no features were downloaded because the setting is disabled. Enable it in the "Main" tab.', WPI);
    } elseif ($return) {
      return __('Update ran successfully.', WPI);
    }
  }

  /**
   * Check if premium feature is installed or not
   * @param string $slug. Slug of premium feature
   * @return boolean.
   */
  function check_premium($slug) {
    global $wpi_settings;

    if(empty($wpi_settings['installed_features'][$slug]['version'])) {
      return false;
    }

    $file = WPI_Premium . "/" . $slug . ".php";

    $default_headers = array(
      'Name' => __('Name',WPI),
      'Version' => __('Version',WPI),
      'Description' => __('Description',WPI)
    );

    $plugin_data = @get_file_data( $file , $default_headers, 'plugin' );

    if(!is_array($plugin_data) || empty($plugin_data['Version'])) {
      return false;
    }

    return true;
  }

  /**
   * Logs an action
   *
   * @since 3.0
   */
  function log_event($object_id, $attribute, $action, $value, $text = '', $time = false) {
    global $wpdb, $current_user, $blog_id;

    if (!$time) {
      $time = time();
    }

     $wpdb->show_errors();

    $wpdb->insert($wpdb->base_prefix . 'wpi_object_log', array(
      'object_id' => $object_id,
      'user_id' => $current_user->ID,
      'attribute' => $attribute,
      'action' => $action,
      'value' => $value,
      'text' => $text,
      'time' => $time,
      'blog_id' => $blog_id
    ));


    if($wpdb->insert_id) {
      return $wpdb->insert_id;
    } else {
      return false;
    }

  }

  /**
   * Detect browser
   *
   * @global bool $is_lynx
   * @global bool $is_gecko
   * @global bool $is_IE
   * @global bool $is_opera
   * @global bool $is_NS4
   * @global bool $is_safari
   * @global bool $is_chrome
   * @global bool $is_iphone
   *
   * @author korotkov@ud
   * @return array
   */
  function browser() {
    global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone;

    if ($is_lynx)
      $classes['name'] = 'lynx';
    elseif ($is_gecko)
      $classes['name'] = 'gecko';
    elseif ($is_opera)
      $classes['name'] = 'opera';
    elseif ($is_NS4)
      $classes['name'] = 'ns4';
    elseif ($is_safari)
      $classes['name'] = 'safari';
    elseif ($is_chrome)
      $classes['name'] = 'chrome';

    elseif ($is_IE) {
      $classes['name'] = 'ie';
      if (preg_match('/MSIE ([0-9]+)([a-zA-Z0-9.]+)/', $_SERVER['HTTP_USER_AGENT'], $browser_version))
        $classes['version'] = $browser_version[1];
    } else {
      $classes['name'] = 'unknown';
    }
    if ($is_iphone) {
      $classes['name'] = 'iphone';
    }
    if (stristr($_SERVER['HTTP_USER_AGENT'], "mac")) {
      $classes['sys'] = 'osx';
    } elseif (stristr($_SERVER['HTTP_USER_AGENT'], "linux")) {
      $classes['sys'] = 'linux';
    } elseif (stristr($_SERVER['HTTP_USER_AGENT'], "windows")) {
      $classes['sys'] = 'windows';
    }
    return $classes;
  }

  /**
   * Revalidate all the invoices
   *
   * @author korotkov@ud
   * @global object $wpdb
   */
  function total_revalidate() {
    global $wpdb;

    /** Recalculate all invoices */
    $invoices = $wpdb->get_col("
      SELECT ID
      FROM {$wpdb->posts}
      WHERE post_type = 'wpi_object'
    ");

    foreach ($invoices as $post_id) {
      $invoice_id = wpi_post_id_to_invoice_id($post_id);
      $this_invoice = new WPI_Invoice();
      $this_invoice->load_invoice("id={$invoice_id}");
      $this_invoice->save_invoice();
    }
  }

  /**
   * Returns WP-CRM attributes list
   *
   * @global object $wp_crm
   * @return array
   * @author korotkov@ud
   */
  function get_wpi_crm_attributes() {
    /** If WP-CRM not installed */
    if ( !class_exists('WP_CRM_Core') ) return;

    global $wp_crm;

    $attributes = array();
    if ( !empty( $wp_crm['data_structure']['attributes'] ) ) {
      foreach( $wp_crm['data_structure']['attributes'] as $slug => $attribute ) {
        if ( !empty( $attribute['wp_invoice'] ) && $attribute['wp_invoice'] == 'true' ) {
          $attributes[ $slug ] = $attribute;
        }
      }
    }

    return $attributes;
  }

  /**
   * WP-CRM custom fields procces filter
   *
   * @param array $current_fields
   * @param string $name
   * @return array
   * @author korotkov@ud
   */
  function wpi_crm_custom_fields( $current_fields, $name ) {
    $attributes = self::get_wpi_crm_attributes();
    if ( empty( $attributes ) ) return $current_fields;

    foreach( $attributes as $attr_key => $attr_value ) {
      $current_fields['customer_information'][ $attr_key ] = array(
        'type'  => 'text',
        'class' => 'text-input',
        'name'  => $name.'['.$attr_key.']',
        'label' => __( $attr_value['title'], WPI )
      );
    }

    return $current_fields;
  }


  /**
   * Filter CRM actions list
   * @param array $current
   * @author odokienko@UD
   * @return array
   */
  function wpi_crm_custom_notification($current) {

    foreach( WPI_Core::$crm_notification_actions as $action_key => $action_name ) {
      $current[$action_key] = $action_name;
    }

    return $current;
  }

     /**
   * Create label for user activity stream attribute
   *
   * @version 1.0
   * @author odokienko@UD
   */
  function wp_crm_entry_type_label($attr,$entity) {
    global $wp_crm;
    switch ($attr){
      case "wpi_notification":
        $attr = __("WP-Invoice Notification");
        break;
    }

    return $attr;
  }

  /**
   * Detects if at least one PF is installed
   *
   * @global array $wpi_settings
   * @return bool
   * @author korotkov@ud
   */
  static function has_installed_premium_features() {
    global $wpi_settings;

    if ( empty( $wpi_settings['installed_features'] ) ) return false;

    foreach ( $wpi_settings['available_features'] as $feature_key => $feature ) {
      if ( array_key_exists( $feature_key, $wpi_settings['installed_features'] ) && class_exists( $feature_key ) ) {
        return true;
      }
    }

    return false;
  }

  /**
   * Changing of Mail From for Notifications.
   *
   * @global array $wpi_settings
   * @return string
   */
  function notification_mail_from() {
    global $wpi_settings;

    $email = empty( $wpi_settings['mail_from_user_email'] ) ? "wordpress@".strtolower($_SERVER['SERVER_NAME']) : $wpi_settings['mail_from_user_email'];

    return $email;
  }

  /**
   * Changing of Mail From Name for Notifications.
   *
   * @global array $wpi_settings
   * @return type
   */
  function notification_mail_from_name() {
    global $wpi_settings;

    $sendername = empty( $wpi_settings['mail_from_sender_name'] ) ? "WordPress" : stripslashes($wpi_settings['mail_from_sender_name']);

    return $sendername;
  }

  /**
   * Promotional links notice
   *
   * @global type $wp_properties
   * @author korotkov@ud
   */
  function promotional_notice() {
    global $wpi_settings;

    $hour = 3600;
    $day = 24*$hour;

    $show_after = 2*$day;
    $activation_date = (int)get_option( 'wpi_activation_time' );
    $now = time();

    if ( empty( $wpi_settings['installed_features'] ) && $now - $activation_date > $show_after ) {
      $screen = get_current_screen();

      if ( $screen->id == 'invoice_page_wpi_page_settings' ) :
        ?>
        <div class="updated <?php wpp_css( 'admin_notice::promotional_notice', 'wpi_promotional_notice' ) ?>">
          <div class="<?php wpp_css( 'admin_notice::promotional_notice::top', 'wpi_promotional_notice_top_line' ) ?>">
            <?php echo sprintf( __('Find out how to <a target="_blank" href="%s">Extend</a> your <a target="_blank" href="%s">WP-Invoice</a> plugin', WPI), 'https://usabilitydynamics.com/products/wp-invoice/premium-features/', 'https://usabilitydynamics.com/products/wp-invoice/' ); ?>
          </div>
          <div class="<?php wpp_css( 'admin_notice::promotional_notice::bottom', 'wpi_promotional_notice_bottom_line' ) ?>">
            <a target="_blank" href="https://usabilitydynamics.com/products/wp-invoice/premium-features/"><?php _e( 'Premium Features', WPI ); ?></a>
            |
            <a target="_blank" href="https://usabilitydynamics.com/forums/"><?php _e( 'Support Forum', WPI ); ?></a>
            |
            <a target="_blank" href="https://usabilitydynamics.com/products/wp-invoice/#documentation-tutorials"><?php _e( 'User Guide', WPI ); ?></a>
          </div>
        </div>
        <?php
      endif;
    }
  }
}

/**
 * Draw users dropdown list
 *
 * @global object $wpdb
 * @param string $post_type
 * @param string $select_name
 * @param bool $return_users
 * @return bool|nothing
 * @author korotkov@ud
 */
function wpi_invoice_users_dropdown($post_type, $select_name, $return_users=false) {
  global $wpdb;

  switch ($post_type) {
    case 'wpi_object':
      $results = $wpdb->get_results($wpdb->prepare("
        SELECT u.ID, pm.meta_value
        FROM {$wpdb->posts} AS p
        JOIN {$wpdb->prefix}postmeta AS pm ON pm.post_id = p.ID AND pm.meta_key = 'user_email'
        JOIN {$wpdb->users} AS u ON u.user_email = pm.meta_value
        WHERE post_type= %s
        ", $post_type), ARRAY_N);
      break;
  }

  if (empty($results)) {
    return false;
  }

  $users = array();
  foreach ($results as $result) {
    $users[] = $result[0];
  }

  if ($return_users)
    return $users;

  $selected = isset($_GET['recipient']) ? (int) $_GET['recipient'] : 0;

  if (!empty($users)) {
    wp_dropdown_users(
      array(
        'include' => $users,
        'show_option_all' => __('Show all users', WPI),
        'selected' => $selected,
        'name' => $select_name
      )
    );
  }
}

/**
 * Mark invoice as Paid
 *
 * @param int $invoice_id
 * @param bool $check_balance
 * @return bool
 * @author korotkov@ud
 */
function wp_invoice_mark_as_paid($invoice_id, $check_balance=false) {
  if ($check_balance) {
    if (wpi_is_full_paid_invoice($invoice_id)) {
      $post_id = wpi_invoice_id_to_post_id($invoice_id);
      wp_update_post(
        array(
          'ID' => $post_id,
          'post_status' => 'paid'
        )
      );
      WPI_Functions::log_event($post_id, 'invoice', 'update', '', __('Payment status: Complete', WPI));
      return true;
    } else {
      $post_id = wpi_invoice_id_to_post_id($invoice_id);
      wp_update_post(
        array(
          'ID' => $post_id,
          'post_status' => 'active'
        )
      );
      return true;
    }
  } else {
    $post_id = wpi_invoice_id_to_post_id($invoice_id);
    wp_update_post(
      array(
        'ID' => $post_id,
        'post_status' => 'paid'
      )
    );
    WPI_Functions::log_event($post_id, 'invoice', 'update', '', __('Payment status: Complete', WPI));
    return true;
  }
}

/**
 * Mark invoice as Pending (for PayPal IPN)
 *
 * @param int $invoice_id
 * @author korotkov@ud
 */
function wp_invoice_mark_as_pending($invoice_id) {
  $post_id = wpi_invoice_id_to_post_id($invoice_id);

  wp_update_post(
          array(
              'ID' => $post_id,
              'post_status' => 'pending'
          )
  );

	/** Mark invoice as processed by IPN (used for trashing abandoned SPC transactions) */
	update_post_meta($post_id, 'processed_by_ipn', 'true');
  WPI_Functions::log_event($post_id, 'invoice', 'update', '', __('Pending', WPI));
}

/**
 * Determine if invoice is paid full
 *
 * @global object $wpdb
 * @param int $invoice_id
 * @return bool
 * @author korotkov@ud
 */
function wpi_is_full_paid_invoice($invoice_id) {
  global $wpdb;

  $invoice_obj = new WPI_Invoice();
  $invoice_obj->load_invoice("id={$invoice_id}");

  $object_id = wpi_invoice_id_to_post_id($invoice_id);
  $payment_history = $wpdb->get_results("SELECT * FROM {$wpdb->base_prefix}wpi_object_log WHERE object_id = '{$object_id}' AND action = 'add_payment'", ARRAY_A);
  $paid_amount = 0;

  foreach ($payment_history as $payment) {
    $paid_amount += abs($payment['value']);
  }

  return $paid_amount >= ( $invoice_obj->data['subtotal'] - $invoice_obj->data['total_discount'] );
}

/**
 * Formates amount
 *
 * @param number $amount
 * @return string
 */
function wp_invoice_currency_format($amount) {
  global $wpi_settings;

  $thousands_separator_symbol = !isset( $wpi_settings['thousands_separator_symbol'] )?',':($wpi_settings['thousands_separator_symbol'] == '0'?'':$wpi_settings['thousands_separator_symbol']);

  if ($amount) {
    return number_format($amount, 2, '.', $thousands_separator_symbol);
  } else {
    return $amount;
  }
}

/**
 * Emails user after payment is done
 *
 * @param array $invoice
 * @author korotkov@ud
 * @refactoring odokienko@UD
 */
function wp_invoice_send_email_receipt($invoice,$notification_data) {
  global $wpi_settings;

  $subject = sprintf(__("Invoice #%s has been paid", WPI), $notification_data['invoice_id']);
  $headers = array(
      "From: {$notification_data['business_name']} <{$notification_data['from']}>\r\n",
      "Content-Type: text/html"
  );
  $message = sprintf(
    __("Dear %1s,<br>%2s has received your payment for the invoice.<br><br>You can overview invoice status and payment history by clicking this link:<br>%3s<br><br>Thank you very much for your patronage.<br><br>Best regards,<br>%4s (%5s)", WPI),
    $notification_data['user_name'],
    $notification_data['business_name'],
    $notification_data['permalink'],
    $notification_data['business_name'],
    $notification_data['from']
  );

  /**
   * @todo add condition witch will be look at this option odokienko@UD */
  if ( function_exists('wp_crm_send_notification') && !empty($wpi_settings['use_wp_crm_to_send_notifications']) && $wpi_settings['use_wp_crm_to_send_notifications'] == 'true') {
    wp_crm_send_notification( 'wpi_send_thank_you_email', $notification_data );
    //** Add message to user activity stream */
    wp_crm_add_to_user_log( $notification_data['user_id'], sprintf(__("WP-Invoice: Message with subject '%1s' was sent", WPI),$subject),false,array('attribute'=>'wpi_notification'));
  }else{
    $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
    $subject = html_entity_decode($subject, ENT_QUOTES, 'UTF-8');


    if (wp_mail("{$notification_data['user_name']} <{$notification_data['user_email']}>", $subject, $message, implode("\r\n",(array)$headers) . "\r\n")) {
      WPI_Functions::log_event($notification_data['invoice_id'], 'invoice', 'emailed', '', __('Receipt eMailed', WPI));
    }
  }

  return $message;
}

/**
 * Emails merchant after payment is done
 *
 * @global array $wpi_settings
 * @param array $invoice
 * @author korotkov@UD
 *
 * @refactoring odokienko@UD
 */
function wp_invoice_send_me_notification($invoice,$notification_data) {
  global $wpi_settings;
  $headers = array(
      "From: {$notification_data['business_name']} <{$notification_data['from']}>\r\n",
      "Content-Type: text/html"
  );
  $subject = sprintf(__("Invoice #%s has been paid", WPI), $notification_data['invoice_id']);

  $message = sprintf(
    __("%1s has paid invoice #%2s.<br><br>%3s<br>Total payments: %4s %5s of %6s %7s.<br><br>You can overview invoice status and payment history by clicking this link:<br>%8s<br><br>User information:<br><br>ID: %9s<br>Name: %10s<br>Email: %11s<br><br>--------------------<br>%12s", WPI),
    $notification_data['user_name'],
    $notification_data['invoice_id'],
    $notification_data['invoice_title'],
    $notification_data['default_currency_code'],
    $notification_data['total_payments'],
    $notification_data['default_currency_code'],
    $notification_data['total'],
    $notification_data['permalink'],
    $notification_data['user_id'],
    $notification_data['user_name'],
    $notification_data['user_email'],
    $notification_data['site']
  );

  if ( function_exists('wp_crm_send_notification') && !empty($wpi_settings['use_wp_crm_to_send_notifications']) && $wpi_settings['use_wp_crm_to_send_notifications'] == 'true') {
    wp_crm_send_notification( 'wpi_cc_thank_you_email', $notification_data );
    //** Add message to user activity stream */
    wp_crm_add_to_user_log( $notification_data['admin_id'], sprintf(__("WP-Invoice: Message with subject '%1s' was sent", WPI),$subject),false,array('attribute'=>'wpi_notification'));

  }else{

    $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
    $subject = html_entity_decode($subject, ENT_QUOTES, 'UTF-8');

    wp_mail("{$notification_data['admin_name']} <{$notification_data['admin_email']}>", $subject, $message,  implode("\r\n",(array)$headers) . "\r\n");
  }
}


/**
 * Sends notification to invoice creator
 *
 * @global array $wpi_settings
 * @param array $invoice
 * @author korotkov@UD
 *
 * @refactoring odokienko@UD
 */
function wp_invoice_send_creator_notification($invoice,$notification_data) {
  global $wpi_settings;
  $headers = array(
      "From: {$notification_data['business_name']} <{$notification_data['from']}>\r\n",
      "Content-Type: text/html"
  );
  $subject = sprintf(__("Invoice #%s has been paid", WPI), $notification_data['invoice_id']);
  $message = sprintf(
    __("Hello %1s,<br><br>%2s has paid invoice #%3s.<br><br>%4s<br>Total payments: %5s %6s of %7s %8s.<br><br>You can overview invoice status and payment history by clicking this link:<br>%9s<br><br>User information:<br><br>ID: %10s<br>Name: %11s<br>Email: %12s<br><br>--------------------<br>%13s", WPI),
    $notification_data['creator_name'],
    $notification_data['user_name'],
    $notification_data['invoice_id'],
    $notification_data['invoice_title'],
    $notification_data['default_currency_code'],
    $notification_data['total_payments'],
    $notification_data['default_currency_code'],
    $notification_data['total'],
    $notification_data['permalink'],
    $notification_data['user_id'],
    $notification_data['user_name'],
    $notification_data['user_email'],
    $notification_data['site']
  );
  if ( function_exists('wp_crm_send_notification') && !empty($wpi_settings['use_wp_crm_to_send_notifications']) && $wpi_settings['use_wp_crm_to_send_notifications'] == 'true'  ) {
    wp_crm_send_notification( 'wpi_send_invoice_creator_email', $notification_data );
    //** Add message to user activity stream */
    wp_crm_add_to_user_log( $notification_data['creator_id'], sprintf(__("WP-Invoice: Message with subject '%1s' was sent", WPI),$subject),false,array('attribute'=>'wpi_notification'));
  }else{
    $message = html_entity_decode($message, ENT_QUOTES, 'UTF-8');
    $subject = html_entity_decode($subject, ENT_QUOTES, 'UTF-8');
    wp_mail("{$notification_data['creator_name']} <{$notification_data['creator_email']}>", $subject, $message, implode("\r\n",(array)$headers) . "\r\n");
  }
}
/**
 * Sends required notifications
 * @global array $wpi_settings
 * @param array $invoice
 * @author korotkov@UD
 * @refactoring odokienko@UD
 */
function send_notification( $invoice ) {
  global $wpi_settings;

  if ( (!empty($wpi_settings['send_thank_you_email']) && $wpi_settings['send_thank_you_email'] == 'true') ||
       (!empty($wpi_settings['cc_thank_you_email']) && $wpi_settings['cc_thank_you_email'] == 'true') ||
       (!empty($wpi_settings['send_invoice_creator_email']) && $wpi_settings['send_invoice_creator_email'] == 'true' ) ) {

    $paid_invoice = new WPI_Invoice();
    $paid_invoice->load_invoice("id={$invoice['invoice_id']}");
    $invoice = $paid_invoice->data;

    $notification_data['invoice_id'] = (!empty($invoice['custom_id'])) ? $invoice['custom_id'] : $invoice['invoice_id'];
    $notification_data['invoice_title']= $invoice['post_title'];
    $notification_data['from'] = stripslashes(get_option('admin_email'));
    $notification_data['permalink'] = get_invoice_permalink($invoice['invoice_id']);
    $notification_data['business_name'] = $wpi_settings['business_name'];
    $notification_data['site']         = stripslashes($wpi_settings['business_name']);

    $notification_data['user_email'] = $invoice['user_data']['user_email'];
    $notification_data['user_name'] = wpi_get_user_display_name($invoice);
    $notification_data['user_id']      = $invoice['user_data']['ID'];

    $admin = get_user_by_email(get_option('admin_email'));
    $notification_data['admin_email']  = stripslashes( $admin->user_email );
    $notification_data['admin_id']  = $admin->ID;
    $notification_data['admin_name']  = stripslashes( $admin->display_name );

    $creator  = get_userdata( $invoice['post_author'] );
    $notification_data['creator_email']= stripslashes( $creator->user_email );
    $notification_data['creator_name'] = stripslashes( $creator->display_name );
    $notification_data['creator_id'] = $creator->ID ;


    $notification_data['total']        = $invoice['subtotal'] - $invoice['total_discount'] + $invoice['total_tax'];
    $notification_data['default_currency_code'] = $invoice['default_currency_code'];
    $notification_data['total_payments'] = $invoice['total_payments'];

    //** If we are going to change our Mail From */
    if ( !empty($wpi_settings['change_mail_from']) && $wpi_settings['change_mail_from'] == 'true' ) {
      add_filter('wp_mail_from',      array('WPI_Functions', 'notification_mail_from'));
      add_filter('wp_mail_from_name', array('WPI_Functions', 'notification_mail_from_name'));
    }

    /** Email client */
    if (!empty($wpi_settings['send_thank_you_email']) && $wpi_settings['send_thank_you_email'] == 'true') {
      wp_invoice_send_email_receipt($invoice,$notification_data);
    }

    /** Email site admin */
    if (!empty($wpi_settings['cc_thank_you_email']) && $wpi_settings['cc_thank_you_email'] == 'true') {
      wp_invoice_send_me_notification($invoice,$notification_data);
    }

    /** Email invoice creator */
    if ( !empty( $wpi_settings['send_invoice_creator_email'] ) && $wpi_settings['send_invoice_creator_email'] == 'true' ){
      wp_invoice_send_creator_notification($invoice,$notification_data);
    }

    remove_filter('wp_mail_from',      array('WPI_Functions', 'notification_mail_from'));
    remove_filter('wp_mail_from_name', array('WPI_Functions', 'notification_mail_from_name'));

  }

}

/**
 * Returns display_name from invoice if exists or from userdata
 *
 * @param type $invoice
 * @return type
 * @author korotkov@ud
 */
function wpi_get_user_display_name( $invoice ) {
  /** If display name exists, return it */
  if ( !empty( $invoice['user_data']['display_name'] ) ) {
    return $invoice['user_data']['display_name'];
  }

  /** Get current user data and return it */
  $user = get_userdata( $invoice['user_data']['ID'] );
  return $user->display_name;
}

/**
 * This function checks to see if a plugin is installed
 * @param string $slug The class name of the plugin
 * @return bool Whether or not its installed
 * @since 3.0
 */
function wpi_feature_installed($slug) {
  global $wpi_settings;
  if (is_array($wpi_settings['installed_features'][$slug]) && !$wpi_settings['installed_features'][$slug]['disabled']) {
    return true;
  }
  return false;
}

/**
 * Shows business information on front-end
 */
function wp_invoice_show_business_information() {
  $core = WPI_Core::getInstance();
  $business_info['name'] = $core->Settings->options['business_name'];
  $business_info['address'] = $core->Settings->options['business_address'];
  $business_info['phone'] = $core->Settings->options['business_phone'];
  ?>
  <div id="invoice_business_info" class="clearfix">
    <p class="invoice_page_subheading"><strong>Bill From:</strong></p>
    <p class="wp_invoice_bi wp_invoice_business_name"><?php echo $business_info['name']; ?></p>
    <p class="wp_invoice_bi wp_invoice_business_address"><?php echo $business_info['address']; ?></p>
    <p class="wp_invoice_bi wp_invoice_business_phone"><?php echo $business_info['phone']; ?></p>
  </div>
  <?php
}

/**
 * Returns due date in format
 *
 * @param type $invoice
 * @return type
 * @author korotkov@ud
 */
function get_due_date( $invoice ) {

  if ( !empty( $invoice['due_date_year'] ) && !empty( $invoice['due_date_month'] ) && !empty( $invoice['due_date_day'] ) ) {
    return date( get_option('date_format'), strtotime( $invoice['due_date_day'].'-'.$invoice['due_date_month'].'-'.$invoice['due_date_year'] ) );
  }

  return false;

}

/**
 * Find a full diff between two arrays.
 *
 * @param array $array1
 * @param array $array2
 * @return array
 * @author korotkov@ud
 */
function wpi_multi_array_diff($array1, $array2) {
    $ret = array();
    foreach ($array1 as $k => $v) {
        if (!isset($array2[$k])) $ret[$k] = $v;
        else if (is_array($v) && is_array($array2[$k])) {
          $u = wpi_multi_array_diff($v, $array2[$k]);
          if ( !empty($u) ) {
            $ret[$k] = $u;
          }
        } else if ( $v != $array2[$k] ) {
          $ret[$k] = $v;
        }
    }
    return $ret;
}

/**
 * @author korotkov@ud
 * @param array $data
 * <b>Example:</b><br>
 * <pre>
 * array(
 *    'venue' => 'wpi_authorize',
 *    'amount' => '100.00',
 *    'payer_email' => 'john.smith@gmail.com',
 *    'payer_first_name' => 'John',
 *    'payer_last_name' => 'Smith',
 *    'cc_number' => '411111111111111',
 *    'cc_expiration' => '0412',
 *    'cc_code' => '356',
 *    'items' => array(
 *      array(
 *        'name' => 'Name 1',
 *        'description' => 'Item 1',
 *        'quantity' => 1,
 *        'price' => '10.00'
 *      ),
 *      array(
 *        'name' => 'Name 2',
 *        'description' => 'Item 2',
 *        'quantity' => 2,
 *        'price' => '10.00'
 *      )
 *    )
 * )
 * </pre>
 * @return array
 */
function wpi_process_transaction($data) {
  $wpa = new WPI_Payment_Api();
  return $wpa->process_transaction($data);
}
Back to Top