androidmobiles /wp-content/plugins/wordbooker/wordbooker.php

Language PHP Lines 2683
MD5 Hash f7d8dcdcd9b77f9d880434577775b80b Estimated Cost $55,382 (why?)
Repository https://bitbucket.org/MaheshDhaduk/androidmobiles View Raw File View Project SPDX
   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
<?php
/*
Plugin Name: Wordbooker
Plugin URI: http://wordbooker.tty.org.uk
Description: Provides integration between your blog and your Facebook account. Navigate to <a href="options-general.php?page=wordbooker">Settings &rarr; Wordbooker</a> for configuration.
Author: Steve Atty 
Author URI: http://wordbooker.tty.org.uk
Version: 2.0.9
*/

 /*
 *
 *
 * Copyright 2011 Steve Atty (email : posty@tty.org.uk)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 51
 * Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

# Putting this in here to see if it fixed some stupid bug
#require_once('../../wp-includes/pluggable.php'); 


@include("includes/premium.php");
global $table_prefix, $wp_version,$wpdb,$db_prefix,$wbooker_user_id;
$wbooker_user_id=0;

$wordbooker_settings = wordbooker_options(); 
if (! isset($wordbooker_settings['wordbooker_extract_length'])) $wordbooker_settings['wordbooker_extract_length']=256;

define('WORDBOOKER_DEBUG', false);
define('WORDBOOKER_TESTING', false);
define('WORDBOOKER_CODE_RELEASE','2.0.9 - Wake Up and Dance!');

# For Troubleshooting 
define('ADVANCED_DEBUG',false);

#$facebook_config['debug'] = WORDBOOKER_TESTING && !$_POST['action'];
#Wordbooker2 - Dev
#define('WORDBOOKER_FB_APIKEY', '0138375357c1eb1257ed9970ec1a274c');
#define('WORDBOOKER_FB_SECRET', '4310b484ec5236694cfa4b94166aca61');
#define('WORDBOOKER_FB_ID', '111687885534181');

# Wordbooker - live
if (!defined('WORDBOOKER_PREMIUM')) {
define('APP TITLE','Wordbooker');
define('WORDBOOKER_FB_APIKEY', '0cbf13c858237f5d74ef0c32a4db11fd');
define('WORDBOOKER_FB_SECRET', 'df04f22f3239fb75bf787f440e726f31');
define('WORDBOOKER_FB_ID', '254577506873');
define('WORDBOOKER_APPLICATION_NAME','Wordbooker');
define('OPENGRAPH_NAMESPACE','wordbooker');
define('OPENGRAPH_ACCESS_TOKEN','AAAAAO0YAejkBANAjpuFluuIfFnNeOkRBUXps0UqQ9aTBFNAYpOS11f7835w676UOxtyZB4KDekuoS6BXwrs1Y95fDrnAZD');
}

define('WORDBOOKER_FB_APIVERSION', '1.0');
define('WORDBOOKER_FB_DOCPREFIX','http://wiki.developers.facebook.com/index.php/');
define('WORDBOOKER_FB_PUBLISH_STREAM', 'publish_stream');
define('WORDBOOKER_FB_READ_STREAM', 'read_stream');
define('WORDBOOKER_FB_STATUS_UPDATE',"status_update");
define('WORDBOOKER_FB_CREATE_NOTE',"create_note");
define('WORDBOOKER_FB_OFFLINE_ACCESS',"offline_access");
define('WORDBOOKER_FB_MANAGE_PAGES',"manage_pages");
define('WORDBOOKER_FB_PHOTO_UPLOAD',"photo_upload");
define('WORDBOOKER_FB_VIDEO_UPLOAD',"video_upload");
define('WORDBOOKER_FB_READ_FRIENDS',"read_friendlists");
define('WORDBOOKER_SETTINGS', 'wordbooker_settings');
define('WORDBOOKER_OPTION_SCHEMAVERS', 'schema_vers');
define('WORDBOOKER_SCHEMA_VERSION', '2.4');

$new_wb_table_prefix=$wpdb->base_prefix;
if (isset ($db_prefix) ) { $new_wb_table_prefix=$db_prefix;}

define('WORDBOOKER_ERRORLOGS', $new_wb_table_prefix . 'wordbooker_errorlogs');
define('WORDBOOKER_POSTLOGS', $new_wb_table_prefix . 'wordbooker_postlogs');
define('WORDBOOKER_USERDATA', $new_wb_table_prefix . 'wordbooker_userdata');
define('WORDBOOKER_USERSTATUS', $new_wb_table_prefix . 'wordbooker_userstatus');
define('WORDBOOKER_POSTCOMMENTS', $new_wb_table_prefix . 'wordbooker_postcomments');
define('WORDBOOKER_PROCESS_QUEUE', $new_wb_table_prefix . 'wordbooker_process_queue');
define('WORDBOOKER_FB_FRIENDS', $new_wb_table_prefix . 'wordbooker_fb_friends');
define('WORDBOOKER_FB_FRIEND_LISTS', $new_wb_table_prefix . 'wordbooker_fb_friend_lists');

define('WORDBOOKER_MINIMUM_ADMIN_LEVEL', 'edit_posts');	/* Contributor role or above. */
define('WORDBOOKER_SETTINGS_PAGENAME', 'wordbooker');
define('WORDBOOKER_SETTINGS_URL', 'options-general.php?page=' . WORDBOOKER_SETTINGS_PAGENAME);



$wordbooker_wp_version_tuple = explode('.', $wp_version);
define('WORDBOOKER_WP_VERSION', $wordbooker_wp_version_tuple[0] * 10 + $wordbooker_wp_version_tuple[1]);

if (function_exists('json_encode')) {
	define('WORDBOOKER_JSON_ENCODE', 'PHP');
} else {
	define('WORDBOOKER_JSON_ENCODE', 'Wordbook');
}

if (function_exists('json_decode') ) {
	define('WORDBOOKER_JSON_DECODE', 'PHP');
} else {
	define('WORDBOOKER_JSON_DECODE', 'Wordbooker');
}
if (function_exists('simplexml_load_string') ) {
	define('WORDBOOKER_SIMPLEXML', 'provided by PHP');
} else {
	define('WORDBOOKER_SIMPLEXML', 'is missing - this is a problem');
}


function wordbooker_load_apis() {
	if (WORDBOOKER_JSON_DECODE == 'Wordbooker') {
	function json_decode($json)
	{ 
	    $comment = false;
	    $out = '$x=';
	   
	    for ($i=0; $i<strlen($json); $i++)
	    {
		if (!$comment)
		{
		    if ($json[$i] == '{')        $out .= ' array(';
		    else if ($json[$i] == '}')    $out .= ')';
		    else if ($json[$i] == ':')    $out .= '=>';
		    else                         $out .= $json[$i];           
		}
		else $out .= $json[$i];
		if ($json[$i] == '"')    $comment = !$comment;
	    }
	    eval($out . ';');
	    return $x;
	} 
	} 

	if (WORDBOOKER_JSON_ENCODE == 'Wordbook') {
		function json_encode($var) {
			if (is_array($var)) {
				$encoded = '{';
				$first = true;
				foreach ($var as $key => $value) {
					if (!$first) {
						$encoded .= ',';
					} else {
						$first = false;
					}
					$encoded .= "\"$key\":"
						. json_encode($value);
				}
				$encoded .= '}';
				return $encoded;
			}
			if (is_string($var)) {
				return "\"$var\"";
			}
			return $var;
		}
	}
}


/******************************************************************************
 * Wordbook options.
 */

function wordbooker_options() {
	return get_option(WORDBOOKER_SETTINGS);
}

function wordbooker_set_options($options) {
	update_option(WORDBOOKER_SETTINGS, $options);
}

function wordbooker_get_option($key) {
	$options = wordbooker_options();
	return isset($options[$key]) ? $options[$key] : null;
}

function wordbooker_set_option($key, $value) {
	$options = wordbooker_options();
	$options[$key] = $value;	
	wordbooker_set_options($options);
}

function wordbooker_delete_option($key) {
	$options = wordbooker_options();
	unset($options[$key]);
	update_option(WORDBOOKER_SETTINGS, $options);
}


/******************************************************************************
 * DB schema.
 */

function wordbooker_activate() {
	global $wpdb, $table_prefix;
	wp_cache_flush();
	$errors = array();
	$result = $wpdb->query('
		CREATE TABLE IF NOT EXISTS ' . WORDBOOKER_POSTLOGS . '  (
			  `post_id` bigint(20) NOT NULL,
			  `blog_id` bigint(20) NOT NULL,
			  `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
			  PRIMARY KEY  (`blog_id`,`post_id`)
			) DEFAULT CHARSET=utf8;
		');
	if ($result === false)
		$errors[] = __('Failed to create ', 'wordbooker') . WORDBOOKER_POSTLOGS;

	$result = $wpdb->query('
		CREATE TABLE IF NOT EXISTS ' . WORDBOOKER_ERRORLOGS . ' (
			`timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
			  `user_ID` bigint(20) unsigned NOT NULL,
			  `method` longtext NOT NULL,
			  `error_code` int(11) NOT NULL,
			  `error_msg` longtext NOT NULL,
			  `post_id` bigint(20) NOT NULL,
			  `blog_id` bigint(20) NOT NULL,
			   `sequence_id` bigint(20) NOT NULL auto_increment,
		           `diag_level` int(4) default NULL,
		           PRIMARY KEY  (`sequence_id`),
		           KEY `timestamp_idx` (`timestamp`),
		           KEY `blog_idx` (`blog_id`)	
			) DEFAULT CHARSET=utf8;
		');
	if ($result === false)
		$errors[] = __('Failed to create ', 'wordbooker') . WORDBOOKER_ERRORLOGS;

	$result = $wpdb->query('
		CREATE TABLE IF NOT EXISTS ' . WORDBOOKER_USERDATA . ' (
			`user_ID` bigint(20) unsigned NOT NULL,
			  `uid` varchar(80) default NULL,
			  `expires` varchar(80) default NULL,
			  `access_token` varchar(255) default NULL,
			  `sig` varchar(80) default NULL,
			  `use_facebook` tinyint(1) default 1,
			  `onetime_data` longtext,
			  `facebook_error` longtext,
			  `secret` varchar(80) default NULL,
			  `session_key` varchar(80) default NULL,
			  `facebook_id` varchar(40) default NULL,
			  `name` varchar(250) default NULL,
			  `status` varchar(2048) default NULL,
			  `updated` int(20) default NULL,
			  `url` varchar(250) default NULL,
			  `pic` varchar(250) default NULL,
			  `pages` longtext,
			  `auths_needed` int(1) default NULL,
			  `blog_id` bigint(20) default NULL,
			  PRIMARY KEY  (`user_ID`),
			  KEY `facebook_idx` (`facebook_id`)
			) DEFAULT CHARSET=utf8;
		');
	if ($result === false)
		$errors[] = __('Failed to create ', 'wordbooker') . WORDBOOKER_USERDATA;

	$result = $wpdb->query('
		CREATE TABLE IF NOT EXISTS ' . WORDBOOKER_POSTCOMMENTS . ' (
		  `fb_post_id` varchar(40) NOT NULL,
		  `user_id` bigint(20) NOT NULL,
		  `comment_timestamp` int(20) NOT NULL,
		  `wp_post_id` int(11) NOT NULL,
		  `blog_id` bigint(20) NOT NULL,
		  `wp_comment_id` int(20) NOT NULL,
  			PRIMARY KEY  (`blog_id`,`wp_post_id`,`fb_post_id`,`wp_comment_id`)
			)  DEFAULT CHARSET=utf8;
		');
	if ($result === false)
		$errors[] = __('Failed to create ', 'wordbooker') . WORDBOOKER_POSTCOMMENTS;

	$result = $wpdb->query('
		CREATE TABLE IF NOT EXISTS ' . WORDBOOKER_USERSTATUS . ' (
			  `user_ID` bigint(20) unsigned NOT NULL,
			  `name` varchar(250)  default NULL,
			  `status` varchar(2048)  default NULL,
			  `updated` int(20) default NULL,
			  `url` varchar(250)  default NULL,
			  `pic` varchar(250)  default NULL,
			  `blog_id` bigint(20) NOT NULL default 0,
			  `facebook_id` varchar(40) default NULL,
			  PRIMARY KEY  (`user_ID`,`blog_id`)
			)  DEFAULT CHARSET=utf8;
		');
		if ($result === false)

		$errors[] = __('Failed to create ', 'wordbooker') . WORDBOOKER_USERSTATUS;
	$result = $wpdb->query(' CREATE TABLE IF NOT EXISTS ' . WORDBOOKER_FB_FRIENDS . ' (
	  `user_id` int(11) NOT NULL,
	  `blog_id` bigint(20) NOT NULL,
	  `facebook_id` varchar(20) NOT NULL,
	  `name` varchar(200) NOT NULL,
	  PRIMARY KEY  (`user_id`,`facebook_id`,`blog_id`),
	  KEY `user_id_idx` (`user_id`),
	  KEY `fb_id_idx` (`facebook_id`)
	)  DEFAULT CHARSET=utf8;
		');
		if ($result === false)
		$errors[] = __('Failed to create ', 'wordbooker') . WORDBOOKER_FB_FRIENDS;

		$result = $wpdb->query('
			CREATE TABLE IF NOT EXISTS ' . WORDBOOKER_FB_FRIEND_LISTS . ' (
	  `user_id` int(11) NOT NULL,
	  `flid` varchar(80) NOT NULL,
	  `owner` varchar(80) NOT NULL,
	  `name` varchar(240) NOT NULL,
	  PRIMARY KEY  (`user_id`,`flid`)
	)  DEFAULT CHARSET=utf8;

		');
		if ($result === false)
			$errors[] = __('Failed to create ', 'wordbooker') . WORDBOOKER_FB_FRIEND_LISTS;


	$result = $wpdb->query(' CREATE TABLE IF NOT EXISTS ' . WORDBOOKER_PROCESS_QUEUE . ' (
	  `entry_type` varchar(20) NOT NULL,
	  `blog_id` int(11) NOT NULL,
	  `post_id` int(11) NOT NULL,
	  `priority` int(11) NOT NULL,
	  `status` varchar(20) NOT NULL,
	  PRIMARY KEY  (`blog_id`,`post_id`)
	) DEFAULT CHARSET=utf8;
		');
		if ($result === false)
			$errors[] = __('Failed to create ', 'wordbooker') . WORDBOOKER_PROCESS_QUEUE ;

	if ($errors) {
		echo '<div id="message" class="updated fade">' . "\n";
		foreach ($errors as $errormsg) {
			_e("$errormsg<br />\n", 'wordbooker');
		}
		echo "</div>\n";
		#return;
	}
	wordbooker_set_option(WORDBOOKER_OPTION_SCHEMAVERS, 2.4);
	$wordbooker_settings=wordbooker_options();
	#Setup the cron. We clear it first in case someone did a dirty de-install.
	$dummy=wp_clear_scheduled_hook('wb_cron_job');
	$dummy=wp_schedule_event(time(), 'hourly', 'wb_cron_job');
}


function wordbooker_upgrade() {
	global $wpdb, $table_prefix,$blog_id;
	$errors = array();
	#return;
	# We use this to make changes to Schema versions. We need to get the current schema version the user is using and then "upgrade" the various tables.
	$wordbooker_settings=wordbooker_options();
	#	var_dump($wordbooker_settings);
	if (! isset($wordbooker_settings['schema_vers'])) {wordbooker_activate(); return;}
	if ($wordbooker_settings['schema_vers']< (float) WORDBOOKER_SCHEMA_VERSION ) { 
		 _e("Database changes being applied", 'wordbooker');
	} else {
		return;
	}
	

	if ($wordbooker_settings['schema_vers']=='2') {

		$result = $wpdb->query('
		ALTER TABLE '. WORDBOOKER_POSTCOMMENTS. ' DROP PRIMARY KEY , DROP INDEX fb_comment_id, 
		ADD PRIMARY KEY ( `blog_id` , `wp_post_id` , `fb_post_id` , `wp_comment_id` ) 
		');
	# All done, set the schemaversion to version 5. NOT the current version, as this allow us to string updates.
		wordbooker_set_option('schema_vers', "2.1");
	}

	if ($wordbooker_settings['schema_vers']=='2.1') {
		$result = $wpdb->query('
		ALTER TABLE '. WORDBOOKER_POSTCOMMENTS. ' ADD `user_id` BIGINT( 20 ) NOT NULL  
		');
	# All done, set the schemaversion to version 5. NOT the current version, as this allow us to string updates.
		wordbooker_set_option('schema_vers', "2.2");
	}

	if ($wordbooker_settings['schema_vers']=='2.2') {
		$result = $wpdb->query('
		ALTER TABLE '. WORDBOOKER_ERRORLOGS. ' ADD `sequence_id` BIGINT( 20 ) NOT NULL AUTO_INCREMENT , ADD `diag_level` INT(4) NULL, ADD PRIMARY KEY ( `sequence_id` ) 
		');
	# All done, set the schemaversion to version 5. NOT the current version, as this allow us to string updates.
		wordbooker_set_option('schema_vers', "2.3");
	}

	if ($wordbooker_settings['schema_vers']=='2.3') {
		$result = $wpdb->query('
		ALTER TABLE '. WORDBOOKER_ERRORLOGS. ' ADD `sequence_id` BIGINT( 20 ) NOT NULL AUTO_INCREMENT , ADD `diag_level` INT(4) NULL, ADD PRIMARY KEY ( `sequence_id` ) 
		');
	# All done, set the schemaversion to version 5. NOT the current version, as this allow us to string updates.
		wordbooker_set_option('schema_vers', "2.4");
	}

	$dummy=wp_clear_scheduled_hook('wb_cron_job');
	$dummy=wp_schedule_event(time(), 'hourly', 'wb_cron_job');
	wordbooker_set_option('schema_vers', WORDBOOKER_SCHEMA_VERSION );
	wp_cache_flush();
}

function wordbooker_delete_user($user_id,$level) {
	global $wpdb;
	$errors = array();
	$table_array[1]=array(WORDBOOKER_USERDATA);
	$table_array[2]=array(WORDBOOKER_USERDATA,WORDBOOKER_USERSTATUS);
	$table_array[3]=array(WORDBOOKER_USERDATA,WORDBOOKER_USERSTATUS,WORDBOOKER_FB_FRIENDS,WORDBOOKER_FB_FRIEND_LISTS);
	foreach ($table_array[$level] as $tablename) {
		$result = $wpdb->query('DELETE FROM ' . $tablename . ' WHERE user_ID = ' . $user_id . '');
		#var_dump($result);
	}
	if ($errors) {
		echo '<div id="message" class="updated fade">' . "\n";
		foreach ($errors as $errormsg) {
			_e("$errormsg<br />\n", 'wordbooker');
		}
		echo "</div>\n";
	}
}

/******************************************************************************
 * Wordbook user data.
 */
function wordbooker_get_userdata($user_id) {
	global $wpdb;
	$sql='SELECT onetime_data,facebook_error,secret,session_key,user_ID,access_token,facebook_id,pages,name FROM ' . WORDBOOKER_USERDATA . ' WHERE user_ID = ' . $user_id ;
	$rows = $wpdb->get_results($sql);
	if ($rows) {
		$rows[0]->onetime_data = unserialize($rows[0]->onetime_data);
		$rows[0]->facebook_error = unserialize($rows[0]->facebook_error);
		$rows[0]->secret = unserialize($rows[0]->secret);
		$rows[0]->session_key = unserialize($rows[0]->session_key);
		$rows[0]->access_token = unserialize($rows[0]->access_token);
		$rows[0]->pages = unserialize($rows[0]->pages);
		return $rows[0];
	}
	return null;
}

function wordbooker_set_userdata($onetime_data, $facebook_error,$secret, $session,$facebook_id) {
	global $user_ID, $wpdb,$blog_id;
	wordbooker_delete_userdata();
	$result = $wpdb->query("
		INSERT INTO " . WORDBOOKER_USERDATA . " (
			user_ID
			, onetime_data
			, facebook_error
			, secret
			, session_key
			, uid
			, expires
			, access_token
			, sig
			,blog_id
			,facebook_id
		) VALUES (
			" . $user_ID . "
			, '" . serialize($onetime_data) . "'
			, '" . serialize($facebook_error) . "'
			, '" . serialize($secret) . "'
			, '" . serialize($session->session_key)."'
			, '". serialize($session->uid)."'
			, '". serialize($session->expires)."'
			, '". serialize($session->access_token)."'
			, '". serialize($session->sig)."'
			, " . $blog_id . "
			, '". $facebook_id."'
		)
		");
}

function wordbooker_set_userdata2( $onetime_data, $facebook_error, $secret, $session_key,$user_ID) {
	global $wpdb;
	$sql= "Update " . WORDBOOKER_USERDATA . " set
 			  onetime_data =  '" . serialize($onetime_data) . "'
			, facebook_error = '" . serialize($facebook_error) . "'
			, secret = '" . serialize($secret) . "'
			, session_key = '" . serialize($session_key) . "'
		 where user_id=".$user_ID;
	$result = $wpdb->query($sql);
}


function wordbooker_update_userdata($wbuser) {
	return wordbooker_set_userdata2( $wbuser->onetime_data, $wbuser->facebook_error, $wbuser->secret, $wbuser->session_key,$wbuser->user_ID);
}

function wordbooker_set_userdata_facebook_error($wbuser, $method, $error_code, $error_msg, $post_id) {
	$wbuser->facebook_error = array(
		'method' => $method,
		'error_code' => mysql_real_escape_string ($error_code),
		'error_msg' => mysql_real_escape_string ($error_msg),
		'postid' => $post_id,
		);
	wordbooker_update_userdata($wbuser);
	wordbooker_append_to_errorlogs($method, $error_code, $error_msg, $post_id,$wbuser->user_ID);
}

function wordbooker_clear_userdata_facebook_error($wbuser) {
	$wbuser->facebook_error = null;
	return wordbooker_update_userdata($wbuser);
}

function wordbooker_remove_user(){
	global $user_ID;
	# Delete the user's meta
	$wordbooker_user_settings_id="wordbookuser".$blog_id;
	delete_usermeta( $user_ID, $wordbooker_user_settings_id);
	# Then go and delete their data from the tables
	wordbooker_delete_user($user_ID,3);
}

function wordbooker_delete_userdata() {
	global $user_ID;
	wordbooker_delete_user($user_ID,2);
}

/******************************************************************************
 * Post logs - record time of last post to Facebook
 */

function wordbooker_trim_postlogs() {
	# Forget that something has been posted to Facebook if it's been there  more than a year. 
	global $wpdb;
	$result = $wpdb->query('
		DELETE FROM ' . WORDBOOKER_POSTLOGS . '
		WHERE timestamp < DATE_SUB(CURDATE(), INTERVAL 365 DAY)
		');
}

function wordbooker_postlogged($post_id,$tstamp=0) {
	global $wpdb,$wordbooker_post_options,$post;
	$wordbooker_settings = wordbooker_options();
	$wbo=get_post_meta($post_id, '_wordbooker_options', true); 
	#if ($wbo["wordbooker_publish_default"]!='published') {
	$time=time() ;
	if (! isset($wordbooker_settings['wordbooker_republish_time_frame'])) $wordbooker_settings['wordbooker_republish_time_frame']='3';
	$sql='SELECT '. $time ." - UNIX_TIMESTAMP(post_date) as time, post_date_gmt,post_date,post_modified, post_modified_gmt,post_status FROM $wpdb->posts WHERE ID = " . $post_id;
	$rows = $wpdb->get_results($sql);
	
	wordbooker_debugger("Post is this old (Seconds) : ",$rows[0]->time,$post_id) ;
	#wordbooker_debugger("Post date : ",$rows[0]->post_date,$post_id) ;
	#wordbooker_debugger("Post modified : ",$rows[0]->post_modified,$post_id) ;
	#wordbooker_debugger("Post status : ",$rows[0]->post_status,$post_id) ;
	#wordbooker_debugger("Post status flag : ",$wbo['wordbooker_new_post'],$post_id) ;
	#wordbooker_debugger("Scheduled Post: ",$wbo['wordbooker_scheduled_post'],$post_id) ;
	if ($tstamp==1) { return $rows[0]->time;}	
	if ($tstamp==1 && !isset($_POST['original_post_status']) && !isset($_POST['screen'])) {return 0;}
	
	# If the post isn't actually being published we give up - just in case
	if ($rows[0]->post_status!='publish') {	return true;}
	# If the post is new then return false
	if ($rows[0]->post_date == $rows[0]->post_modified) {return false;}
	if ($wbo['wordbooker_scheduled_post']!=0) {
		$wbo['wordbooker_scheduled_post']=0;
		$y=update_post_meta($post_id, '_wordbooker_options', $wbo); 
		return false;
	}
	if ($wbo['wordbooker_new_post']!=0) { 
		$wbo['wordbooker_new_post']=0;
		$y=update_post_meta($post_id, '_wordbooker_options', $wbo); 
		return false;
	}
	#}
	wordbooker_debugger("This post has already been published. So do checks "," ",$post_id) ;
	#if (!isset($_POST['original_post_status']) && !isset($_POST['screen'])) {return false;}
	// See if the user has overridden the repost on edit - i.e. they want to publish and be damned!
	if (isset ($wordbooker_post_options["wordbooker_publish_default"])) { 
		wordbooker_debugger("Publish Post is set so user wants to republish "," ",$post_id) ;
		return false;
	}
	return true;
}


function wordbooker_insert_into_postlogs($post_id,$blog_id) {
	global $wpdb;
	wordbooker_delete_from_postlogs($post_id,$blog_id);
	if (!WORDBOOKER_TESTING) {
		$result = $wpdb->query(' INSERT INTO ' . WORDBOOKER_POSTLOGS . ' (post_id,blog_id) VALUES (' . $post_id . ','.$blog_id.')');
	}
}

function wordbooker_insert_into_process_queue($post_id,$blog_id,$entry_type) {
	global $wpdb;
		$result = $wpdb->query(' INSERT INTO ' . WORDBOOKER_PROCESS_QUEUE . ' (entry_type,blog_id,post_id,status) VALUES ("' . $entry_type. '",' .$blog_id .',' . $post_id . ',"B")');
}

function wordbooker_delete_from_process_queue($post_id,$blog_id) {
	global $wpdb,$blog_id;
		$result = $wpdb->query(' DELETE FROM ' . WORDBOOKER_PROCESS_QUEUE . ' where post_id='.$post_id.' and blog_id='.$blog_id);
}

function wordbooker_delete_from_postlogs($post_id,$blog_id) {
	global $wpdb,$blog_id;
	$result = $wpdb->query('DELETE FROM ' . WORDBOOKER_POSTLOGS . '	WHERE post_id = ' . $post_id . ' and blog_id='.$blog_id);
}

function wordbooker_delete_from_commentlogs($post_id,$blog_id) {
	global $wpdb,$blog_id;
	$result = $wpdb->query('DELETE FROM ' . WORDBOOKER_POSTCOMMENTS . ' WHERE wp_post_id = ' . $post_id . ' and blog_id='.$blog_id);
}

/******************************************************************************
 * Error logs - record errors
 */

function wordbooker_hyperlinked_method($method) {
	return '<a href="'. WORDBOOKER_FB_DOCPREFIX . $method . '"'. ' title="Facebook API documentation" target="facebook"'. '>'. $method. '</a>';
}

function wordbooker_trim_errorlogs() {
		global $user_ID, $wpdb,$blog_id;
	$result = $wpdb->query('
		DELETE FROM ' . WORDBOOKER_ERRORLOGS . '
		WHERE timestamp < DATE_SUB(CURDATE(), INTERVAL 2 DAY)  and blog_id ='.$blog_id);
}

function wordbooker_clear_errorlogs() {
	global $user_ID, $wpdb,$blog_id;
	$result = $wpdb->query('
		DELETE FROM ' . WORDBOOKER_ERRORLOGS . '
		WHERE user_ID = ' . $user_ID . ' and error_code > -1  and blog_id ='.$blog_id);
	if ($result === false) {
		echo '<div id="message" class="updated fade">';
		_e('Failed to clear error logs.', 'wordbooker');
		echo "</div>\n";
	}
}


function wordbooker_clear_diagnosticlogs() {
	global $user_ID, $wpdb,$blog_id;
	$result = $wpdb->query('
		DELETE FROM ' . WORDBOOKER_ERRORLOGS . '
		WHERE blog_id ='.$blog_id);
	if ($result === false) {
		echo '<div id="message" class="updated fade">';
		_e('Failed to clear Diagnostic logs.', 'wordbooker');
		echo "</div>\n";
	}
}
function wordbooker_append_to_errorlogs($method, $error_code, $error_msg,$post_id,$user_id) {
	global $user_ID, $wpdb,$blog_id;
	if ($post_id == null) {
		$post_id = 0;
	} else {
		$post = get_post($post_id);
	}
	$result = $wpdb->insert(WORDBOOKER_ERRORLOGS,
		array('user_ID' => $user_id,
			'method' => $method,
			'error_code' => $error_code,
			'error_msg' => $error_msg,
			'post_id' => $post_id,
			'blog_id' => $blog_id,
			'diag_level'=> 900
			),
		array('%d', '%s', '%d', '%s', '%d','%d')
		);	 
}

function wordbooker_delete_from_errorlogs($post_id) {
	global $wpdb,$blog_id;
	$result = $wpdb->query('DELETE FROM ' . WORDBOOKER_ERRORLOGS . ' WHERE post_id = ' . $post_id .' and blog_id ='.$blog_id );
}

function wordbooker_render_errorlogs() {
	global $user_ID, $wpdb,$blog_id;
	$diaglevel=wordbooker_get_option('wordbooker_advanced_diagnostics_level');
	#var_dump($diaglevel);
	#$sql='SELECT * FROM ' . WORDBOOKER_ERRORLOGS . ' WHERE user_ID = ' . $user_ID . '  and blog_id='.$blog_id.' and diag_level >'.$diaglevel.' order by sequence_id asc';
	#var_dump($sql);
	$rows = $wpdb->get_results('SELECT * FROM ' . WORDBOOKER_ERRORLOGS . ' WHERE user_ID = ' . $user_ID . '  and blog_id='.$blog_id.' and diag_level >'.$diaglevel.' order by sequence_id asc');
	if ($rows) {
?>
	<h3><?php _e('Diagnostic Messages', 'wordbooker'); ?></h3>
	<div class="wordbooker_errors">
	<p>
	</p>
	<table class="wordbooker_errorlogs">
		<tr>
			<th>Post</th>
			<th>Time</th>
			<th>Action</th>
			<th>Message</th>
			<th>Error Code</th>
		</tr>
<?php
	foreach ($rows as $row) {
		$hyperlinked_post = '';
		if (($post = get_post($row->post_id))) {
			$hyperlinked_post = '<a href="'. get_permalink($row->post_id) . '">'. apply_filters('the_title',get_the_title($row->post_id)) . '</a>';
		}
		$hyperlinked_method= wordbooker_hyperlinked_method($row->method);
		if ($row->error_code>1){ echo "<tr class='error'>";} else {echo "<tr class='diag'>";}
?>
			<td><?php if ($row->post_id>0) { echo $hyperlinked_post;} else {echo "-";} ?></td>
			<td><?php echo $row->timestamp; ?></td>
			<td><?php echo $row->method; ?></td>
			<td><?php echo stripslashes($row->error_msg); ?></td>
			<td><?php if ($row->error_code>1) {echo $row->error_code;} else { echo "-";}  ?></td>
		</tr>

<?php
		}
?>

	</table>
	<form action="<?php echo WORDBOOKER_SETTINGS_URL; ?>" method="post">
		<input type="hidden" name="action" value="clear_errorlogs" />
		<p class="submit" style="text-align: center;">
		<input type="submit" value="<?php _e('Clear Diagnostic Messages', 'wordbooker'); ?>" />
		</p>
	</form>
	</div>
	<hr>
<?php
	}
}


/******************************************************************************
 * Wordbooker setup and administration.
 */

function wordbooker_admin_load() {

	if (isset($POST['reset_user_config'])){
		wordbooker_delete_userdata();
	return;}
	if (!$_POST['action'])
		return;

	switch ($_POST['action']) {


	case 'delete_userdata':
		# Catch if they got here using the perm_save/cache refresh
		
		if ( ! isset ($_POST["perm_save"])) {
			wordbooker_delete_userdata();
		}
		wp_redirect(WORDBOOKER_SETTINGS_URL);
		break;

	case 'clear_errorlogs':
		wordbooker_clear_diagnosticlogs();
		wp_redirect(WORDBOOKER_SETTINGS_URL);
		break;

	case 'clear_diagnosticlogs':
		wordbooker_clear_diagnosticlogs();
		wp_redirect(WORDBOOKER_SETTINGS_URL);
		break;


	case 'no_facebook':
		wordbooker_set_userdata(false, null, null, null,null,null);
		wp_redirect('/wp-admin/index.php');
		break;
	}

	exit;
}

function wordbooker_admin_head() {
?>
	<style type="text/css">
	.wordbooker_setup { margin: 0 3em; }
	.wordbooker_notices { margin: 0 3em; }
	.wordbooker_status { margin: 0 3em; }
	.wordbooker_errors { margin: 0 3em; }
	.wordbooker_thanks { margin: 0 3em; }
	.wordbooker_thanks ul { margin: 1em 0 1em 2em; list-style-type: disc; }
	.wordbooker_support { margin: 0 3em; }
	.wordbooker_support ul { margin: 1em 0 1em 2em; list-style-type: disc; }
	.facebook_picture {
		float: right;
		border: 1px solid black;
		padding: 2px;
		margin: 0 0 1ex 2ex;
	}
	.wordbooker_errorcolor { color: #c00; }
	table.wordbooker_errorlogs { text-align: center; }
	table.wordbooker_errorlogs th, table.wordbooker_errorlogs td {
		padding: 0.5ex 1.5em;
	}
	table.wordbooker_errorlogs th { background-color: #999; }
	table.wordbooker_errorlogs tr.error td { background-color: #f66; }
	table.wordbooker_errorlogs tr.diag td { background-color: #CCC; }
	</style>
<?php
}

function wordbooker_option_notices() {
	global $user_ID, $wp_version;
	wordbooker_upgrade();
	wordbooker_trim_postlogs();
	wordbooker_trim_errorlogs();
	$errormsg = null;
	if (!function_exists('curl_init')) {
		$errormsg .=  __('Wordbooker needs the CURL PHP extension to work. Please install / enable it and try again','wordbooker').' <br />';
	}
	if (!function_exists('json_decode')) {
	 	$errormsg .=   __('Wordbooker needs the JSON PHP extension.  Please install / enable it and try again ','wordbooker').'<br />';
	}

	if (!function_exists('simplexml_load_string')) {
		$errormsg .=   __('Your PHP install is missing <code>simplexml_load_string()</code> ','wordbooker')."<br />";
	}
	$wbuser = wordbooker_get_userdata($user_ID);
	if (strlen($wbuser->access_token)< 50 ) {
		$errormsg .=__("Wordbooker needs to be set up", 'wordbooker')."<br />";
	} else if ($wbuser->facebook_error) {
		$method = $wbuser->facebook_error['method'];
		$error_code = $wbuser->facebook_error['error_code'];
		$error_msg = $wbuser->facebook_error['error_msg'];
		$post_id = $wbuser->facebook_error['postid'];
		$suffix = '';
		if ($post_id != null && ($post = get_post($post_id))) {
			wordbooker_delete_from_postlogs($post_id);
			$suffix = __('for', 'wordbooker').' <a href="'. get_permalink($post_id) . '">'. get_the_title($post_id) . '</a>';
		}
		$errormsg .= sprintf(__("<a href='%s'>Wordbooker</a> failed to communicate with Facebook" . $suffix . ": method = %s, error_code = %d (%s). Your blog is OK, but Facebook didn't get the update.", 'wordbooker'), " ".WORDBOOKER_SETTINGS_URL," ".wordbooker_hyperlinked_method($method)," ".$error_code," ".$error_msg)."<br />";
		wordbooker_clear_userdata_facebook_error($wbuser);
	}

	if ($errormsg) {
?>

	<h3><?php _e('Notices', 'wordbooker'); ?></h3>

	<div class="wordbooker_notices" style="background-color: #f66;">
	<p><?php echo $errormsg; ?></p>
	</div>

<?php
	}
}


function get_check_session(){
	global $facebook2,$user_ID;
	# This function basically checks for a stored session and if we have one it returns it, If we have no stored session then it gets one and stores it
	# OK lets go to the database and see if we have a session stored


	wordbooker_debugger("Getting Userdata "," ",0) ;
	$session = wordbooker_get_userdata($user_ID);
	if (strlen($session->access_token)>5) {
		var_dump($session);
		wordbooker_debugger("Session found. Check validity "," ",0) ;
		# We have a session ID so lets not get a new one
		# Put some session checking in here to make sure its valid
		try {
	#	var_dump($session->access_token);

		wordbooker_debugger("Calling Facebook API : get current user "," ",0) ;
	#	$attachment =  array('access_token' => $session->access_token,);
		#var_dump($attachment);
		$ret_code=wordbooker_me($session->facebook_id,$session->access_token);
	#	echo "mee";
	#	var_dump($ret_code);
		}
		catch (Exception $e) {
		# We don't have a good session so
		wordbooker_debugger("User Session invalid - clear down data "," ",0) ;
		#wordbooker_delete_user($user_ID,1);
		return;

	}
		#var_dump($session);
		return $session->access_token;
	} 
	else 
	{
		# Are we coming back from a login with a session set? 
		$zz=htmlspecialchars_decode ($_POST['session'])."<br>";
		$oldkey=explode("|",$zz);
		$newkey=explode("&expires",$zz);
	
		$session->access_token=$newkey[0];
		$session->session_key=$oldkey[1];
		$session->expires=0;	
		$ret_code=wordbooker_me_status($session->facebook_id,$session->access_token);
		#echo "mee tooo";
	#	var_dump($ret_code);

		wordbooker_debugger("Checking session (2) "," ",0) ;
	#	$session = $facebook2->getSession();
		#var_dump($session);
		if (strlen($session->access_token)>5){
		wordbooker_debugger("Session found. Store it "," ",0) ;
			# Yes! so lets store it!y)
		wordbooker_set_userdata($onetime_data, $facebook_error, $secret,$session,$ret_code->id);
			return $session->access_token;
		}
		
	} 
}




function wordbooker_option_setup($wbuser) {
?>

	<h3><?php _e('Setup', 'wordbooker'); ?></h3>
	<div class="wordbooker_setup">
<?php
	$access_token=get_check_session();
	$loginUrl2='https://www.facebook.com/dialog/oauth?client_id='.WORDBOOKER_FB_ID.'&redirect_uri=https://wordbooker.tty.org.uk/index2.html?br='.urlencode(get_bloginfo('wpurl')).'&scope=publish_stream,offline_access,user_status,read_stream,email,user_groups,manage_pages,read_friendlists&response_type=token';

	if ( is_null($access_token) ) {
	wordbooker_debugger("No session found - lets login and authorise "," ",0,99) ;
			echo "<br />".__("Secure link ( may require you to add a new certificate for wordbooker.tty.org.uk ) Also you may get a warning about passing data on a non secure connection :",'wordbooker').'<br /><br /> <a href="'. $loginUrl2.'"> <img src="http://static.ak.fbcdn.net/rsrc.php/zB6N8/hash/4li2k73z.gif" alt="Facebook Login Button" /> </a><br />';
	}
	 else  {
		wordbooker_debugger("Everything looks good so lets ask them to refresh "," ",0,99) ;
			echo __("Wordbooker should now be authorised. Please click on the Reload Page Button",'wordbooker').'<br> <form action="options-general.php?page=wordbooker" method="post">';
		echo '<p style="text-align: center;"><input type="submit" name="perm_save" class="button-primary" value="'. __('Reload Page', 'wordbooker').'" /></p>';
		echo '</form> '; 
	}
	echo "</div></div>";
}

function wordbooker_status($user_id)
{
	echo '<h3>'.__('Status', 'wordbooker').'</h3>';
	global  $wpdb, $user_ID,$table_prefix,$blog_id;
	$wordbooker_user_settings_id="wordbookuser".$blog_id;
	$wordbookuser=get_usermeta($user_ID,$wordbooker_user_settings_id);
	if ($wordbookuser['wordbooker_disable_status']=='on') {return;}
	global $shortcode_tags;
	$result = wordbooker_get_cache($user_id);
?>		

	<div class="wordbooker_status">
	<div class="facebook_picture">
		<a href="<?php echo $result->url; ?>" target="facebook">
		<img src="<?php echo $result->pic; ?>" /></a>
		</div>
		<p>
		<a href="<?php echo $result->url; ?>"><?php echo $result->name; ?></a> ( <?php echo $result->facebook_id; ?> )<br /><br />
		<i><?php echo "<p>".$result->status; ?></i></p>
		(<?php 
			$current_offset=0;
			$current_offset = get_option('gmt_offset');
			echo date('D M j, g:i a', $result->updated+(3600*$current_offset)); ?>).
		<br /><br />


<?php

}

function wordbooker_option_status($wbuser) {
global  $wpdb,$user_ID;

	#$fbclient = wordbooker_fbclient($wbuser);
	# Go to the cache and try to pull details
	$fb_info=wordbooker_get_cache($user_ID,'use_facebook,facebook_id',1);
	# If we're missing stuff lets kick the cache.
	if (! isset($fb_info->facebook_id)) {
		 wordbooker_cache_refresh ($user_ID,$fbclient);
		$fb_info=wordbooker_get_cache($user_ID,'use_facebook,facebook_id',1); 
	}
#	if (isset($fbclient->secret)){
		#var_dump($fb_info);
		if ($fb_info->use_facebook==1) {
			echo"<p>".__('Wordbooker appears to be configured and working just fine', 'wordbooker');
			wordbooker_check_permissions($wbuser,$user);	
			echo "</p><p>".__("If you like, you can start over from the beginning (this does not delete your posting and comment history)", 'wordbooker').":</p>";
		} 
		else 
		{
			echo "<p>".__('Wordbooker is able to connect to Facebook', 'wordbooker').'</p>';
		#	_e( 'Or, you can start over from the beginning');

		} 

	echo'<form action="" method="post">';
	echo '<p style="text-align: center;"><input type="submit"  class="button-primary" name="reset_user_config"  value="'.__('Reset User Session', 'wordbooker').'" />';
	echo '&nbsp;&nbsp;<input type="submit" name="perm_save" class="button-primary" value="'. __('Refresh Status', 'wordbooker').'" /></p>';
	echo '</form> </div>';

    $description=__("Recent Facebook Activity for this site", 'wordbooker');


    $iframe='<iframe src="http://www.facebook.com/plugins/activity.php?site='.get_bloginfo('url').'&amp;width=600&amp;height=400&amp;header=true&amp;colorscheme=light&amp;font&amp;border_color&amp;recommendations=true"  scrolling="no" frameborder="no" style="border:none; overflow:hidden; width:600px; height:400px"></iframe>';
    $activity="<hr><h3>".$description.'</h3><p>'.$iframe."</p></div>";
	$options = wordbooker_options();
   if (isset($options["wordbooker_fb_rec_act"])) { echo $activity; }


}

function wordbooker_version_ok($currentvers, $minimumvers) {
	#Lets strip out the text and any other bits of crap so all we're left with is numbers.
	$currentvers=trim(preg_replace("/[^0-9.]/ ", "", $currentvers ));
	$current = preg_split('/\D+/', $currentvers);
	$minimum = preg_split('/\D+/', $minimumvers);
	for ($ii = 0; $ii < min(count($current), count($minimum)); $ii++) {	
		if ($current[$ii] < $minimum[$ii])
			return false;
	}
	if (count($current) < count($minimum))
		return false;
	return true;
}


function wordbooker_option_support() {
	global $wp_version,$wpdb,$user_ID,$facebook2;
	$wordbooker_settings=wordbooker_options();
?>
	<h3><?php _e('Support', 'wordbooker'); ?></h3>
	<div class="wordbooker_support">
	<?php _e('For feature requests, bug reports, and general support :', 'wordbooker'); ?>
	<ul>	
	<li><?php _e('Check the ', 'wordbooker'); ?><a href="../wp-content/plugins/wordbooker/wordbooker_user_guide.pdf" target="wordpress"><?php _e('User Guide', 'wordbooker'); ?></a>.</li>
	<li><?php _e('Check the ', 'wordbooker'); ?><a href="http://wordpress.org/extend/plugins/wordbooker/other_notes/" target="wordpress"><?php _e('WordPress.org Notes', 'wordbooker'); ?></a>.</li>
	<li><?php _e('Try the ', 'wordbooker'); ?><a href="http://wordbooker.tty.org.uk/forums/" target="facebook"><?php _e('Wordbooker Support Forums', 'wordbooker'); ?></a>.</li>
		<li><?php _e('Enhancement requests can be made at the ', 'wordbooker'); ?><a href="http://code.google.com/p/wordbooker/" target="facebook"><?php _e('Wordbooker Project on Google Code', 'wordbooker'); ?></a>.</li>
	<li><?php _e('Consider upgrading to the ', 'wordbooker'); ?><a href="http://wordpress.org/download/"><?php _e('latest stable release', 'wordbooker'); ?></a> <?php _e(' of WordPress. ', 'wordbooker'); ?></li>
	<li><?php _e('Read the release notes for Wordbooker on the ', 'wordbooker'); ?><a href="http://wordbooker.tty.org.uk/current-release/">Wordbooker</a> <?php _e('blog.', 'wordbooker'); ?></li>
	<li><?php _e('Check the Wordbooker ', 'wordbooker'); ?><a href="http://wordbooker.tty.org.uk/faqs/">Wordbooker</a> <?php _e('FAQs', 'wordbooker'); ?></li>
	</ul>
	<br />
	<?php _e('Please provide the following information about your installation:', 'wordbooker'); ?>
	<ul>
<?php
	$active_plugins = get_option('active_plugins');
	$plug_info=get_plugins();
	$phpvers = phpversion();
	$jsonvers=phpversion('json');
	if (!phpversion('json')) { $jsonvers="Installed but version not being returned";}
	$sxmlvers=phpversion('simplexml');
	if (!phpversion('simplexml')) { $sxmlvers=" No version being returned";} 
	$mysqlvers = function_exists('mysql_get_client_info') ? mysql_get_client_info() :  'Unknown';
	# If we dont have the function then lets go and get the version the old way
	if ($mysqlvers=="Unknown") {
		$t=mysql_query("select version() as ve");
		$r=mysql_fetch_object($t);
		$mysqlvers =  $r->ve;
	}
	$http_coding="No Multibyte support";
	$int_coding="No Multibyte support";
	$mb_language="No Multibyte support";
	#$t=mysql_query("show variables like 'character%'");
	if (function_exists('mb_convert_encoding')) {
		$http_coding=mb_http_output();
		$int_coding=mb_internal_encoding();
		$mb_language=mb_language();
	}


	$curlcontent=__("Curl is not installed",'wordbooker');
	if (function_exists('curl_init')) {
	  $ch = curl_init();
	   curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/platform');
	   curl_setopt($ch, CURLOPT_HEADER, 0);
	   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
	   curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/includes/fb_ca_chain_bundle.crt');
	   curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0');
	   $curlcontent = @curl_exec($ch);
	   $x=json_decode($curlcontent);
	#var_dump($x->name);
	   $curlstatus=__("Curl is available but cannot access Facebook - This is a problem (",'wordbooker').curl_errno($ch)." - ". curl_error($ch) ." )";
	   if ($x->name=="Facebook Platform") {$curlstatus=__("Curl is available and can access Facebook - All is OK",'wordbooker');}
  	 curl_close($ch);
	}
	$new_wb_table_prefix=$wpdb->base_prefix;
	if (isset ($db_prefix) ) { $new_wb_table_prefix=$db_prefix;}
	$info = array(	
		'Wordbooker' => $plug_info['wordbooker/wordbooker.php']['Version'],
		'Wordbooker ID'=>WORDBOOKER_FB_ID,
		'Wordbooker Schema' => $wordbooker_settings['schema_vers'],
		'WordPress' => $wp_version,
		'Table prefix' =>$new_wb_table_prefix,
		 'PHP' => $phpvers,
		 'PHP Memory Usage (MB)' => memory_get_usage(true)/1024/1024,
		'JSON Encode' => WORDBOOKER_JSON_ENCODE,
		'JSON Decode' => WORDBOOKER_JSON_DECODE,
		'Curl Status' => $curlstatus,
#		'Fopen Status' => $fopenstat2.$fopenstat,
		'JSON Version' => $jsonvers,
		'SimpleXML library' => $sxmlvers." (". WORDBOOKER_SIMPLEXML.")",
		'HTTP Output Character Encoding'=>$http_coding,
		'Internal PHP Character Encoding'=>$int_coding,
		'MySQL' => $mysqlvers,
#		'Facebook Transaction limit'=>$result2,
		);
	$version_errors = array();
	$phpminvers = '5.0';
	$mysqlminvers = '4.0';
	if (!wordbooker_version_ok($phpvers, $phpminvers)) {
		$version_errors['PHP'] = $phpminvers;
	}
	if ($mysqlvers != 'Unknown' && !wordbooker_version_ok($mysqlvers, $mysqlminvers)) {
		$version_errors['MySQL'] = $mysqlminvers;
	}

	foreach ($info as $key => $value) {
		$suffix = '';
		if (($minvers = $version_errors[$key])) {
			$suffix = " <span class=\"wordbooker_errorcolor\">" . " (need $key version $minvers or greater)" . " </span>";
		}
		echo "<li>$key: <b>$value</b>$suffix</li>";
	}
	if (!function_exists('simplexml_load_string')) {
		_e("<li>XML: your PHP is missing <code>simplexml_load_string()</code></li>", 'wordbooker');
	}

	$rows = $wpdb->get_results("show variables like 'character_set%'");
	foreach ($rows as $chardata){
		echo "<li> Database ". $chardata->Variable_name ." : <b> ".$chardata->Value ."</b></li>";
	}
	$rows = $wpdb->get_results("show variables like 'collation%'");
	foreach ($rows as $chardata){
		echo "<li> Database ". $chardata->Variable_name ." : <b> ".$chardata->Value ."</b></li>";
	}
	echo "<li> Server : <b>".$_SERVER['SERVER_SOFTWARE']."</b></li>";
	_e("<li> Active Plugins : <b></li>", 'wordbooker');	
	 foreach($active_plugins as $name) {
		if ( $plug_info[$name]['Title']!='Wordbooker') {
		echo "&nbsp;&nbsp;&nbsp;".$plug_info[$name]['Title']." ( ".$plug_info[$name]['Version']." ) <br />";}
	}

	
	if (ADVANCED_DEBUG) { phpinfo(INFO_MODULES);}
?>
	</ul>

<?php
	if ($version_errors) {
?>

	<div class="wordbooker_errorcolor">
	<?php _e('Your system does not meet the', 'wordbooker'); ?> <a href="http://wordpress.org/about/requirements/"><?php _e('WordPress minimum requirements', 'wordbooker'); ?></a>. <?php _e('Things are unlikely to work.', 'wordbooker'); ?>
	</div>

<?php
	} else if ($mysqlvers == 'Unknown') {
?>

	<div>
	<?php _e('Please ensure that your system meets the', 'wordbooker'); ?> <a href="http://wordpress.org/about/requirements/"><?php _e('WordPress minimum requirements', 'wordbooker'); ?></a>.
	</div>

<?php
	}
?>
	</div>

<?php
}


/******************************************************************************
 * Facebook API wrappers.
 */

/*
function wordbooker_fbclient_facebook_finish($wbuser, $result, $method,$error_code, $error_msg, $post_id,$result2, $error_code2, $error_msg2) 
{	
	global $blog_id;
	wordbooker_debugger("Publish complete"," ",$post_id,99) ;
	if ($error_code) {
		wordbooker_set_userdata_facebook_error($wbuser, $method, $error_code, $error_msg, $post_id);
	}

	if ($error_code2) {
		wordbooker_set_userdata_facebook_error($wbuser, $method, $error_code2, $error_msg2, $post_id);
	}
 If ((! $error_code) && (! $error_code2)) 
 	{	
		wordbooker_clear_userdata_facebook_error($wbuser);
		wordbooker_delete_from_process_queue($post_id,$blog_id);
	}

	return array($result,$result2);
}
*/

function wordbooker_fbclient_publishaction($wbuser,$post_id) 
{	
	global $wordbooker_post_options,$wpdb;

	$wordbooker_settings =wordbooker_options(); 
	$post = get_post($post_id);
	$post_link_share = get_permalink($post_id);
	$post_link=wordbooker_short_url($post_id);
	$post_title=$post->post_title;
	$post_content = $post->post_content;
	# Grab the content of the post once its been filtered for display - this converts app tags into HTML so we can grab gallery images etc.
	$processed_content ="!!!  ".apply_filters('the_content', $post_content)."    !!!";
	$yturls  = array();
	$matches_tn=array();
	# Get the Yapb image for the post
	if (class_exists('YapbImage')) {
	   $siteUrl = get_option('siteurl');
	   if (substr($siteUrl, -1) != '/') $siteUrl .= '/';
	    $uri = substr($url, strpos($siteUrl, '/', strpos($url, '//')+2));
	    $WordbookerYapbImageclass = new YapbImage(null,$post->ID,$uri);
	    $WordbookerYapbImage=$WordbookerYapbImageclass->getInstanceFromDb($post_id);
	    if (strlen($WordbookerYapbImage->uri)>6) {$yturls[]=get_bloginfo('url').$WordbookerYapbImage->uri;}
	}

	if ( function_exists( 'get_the_post_thumbnail' ) ) { 
		wordbooker_debugger("Getting the thumnail image"," ",$post->ID) ;
		preg_match_all('/<img \s+ ([^>]*\s+)? src \s* = \s* [\'"](.*?)[\'"]/ix',get_the_post_thumbnail($post_id), $matches_tn); 
	}
	
	$meta_tag_scan=explode(',',$wordbooker_settings['wordbooker_meta_tag_scan']);
	foreach($meta_tag_scan as $meta_tag) {
		wordbooker_debugger("Getting image from custom meta : ",$meta_tag,$post->ID) ;
		$matches_ct[]=get_post_meta($post->ID, $meta_tag, TRUE);
	}
	$matches=$matches_ct;
	if ( function_exists( 'get_the_post_thumbnail' ) ) { 
		$matches=array_merge($matches_ct,$matches_tn[2]);
	}
   
	# If the user only wants the thumbnail then we can simply not do the skim over the processed images
	if (! isset($wordbooker_post_options["wordbooker_thumb_only"]) ) {
		wordbooker_debugger("Getting the rest of the images "," ",$post->ID) ;
		preg_match_all('/<img \s+ ([^>]*\s+)? src \s* = \s* [\'"](.*?)[\'"]/ix',$processed_content, $matched);
		$x=strip_shortcodes($post_content);
		preg_match_all( '#http://(www.youtube|youtube|[A-Za-z]{2}.youtube)\.com/(watch\?v=|w/\?v=|\?v=|embed/)([\w-]+)(.*?)#i', $x, $matches3 );
		if (is_array($matches3[3])) {
			foreach ($matches3[3] as $key ) {
				$yturls[]='http://img.youtube.com/vi/'.$key.'/0.jpg';
			}
		}
		
	}
	if ( function_exists( 'get_the_post_thumbnail' ) ) {
		# If the thumb only is set then pulled images is just matches
		if (!isset($wordbooker_settings["wordbooker_meta_tag_thumb"])) {
			if (! isset($wordbooker_post_options["wordbooker_thumb_only"]) ) {
				wordbooker_debugger("Setting image array to be both thumb and the post images "," ",$post->ID) ;
			 	$pulled_images=@array_merge($matches[2],$matched[2],$yturls,$matches);
			}
			else {
				wordbooker_debugger("Setting image array to be just thumb "," ",$post->ID) ;
				$pulled_images[]=$matches[2];
			} 
		}
	}

	if (isset($wordbooker_settings["wordbooker_meta_tag_thumb"]) && isset($wordbooker_post_options["wordbooker_thumb_only"]) ) {
	wordbooker_debugger("Setting image array to be just thumb from meta. "," ",$post->ID) ;
	$pulled_images[]=$matches_ct[2];}

	else {
		wordbooker_debugger("Setting image array to be post and thumb images. "," ",$post->ID) ;
		if (is_array($matched[2])) {$pulled_images[]=array_merge($matches,$matched[2]);}
		if (is_array($matched[2]) && is_array($yturls)) {$pulled_images=array_merge($matches,$matched[2],$yturls);}
	}

	$images = array();
	if (is_array($pulled_images)) {
		foreach ($pulled_images as $imgsrc) {
			if ($imgsrc) {
				if (stristr(substr($imgsrc, 0, 8), '://') ===false) {
					/* Fully-qualify src URL if necessary. */
					$scheme = $_SERVER['HTTPS'] ? 'https' : 'http';
					$new_imgsrc = "$scheme://". $_SERVER['SERVER_NAME'];
					if ($imgsrc[0] == '/') {
						$new_imgsrc .= $imgsrc;
					}
					$imgsrc = $new_imgsrc;
				}
				$images[] =  $imgsrc;
			}
		}
	}
	/* Pull out <wpg2> image tags. */
	$wpg2_g2path = get_option('wpg2_g2paths');
	if ($wpg2_g2path) {
		$g2embeduri = $wpg2_g2path['g2_embeduri'];
		if ($g2embeduri) {
			preg_match_all('/<wpg2>(.*?)</ix', $processed_content,
				$wpg_matches);
			foreach ($wpg_matches[1] as $wpgtag) {
				if ($wpgtag) {
					$images[] = $g2embeduri.'?g2_view='.'core.DownloadItem'."&g2_itemId=$wpgtag";
				}
			}
		}
	}
	$wordbooker_settings =wordbooker_options(); 
	if (count($images)>0){
		# Remove duplicates
		$images=array_unique($images);
		# Strip images from various plugins
		$images=wordbooker_strip_images($images);
		# And limit it to 5 pictures to keep Facebook happy.
		$images = array_slice($images, 0, 5);

	} else { 
		if (isset($wordbooker_settings['wordbooker_use_this_image']))  {
			$images[]=$wordbooker_settings['wb_wordbooker_default_image'];
			wordbooker_debugger("No Post images found so using open graph default to keep Facebook happy ",'',$post->ID) ;
			} 
		else {
			$x=get_bloginfo('wpurl').'/wp-content/plugins/wordbooker/includes/wordbooker_blank.jpg';
			$images[]=$x;
			wordbooker_debugger("No Post images found so loading blank to keep Facebook happy ",'',$post->ID) ;	
			}
		}
		#var_dump($images);
		foreach ($images as $single) {
 			$images_array[]=array(
					'type' => 'image', 
					'src' => $single,
					'href' => $post_link_share,
					);
		}
		$images=$images_array;
		#var_dump($images);
			foreach ($images as $key){
			wordbooker_debugger("Post Images : ".$key['src'],'',$post->ID) ;
		}
	// Set post_meta to be first image
	update_post_meta($post->ID,'_wordbooker_thumb',$images[0]['src']);
	wordbooker_debugger("Getting the Excerpt"," ",$post->ID) ;
	unset ($processed_content);
	if (isset($wordbooker_post_options["wordbooker_use_excerpt"])  && (strlen($post->post_excerpt)>3)) { 
		$post_content=$post->post_excerpt; 
		$post_content=wordbooker_translate($post_content);
	}
	else {	$post_content=wordbooker_post_excerpt($post_content,$wordbooker_post_options['wordbooker_extract_length']);}
	update_post_meta($post->ID,'_wordbooker_extract',$post_content);
	# this is getting and setting the post attributes
	$post_attribute=parse_wordbooker_attributes(stripslashes($wordbooker_post_options["wordbooker_attribute"]),$post_id,strtotime($post->post_date));
	$post_data = array(
		'media' => $images,
		'post_link' => $post_link,
		'post_link_share' => $post_link_share,
		'post_title' => $post_title,
		'post_excerpt' => $post_content,
		'post_attribute' => $post_attribute,
	#	'post_full_text' => $post->post_content,
		'post_id'=>$post->ID,
		'post_date'=>$post->post_date
		);
	# This is the tagging code - 
	#if (strlen($wordbooker_post_options['wordbooker_tag_list']) > 6 ) {
#		$wordbooker_tag_list=str_replace('[','@[',$wordbooker_post_options['wordbooker_tag_list']);
#		$message=$message. "   (Tagged : ".$wordbooker_tag_list." ) ";
#	}
		
	if (function_exists('qtrans_use')) {
		global $q_config;
		$post_data['post_title']=qtrans_use($q_config['default_language'],$post_data['post_title']);
	}
	$post_id=$post->ID;

	$wordbooker_fb_post = array(
	  'name' => $post_data['post_title'],
	  'link' => $post_data['post_link'],
	  'message'=> $post_data['post_attribute'],
	  'description' => $post_data['post_excerpt'],
	  'picture'=>$images[0]['src']
	#  'media' => json_encode($images)
	);
	wordbooker_debugger("Post Titled : ",$post_data['post_title'],$post_id,99) ;
	wordbooker_debugger("Post URL : ",$post_data['post_link'],$post_id,99) ;
	
	if ($wordbooker_post_options['wordbooker_actionlink']==100) {
		// No action link
		wordbooker_debugger("No action link being used","",$post_id,99) ;
	}
	if ($wordbooker_post_options['wordbooker_actionlink']==200) {
		// Share This
		wordbooker_debugger("Share Link being used"," ",$post_id,99) ;
		$action_links = array('name' => __('Share', 'wordbooker'),'link' => 'http://www.facebook.com/share.php?u='.urlencode($post_data['post_link_share']));
		$wordbooker_fb_post['actions']=json_encode($action_links);
	}
	if ($wordbooker_post_options['wordbooker_actionlink']==300) {
		// Read Full
		wordbooker_debugger("Read Full link being used"," ",$post_id,99) ;
		$action_links = array('name' => __('Read entire article', 'wordbooker'),'link' => $post_data['post_link_share']);
		$wordbooker_fb_post['actions'] =json_encode($action_links);
	}

	$posting_array[] = array('target_id'=>__("Primary", 'wordbooker'),
				'target'=>$wordbooker_post_options['wordbooker_primary_target'], 
				 'target_type'=>$wordbooker_post_options['wordbooker_primary_type'],
				 'target_active'=>$wordbooker_post_options['wordbooker_primary_active']);
	$posting_array[] = array('target_id'=>__("Secondary", 'wordbooker'),
				'target'=>$wordbooker_post_options['wordbooker_secondary_target'], 
				 'target_type'=>$wordbooker_post_options['wordbooker_secondary_type'],
				 'target_active'=>$wordbooker_post_options['wordbooker_secondary_active']);;
	$target_types = array('PW' => "",'FW' => __('Fan Wall', 'wordbooker'), 'GW'=>__('Group wall', 'wordbooker'));
	$posting_type=array("1"=>"Wall Post","2"=>"Note","3"=>"Status Update");
	foreach($posting_array as $posting_target) {
		$access_token='dummy access token';
		$wbuser->pages[]=array( 'id'=>'PW:'.$wbuser->facebook_id, 'name'=>"Personal Wall",'access_token'=>$wbuser->access_token);
		if(is_array($wbuser->pages)){
			foreach ($wbuser->pages as $pager) {
				if ($pager['id']==$posting_target['target']) {
					$target_name=$pager['name'];
					$access_token=$pager['access_token'];
				}
			}
		}
 		if (isset($posting_target['target_active'])) {
			$target_type=substr($posting_target['target'],0,2);
			wordbooker_debugger("Posting to ".$target_types[$target_type]." ".$target_name." (".$posting_target['target_id'].") as a ".$posting_type[$posting_target['target_type']],"",$post_id,99) ; 
			if ($access_token=='dummy access token') {$access_token=$wbuser->access_token;}
			$target=substr($posting_target['target'],3);
			$is_dummy=$wordbooker_settings['wordbooker_fake_publish'];
			switch($posting_target['target_type']) {
				# Wall Post
				case 1 : 
				wordbooker_wall_post($post_id,$access_token,$post_title,$wordbooker_fb_post ,$target,$is_dummy,$target_name);
				break;
				# Note
				case 2 :
				wordbooker_notes_post($post_id,$access_token,$post_title,$target,$is_dummy,$target_name);
				break;
				# Status Update
				case 3 : 
				wordbooker_status_update($post_id,$access_token,$post_data['post_date'],$target,$is_dummy,$target_name);
				break ;
			}

		} else {wordbooker_debugger("Posting to ".$posting_target['target_id']." target (".$target_name.") not active","",$post_id,99) ; }

	}
}

function wordbooker_strip_images($images)
{
	$newimages = array();
	$strip_array= array ('addthis.com','gravatar.com','zemanta.com','wp-includes','plugins','favicon.ico','facebook.com','themes','mu-plugins','fbcdn.net');
	foreach($images as $single){
		$ext = substr(strrchr($single, '.'), 1);
		if (strlen($ext) >2){
		foreach ($strip_array as $strip_domain) {
			wordbooker_debugger("Looking for ".$strip_domain." in ".$single," ",$post->ID,200) ;
 		  	if (stripos($single,$strip_domain)) {wordbooker_debugger("Found a match so dump the image",$single,$post->ID,200) ;} else { if (!in_array($single,$newimages)){$newimages[]=$single;}}
		}} else {wordbooker_debugger("Image URL ".$single." not valid ",$post->ID,200) ;}
	}
	return $newimages;
}

function wordbooker_get_language() {
	global $q_config;
	$wplang="en_US";
	if (strlen(WPLANG) > 2) {$wplang=WPLANG;}
	if (isset ($q_config["language"])) {
		$x=get_option('qtranslate_locales');
		$wplang=$x[$q_config["language"]];
	}
	if (strlen($wplang)< 5) {$wplang='en_US';}
	if ($wplang=="WPLANG" ) {$wplang="en_US";}
	return $wplang;
}


function wordbooker_short_url($post_id) {
	# This provides short_url responses by checking for various functions and using 
	$wordbooker_settings =wordbooker_options(); 
	
	if (isset($wordbooker_settings["wordbooker_disable_shorties"])) {
		$url = get_permalink($post_id);
		return $url;
	}
	$url = get_permalink($post_id);
	$url2 = $url;
	if (function_exists(fts_show_shorturl)) {	
		$post = get_post($post_id);
		$url=fts_show_shorturl($post,$output = false);
	}
	if (function_exists(wp_ozh_yourls_geturl)) {
		$url=wp_ozh_yourls_geturl($post_id);
	}
	if ("!!!".$url."XXXX"=="!!!XXXX") {$url = $url2;}
	return $url;
}

function parse_wordbooker_attributes($attribute_text,$post_id,$timestamp) {
	# Changes various "tags" into their WordPress equivalents.
	$post = get_post($post_id);
	$user_id=$post->post_author; 
	$title=$post->post_title;
	$perma=get_permalink($post->ID);
	$perma_short=wordbooker_short_url($post_id);
	$user_info = get_userdata($user_id);
	$blog_url= get_bloginfo('url');
	$wp_url= get_bloginfo('wpurl');
	$blog_name = get_bloginfo('name');
	$author_nice=$user_info->display_name;
	$author_nick=$user_info->nickname;
	$author_first=$user_info->first_name;
	$author_last=$user_info->last_name;

	# Format date and time to the blogs preferences.
	$date_info=date_i18n(get_option('date_format'),$timestamp);
	$time_info=date_i18n(get_option('time_format'),$timestamp);

	# Now do the replacements
	$attribute_text=str_ireplace( '%author%',$author_nice,$attribute_text );
	$attribute_text=str_ireplace( '%first%',$author_first,$attribute_text );
	$attribute_text=str_ireplace( '%wpurl%',$wp_url,$attribute_text );
	$attribute_text=str_ireplace( '%burl%',$blog_url,$attribute_text );
	$attribute_text=str_ireplace( '%last%',$author_last,$attribute_text );
	$attribute_text=str_ireplace( '%nick%',$author_nick,$attribute_text );
	$attribute_text=str_ireplace( '%title%',$title,$attribute_text );
	$attribute_text=str_ireplace( '%link%',$perma,$attribute_text );
	$attribute_text=str_ireplace( '%slink%',$perma_short,$attribute_text );
	$attribute_text=str_ireplace( '%date%', $date_info ,$attribute_text);
	$attribute_text=str_ireplace( '%time%', $time_info,$attribute_text );

	return $attribute_text;
}


function wordbooker_footer($blah)
{
	if (is_404()) {
		echo "\n<!-- Wordbooker code revision : ".WORDBOOKER_CODE_RELEASE." -->\n";
		return;
	}
	$wplang=wordbooker_get_language();

$efb_script = <<< EOGS
 <div id="fb-root"></div>
     <script type="text/javascript">
      window.fbAsyncInit = function() {
	FB.init({
	 appId  : '254577506873',
	  status : true, // check login status
	  cookie : true, // enable cookies to allow the server to access the session
	  xfbml  : true,  // parse XFBML
	  oauth:true
	});
      };

      (function() {
	var e = document.createElement('script');

EOGS;

$efb_script.= "e.src = document.location.protocol + '//connect.facebook.net/".$wplang."/all.js';";
$efb_script.= <<< EOGS
	e.async = true;
	document.getElementById('fb-root').appendChild(e);
      }());
    </script>

EOGS;
	$wordbooker_settings = wordbooker_options(); 
	if  (isset($wordbooker_settings['wordbooker_like_button_show']) || isset($wordbooker_settings['wordbooker_like_share_too'])) 
		{
		echo $efb_script;
		 if ( isset($wordbooker_settings['wordbooker_iframe'])) {
			echo '<script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script>';
		}
	}
#	echo '\n<script type="text/javascript " defer="defer" > setTimeout("wordbooker_read()",3000); </script> \n';
	echo "\n<!-- Wordbooker code revision : ".WORDBOOKER_CODE_RELEASE." -->\n";
return $blah;
}

function wordbooker_og_tags(){
	if (is_404()) {return;}
	global $post;
	# Stops the code firing on non published posts
	if ('publish' != get_post_status($post->ID)) {return;}
	$bname=get_bloginfo('name');
	$bdesc=get_bloginfo('description');
	$wordbooker_settings = wordbooker_options(); 	
	# Always put out the tags because even if they are not using like/share it gives Facebook stuff to work with.
		$wordbooker_post_options= get_post_meta($post->ID, '_wordbooker_options', true); 
		$wpuserid=$post->post_author;
		if (is_array($wordbooker_post_options)){
			if  ($wordbooker_post_options["wordbooker_default_author"] > 0 ) {$wpuserid=$wordbooker_post_options["wordbooker_default_author"];}
		}

		$blog_name=get_bloginfo('name');
		echo '<meta property="og:site_name" content="'.$bname.' - '.$bdesc.'"/> ';
		if (strlen($wordbooker_settings["fb_comment_app_id"])<6) {
		if ($wordbooker_settings['wordbooker_fb_comments_admin']) {
			$xxx=wordbooker_get_cache(-99,facebook_id,1);
			#var_dump($wordbooker_settings['wb_wordbooker_default_image']);
				if (!is_null($xxx)) {
				echo '<meta property="fb:admins" content="'.$xxx.'"/> ';
			}
		} else {
			 $xxx=wordbooker_get_cache( $wpuserid,facebook_id,1);
			if (!is_null($xxx->facebook_id)) {
				echo '<meta property="fb:admins" content="'.$xxx->facebook_id.'"/> ';
			}
		 }
		}
		if (strlen($wordbooker_settings["fb_comment_app_id"])>6) {
			echo '<meta property = "fb:app_id" content = "'.$wordbooker_settings["fb_comment_app_id"].'" /> ';
		}
		if (defined('WORDBOOKER_PREMIUM')) {
			echo '<meta property = "fb:app_id" content = "'.WORDBOOKER_FB_ID.'" /> ';
		}	
		if ( (is_single() || is_page()) && !is_front_page() && !is_category() && !is_home() ) {
			$post_link = get_permalink($post->ID);
			$post_title=$post->post_title;
			echo '<meta property="og:title" content="'.htmlspecialchars(strip_tags($post_title),ENT_QUOTES).'"/> ';
			echo '<meta property="og:url" content="'.$post_link.'"/> ';
			echo '<meta property="og:type" content="article"/> ';
			
			$ogimage=get_post_meta($post->ID, '_wordbooker_thumb', TRUE);
			if (strlen($ogimage)<4 && strlen($wordbooker_settings['wb_wordbooker_default_image'])>4) {
				$ogimage=$wordbooker_settings['wb_wordbooker_default_image'];
			}
			if (strlen($ogimage)>4) {
				echo '<meta property="og:image" content="'.$ogimage.'"/> ';
				
			}
		} 
		else
		{ # Not a single post so we only need the og:type tag
			echo '<meta property="og:type" content="blog"/> ';
		}
		#wordbooker_get_option('wordbooker_description_meta_length')
	if ($meta_length = wordbooker_get_option('wordbooker_description_meta_length')) {
		if (is_single() || is_page()) {
			$excerpt=get_post_meta($post->ID, '_wordbooker_extract', TRUE);
		#var_dump($excerpt);
			if(strlen($excerpt) < 5 ) {
				$excerpt=wordbooker_post_excerpt($post->post_content,$wordbooker_settings['wordbooker_extract_length']);
				update_post_meta($post->ID, '_wordbooker_extract', $excerpt);
	#	var_dump($excerpt);
			}
			# If we've got an excerpt use that instead
			if ((strlen($post->post_excerpt)>3) && (strlen($excerpt) <=5)) { 
				$excerpt=$post->post_excerpt; 
				$description = str_replace('"','&quot;',$post->post_content);
				$excerpt = wordbooker_post_excerpt($description,$meta_length);
				$excerpt = preg_replace('/(\r|\n)+/',' ',$excerpt);
				$excerpt = preg_replace('/\s\s+/',' ',$excerpt);
	
				update_post_meta($post->ID, '_wordbooker_extract', $excerpt);
			}
			# Now if we've got something put the meta tag out.
			if (isset($excerpt)){ 
				$meta_string = sprintf("<meta name=\"description\" content=\"%s\"/> ", htmlspecialchars($excerpt,ENT_QUOTES));
				echo $meta_string;
			}
		}
	else
		{		
			$meta_string = sprintf("<meta name=\"description\" content=\"%s\"/> ", get_bloginfo('description'));
			echo $meta_string;
		}
	}
}

function wordbooker_header($blah){
	if (is_404()) {return;}
	global $post;
	# Stops the code firing on non published posts
	if ('publish' != get_post_status($post->ID)) {return;}
	$wordbooker_settings = wordbooker_options(); 
	# Now we just call the wordbooker_og_tags function.
	if (!isset ( $wordbooker_settings['wordbooker_fb_disable_og'])) {
		wordbooker_og_tags();
	}
/*	if (is_single() && isset($wordbooker_settings['wordbooker_read_button']) ) {

$read_codes=" <script type=\"text/javascript\">
function wordbooker_read()
{
FB.api('/me/".OPENGRAPH_NAMESPACE.":read' + 
'?article=";
$read_codes.=get_permalink($post->ID);
$read_codes.="&access_token=".OPENGRAPH_ACCESS_TOKEN."','post',";
$read_codes.=<<<READCODE4

function(response) {
var msg = 'Error occured';
if (!response || response.error) {
if (response.error) {
msg += " Type: " + response.error.type+"  Message: " + response.error.message;
}
alert(msg);
} 
else {
//alert('Post was successful! Action ID: ' + response.id);
}
});
}
</script>
READCODE4;
echo $read_codes;
}
*/
	return $blah;
}

function display_wordbooker_fb_comment() {
	global $post;
	if(!is_single()){return;}
	$wordbooker_settings = wordbooker_options(); 
	$wordbooker_post_options= get_post_meta($post->ID, '_wordbooker_options', true);  
	#var_dump($wordbooker_settings['wordbooker_comment_handling']);
#	var_dump($wordbooker_post_options['wordbooker_use_facebook_comments']);
	if ($wordbooker_settings['wordbooker_comment_handling']=="2" && isset($wordbooker_post_options['wordbooker_use_facebook_comments'])) {
		$post_link = get_permalink($post->ID);
		$checked_flag=array('on'=>'true','off'=>'false');
		$comment_code= '<fb:comments href="'.$post_link.'" num_posts="'.$wordbooker_settings['fb_comment_box_count'].'" width="'.$wordbooker_settings['fb_comment_box_size'].'" notify="'.$checked_flag[$wordbooker_settings['fb_comment_box_notify']].' colorscheme="'.$wordbooker_settings['wb_comment_colorscheme'].'" ></fb:comments>';
		echo $comment_code;
	}
}

function wordbooker_fb_comment_inline() {
	global $post;
	if(!is_single()){return;}
	$wordbooker_settings = wordbooker_options(); 
	$wordbooker_post_options= get_post_meta($post->ID, '_wordbooker_options', true);  
	if ($wordbooker_settings['wordbooker_comment_handling']=="2" && isset($wordbooker_post_options['wordbooker_use_facebook_comments'])) {
		$post_link = get_permalink($post->ID);
		$checked_flag=array('on'=>'true','off'=>'false');
		$comment_code= '<fb:comments href="'.$post_link.'" num_posts="'.$wordbooker_settings['fb_comment_box_count'].'" width="'.$wordbooker_settings['fb_comment_box_size'].'" notify="'.$checked_flag[$wordbooker_settings['fb_comment_box_notify']].' colorscheme="'.$wordbooker_settings['wb_comment_colorscheme'].'" ></fb:comments>';
		return $comment_code;
	}
}
function display_wordbooker_fb_share() {
	global $post;
	$wordbooker_settings = wordbooker_options(); 
	$do_share=0;
	$wordbooker_post_options= get_post_meta($post->ID, '_wordbooker_options', true);  
	#var_dump($$wordbooker_settings[);
	if ($wordbooker_post_options['wordbooker_share_button_post']==2 && !is_page()) {return ;}
	if ($wordbooker_post_options['wordbooker_share_button_page']==2 && is_page()) {return ;}
	if (!isset($wordbooker_settings['wordbooker_like_share_too'])) {return ;}
	if (isset($wordbooker_settings['wordbooker_share_button_post']) && is_single()  ) {$do_share=1;}
	if (isset($wordbooker_settings['wordbooker_share_button_page']) && is_page() )  {$do_share=1;}
	if (isset($wordbooker_settings['wordbooker_share_button_frontpage'])  && is_front_page() ) {$do_share=1;}
	if (isset($wordbooker_settings['wordbooker_share_button_category']) &&  is_category()  ) {$do_share=1;}
	if (isset($wordbooker_settings['wordbooker_no_share_stick']) &&  is_sticky()  ) {$do_share=0; }
	if ( $do_share==1  &&
	((isset($wordbooker_settings['wordbooker_share_button_post']) && is_single()  )
          || (isset($wordbooker_settings['wordbooker_share_button_page']) && is_page() ) 
	  || (isset($wordbooker_settings['wordbooker_share_button_frontpage'])  && is_front_page() ) 
	  || (isset($wordbooker_settings['wordbooker_share_button_category']) &&  is_category()  ))
	  )
	{
	$post_link = get_permalink($post->ID);
	$btype="button";
	if (is_single() || is_page()) {
	$btype="button_count";
	}
	if (isset($wordbooker_settings['wordbooker_iframe'])) {
		 $share_code='<!-- Wordbooker created FB tags --> <a name="fb_share" type="'.$btype.'" share_url="'.$post_link.'"></a>';
	}
	else {
		$share_code='<!-- Wordbooker created FB tags --> <fb:share-button class="meta" type="'.$btype.'" href="'.$post_link.'" > </fb:share-button>';
	}
	echo $share_code;
	}
}

function wordbooker_fb_share_inline() {
	global $post;
	$wordbooker_settings = wordbooker_options(); 
	$do_share=0;
	$wordbooker_post_options= get_post_meta($post->ID, '_wordbooker_options', true);  
	#var_dump($$wordbooker_settings[);
	if ($wordbooker_post_options['wordbooker_share_button_post']==2 && !is_page()) {return ;}
	if ($wordbooker_post_options['wordbooker_share_button_page']==2 && is_page()) {return ;}
	if (!isset($wordbooker_settings['wordbooker_like_share_too'])) {return ;}
	if (isset($wordbooker_settings['wordbooker_share_button_post']) && is_single() && !is_front_page() ) {$do_share=1;}
	if (isset($wordbooker_settings['wordbooker_share_button_page']) && is_page()  && !is_front_page() )  {$do_share=1;}
	if (isset($wordbooker_settings['wordbooker_share_button_frontpage'])  && is_front_page() ) {$do_share=1;}
	if (isset($wordbooker_settings['wordbooker_share_button_category']) &&  is_category()  ) {$do_share=1;}
	if (isset($wordbooker_settings['wordbooker_no_share_stick']) &&  is_sticky()  ) {$do_share=0; }
	if ( $do_share==1  &&
	((isset($wordbooker_settings['wordbooker_share_button_post']) && is_single()  )
          || (isset($wordbooker_settings['wordbooker_share_button_page']) && is_page() ) 
	  || (isset($wordbooker_settings['wordbooker_share_button_frontpage'])  && is_front_page() ) 
	  || (isset($wordbooker_settings['wordbooker_share_button_category']) &&  is_category()  ))
	  )
	{
	$post_link = get_permalink($post->ID);
	$btype="button";
	if (is_single() || is_page()) {
	$btype="button_count";
	}
	if (isset($wordbooker_settings['wordbooker_iframe'])) {
		 $share_code='<!-- Wordbooker created FB tags --> <a name="fb_share" type="'.$btype.'" share_url="'.$post_link.'"></a>';
	}
	else {
		$share_code='<!-- Wordbooker created FB tags --> <fb:share-button class="meta" type="'.$btype.'" href="'.$post_link.'" > </fb:share-button>';
	}
	 return $share_code;
	}
}
function display_wordbooker_fb_send() {
	global $post,$q_config;
	$wordbooker_settings = wordbooker_options(); 
	$wordbooker_post_options= get_post_meta($post->ID, '_wordbooker_options', true);  
	$post_link = get_permalink($post->ID);
	if ($wordbooker_post_options['wordbooker_like_button_post']==2 && !is_page()) {return ;}
	if ($wordbooker_post_options['wordbooker_like_button_page']==2 && is_page()) {return ;}
	if ($wordbooker_settings['wordbooker_fblike_send_combi']=='true') {return;}

	$do_like=0;
	if (isset($wordbooker_settings['wordbooker_like_button_post']) && is_single() && !is_front_page() ) {$do_like=1;}
	if (isset($wordbooker_settings['wordbooker_like_button_page']) && is_page() && !is_front_page())  {$do_like=1;}
	if (isset($wordbooker_settings['wordbooker_like_button_frontpage'])  && is_front_page() ) {$do_like=1;}
	if (isset($wordbooker_settings['wordbooker_like_button_category']) &&  is_category() && !is_front_page() ) {$do_like=1;}
	if (isset($wordbooker_settings['wordbooker_no_like_stick']) &&  is_sticky()  ) { $do_like=0;}
	if ( $do_like==1  &&
		((isset($wordbooker_settings['wordbooker_like_button_post']) && is_single()  )
          || (isset($wordbooker_settings['wordbooker_like_button_page']) && is_page() ) 
	  || (isset($wordbooker_settings['wordbooker_like_button_frontpage'])  && is_front_page() ) 
	  || (isset($wordbooker_settings['wordbooker_like_button_category']) &&  is_category()  ))
	  )
	{
		if (isset($wordbooker_settings['wordbooker_iframe'])) { 
			$px=35;
			$wplang=wordbooker_get_language();
			if ($wordbooker_settings['wordbooker_fblike_faces']=='true') {$px=80;}
			$like_code='<!-- Wordbooker created FB tags --> <iframe src="http://www.facebook.com/plugins/send.php?locale='.$wplang.'&href='.$post_link.'&amp;layout='.$wordbooker_settings['wordbooker_fblike_button'].'&amp;show_faces='.$wordbooker_settings['wordbooker_fblike_faces'].'&amp;width='.$wordbooker_settings["wordbooker_like_width"].'&amp;action='.$wordbooker_settings['wordbooker_fblike_action'].'&amp;colorscheme='.$wordbooker_settings['wordbooker_fblike_colorscheme'].'&amp;font='.$wordbooker_settings['wordbooker_fblike_font'].'&amp;height='.$px.'px" scrolling="no" frameborder="no" style="border:none; overflow:hidden; width:'.$wordbooker_settings["wordbooker_like_width"].'px; height:'.$px.'px;" allowTransparency="true"></iframe>';

		}
		else {
		#var_dump($wordbooker_settings);
		$like_code='<!-- Wordbooker created FB tags --> <fb:send layout="'.$wordbooker_settings['wordbooker_fblike_button'] .'" show_faces="'.$wordbooker_settings['wordbooker_fblike_faces'].'" action="'.$wordbooker_settings['wordbooker_fblike_action'].'" font="'.$wordbooker_settings['wordbooker_fblike_font'].'" colorscheme="'.$wordbooker_settings['wordbooker_fblike_colorscheme'].'"  href="'.$post_link.'" width="'.$wordbooker_settings["wordbooker_like_width"].' "></fb:send> ';}
		echo $like_code;
	}
}

function wordbooker_fb_send_inline() {
	global $post;
	$wordbooker_settings = wordbooker_options(); 
	$wordbooker_post_options= get_post_meta($post->ID, '_wordbooker_options', true);  
	if ($wordbooker_post_options['wordbooker_like_button_post']==2 && !is_page()) {return ;}
	if ($wordbooker_post_options['wordbooker_like_button_page']==2 && is_page()) {return ;}
	if ($wordbooker_settings['wordbooker_fblike_send_combi']=='true') {return;}
	$post_link = get_permalink($post->ID);
	$do_like=0;
	if (isset($wordbooker_settings['wordbooker_like_button_post']) && is_single() && !is_front_page() ) {$do_like=1;}
	if (isset($wordbooker_settings['wordbooker_like_button_page']) && is_page() && !is_front_page())  {$do_like=1;}
	if (isset($wordbooker_settings['wordbooker_like_button_frontpage'])  && is_front_page() ) {$do_like=1;}
	if (isset($wordbooker_settings['wordbooker_like_button_category']) &&  is_category() && !is_front_page() ) {$do_like=1;}
	if (isset($wordbooker_settings['wordbooker_no_like_stick']) &&  is_sticky()  ) { $do_like=0;}

	if ( $do_like==1  &&
		((isset($wordbooker_settings['wordbooker_like_button_post']) && is_single()  )
          || (isset($wordbooker_settings['wordbooker_like_button_page']) && is_page() ) 
	  || (isset($wordbooker_settings['wordbooker_like_button_frontpage'])  && is_front_page() ) 
	  || (isset($wordbooker_settings['wordbooker_like_button_category']) &&  is_category()  ))
	  )
	{
		if (isset($wordbooker_settings['wordbooker_iframe'])) { 
			$px=35;
			$wplang=wordbooker_get_language();
			if ($wordbooker_settings['wordbooker_fblike_faces']=='true') {$px=80;}
			$like_code='<!-- Wordbooker created FB tags --> <iframe src="http://www.facebook.com/plugins/send.php?locale='.$wplang.'&href='.$post_link.'&amp;layout='.$wordbooker_settings['wordbooker_fblike_button'].'&amp;show_faces='.$wordbooker_settings['wordbooker_fblike_faces'].'&amp;width='.$wordbooker_settings["wordbooker_like_width"].'&amp;action='.$wordbooker_settings['wordbooker_fblike_action'].'&amp;colorscheme='.$wordbooker_settings['wordbooker_fblike_colorscheme'].'&amp;font='.$wordbooker_settings['wordbooker_fblike_font'].'&amp;height='.$px.'px" scrolling="no" frameborder="no" style="border:none; overflow:hidden; width:'.$wordbooker_settings["wordbooker_like_width"].'px; height:'.$px.'px;" allowTransparency="true"></iframe>';

		}
		else {
		#var_dump($wordbooker_settings);
		$like_code='<!-- Wordbooker created FB tags --> <fb:send layout="'.$wordbooker_settings['wordbooker_fblike_button'] .'" show_faces="'.$wordbooker_settings['wordbooker_fblike_faces'].'" action="'.$wordbooker_settings['wordbooker_fblike_action'].'" font="'.$wordbooker_settings['wordbooker_fblike_font'].'" colorscheme="'.$wordbooker_settings['wordbooker_fblike_colorscheme'].'"  href="'.$post_link.'" width="'.$wordbooker_settings["wordbooker_like_width"].' "></fb:send> ';}
		return $like_code;
	}
}

function display_wordbooker_fb_like() {
	global $post;
	$wordbooker_settings = wordbooker_options();

	$wordbooker_post_options= get_post_meta($post->ID, '_wordbooker_options', true);  
	if ($wordbooker_post_options['wordbooker_like_button_post']==2 && !is_page()) {return ;}
	if ($wordbooker_post_options['wordbooker_like_button_page']==2 && is_page()) {return ;}
	if (!isset($wordbooker_settings['wordbooker_like_button_show'])) {return;}
	$do_like=0;
	$post_link = get_permalink($post->ID);
	if (isset($wordbooker_settings['wordbooker_like_button_post']) && is_single() && !is_front_page() ) {$do_like=1;}
	if (isset($wordbooker_settings['wordbooker_like_button_page']) && is_page() && !is_front_page())  {$do_like=1;}
	if (isset($wordbooker_settings['wordbooker_like_button_frontpage'])  && is_front_page() ) {$do_like=1;}
	if (isset($wordbooker_settings['wordbooker_like_button_category']) &&  is_category() && !is_front_page() ) {$do_like=1;}
	if (isset($wordbooker_settings['wordbooker_no_like_stick']) &&  is_sticky()  ) { $do_like=0;}
	if ( $do_like==1  &&
		((isset($wordbooker_settings['wordbooker_like_button_post']) && is_single()  )
          || (isset($wordbooker_settings['wordbooker_like_button_page']) && is_page() ) 
	  || (isset($wordbooker_settings['wordbooker_like_button_frontpage'])  && is_front_page() ) 
	  || (isset($wordbooker_settings['wordbooker_like_button_category']) &&  is_category()  ))
	  )
	{
		if (isset($wordbooker_settings['wordbooker_iframe'])) { 
			$px=35;
			$wplang=wordbooker_get_language();
			if ($wordbooker_settings['wordbooker_fblike_faces']=='true') {$px=95;}
			$like_code='<!-- Wordbooker created FB tags --> <iframe src="http://www.facebook.com/plugins/like.php?locale='.$wplang.'&href='.$post_link.'&amp;layout='.$wordbooker_settings['wordbooker_fblike_button'].'&amp;show_faces='.$wordbooker_settings['wordbooker_fblike_faces'].'&amp;width='.$wordbooker_settings["wordbooker_like_width"].'&amp;action='.$wordbooker_settings['wordbooker_fblike_action'].'&amp;colorscheme='.$wordbooker_settings['wordbooker_fblike_colorscheme'].'&amp;font='.$wordbooker_settings['wordbooker_fblike_font'].'&amp;height='.$px.'px" scrolling="no" frameborder="no" style="border:none; overflow:hidden; width:'.$wordbooker_settings["wordbooker_like_width"].'px; height:'.$px.'px;" allowTransparency="true"></iframe>';

		}
		else {
		#var_dump($wordbooker_settings);
		$like_code='<!-- Wordbooker created FB tags --> <fb:like layout="'.$wordbooker_settings['wordbooker_fblike_button'] .'" show_faces="'.$wordbooker_settings['wordbooker_fblike_faces'].'" action="'.$wordbooker_settings['wordbooker_fblike_action'].'" font="'.$wordbooker_settings['wordbooker_fblike_font'].'" colorscheme="'.$wordbooker_settings['wordbooker_fblike_colorscheme'].'"  href="'.$post_link.'" width="'.$wordbooker_settings["wordbooker_like_width"].'" ';
if ($wordbooker_settings['wordbooker_fblike_send_combi']=='true' ) { $like_code.=' send="'.$wordbooker_settings['wordbooker_fblike_send'].'" ';}
$like_code.='></fb:like> ';}
		echo $like_code;
	}
}

function wordbooker_fb_like_inline() {
	global $post;
	$wordbooker_settings = wordbooker_options();

	$wordbooker_post_options= get_post_meta($post->ID, '_wordbooker_options', true);  
	if ($wordbooker_post_options['wordbooker_like_button_post']==2 && !is_page()) {return ;}
	if ($wordbooker_post_options['wordbooker_like_button_page']==2 && is_page()) {return ;}
	if (!isset($wordbooker_settings['wordbooker_like_button_show'])) {return;}
	$do_like=0;
	$post_link = get_permalink($post->ID);
	if (isset($wordbooker_settings['wordbooker_like_button_post']) && is_single() && !is_front_page() ) {$do_like=1;}
	if (isset($wordbooker_settings['wordbooker_like_button_page']) && is_page() && !is_front_page())  {$do_like=1;}
	if (isset($wordbooker_settings['wordbooker_like_button_frontpage'])  && is_front_page() ) {$do_like=1;}
	if (isset($wordbooker_settings['wordbooker_like_button_category']) &&  is_category() && !is_front_page() ) {$do_like=1;}
	if (isset($wordbooker_settings['wordbooker_no_like_stick']) &&  is_sticky()  ) { $do_like=0;}
	if ( $do_like==1  &&
		((isset($wordbooker_settings['wordbooker_like_button_post']) && is_single()  )
          || (isset($wordbooker_settings['wordbooker_like_button_page']) && is_page() ) 
	  || (isset($wordbooker_settings['wordbooker_like_button_frontpage'])  && is_front_page() ) 
	  || (isset($wordbooker_settings['wordbooker_like_button_category']) &&  is_category()  ))
	  )
	{
		if (isset($wordbooker_settings['wordbooker_iframe'])) { 
			$px=35;
			$wplang="en_US";
			if (strlen(WPLANG) > 2) {$wplang=WPLANG;}
			# then we check if WPLANG is actually set to anything sensible.
			if ($wplang=="WPLANG" ) {$wplang="en_US";}
			if ($wordbooker_settings['wordbooker_fblike_faces']=='true') {$px=95;}
			$like_code='<!-- Wordbooker created FB tags --> <iframe src="http://www.facebook.com/plugins/like.php?locale='.$wplang.'&href='.$post_link.'&amp;layout='.$wordbooker_settings['wordbooker_fblike_button'].'&amp;show_faces='.$wordbooker_settings['wordbooker_fblike_faces'].'&amp;width='.$wordbooker_settings["wordbooker_like_width"].'&amp;action='.$wordbooker_settings['wordbooker_fblike_action'].'&amp;colorscheme='.$wordbooker_settings['wordbooker_fblike_colorscheme'].'&amp;font='.$wordbooker_settings['wordbooker_fblike_font'].'&amp;height='.$px.'px" scrolling="no" frameborder="no" style="border:none; overflow:hidden; width:'.$wordbooker_settings["wordbooker_like_width"].'px; height:'.$px.'px;" allowTransparency="true"></iframe>';

		}
		else {
		#var_dump($wordbooker_settings);
		$like_code='<!-- Wordbooker created FB tags --> <fb:like layout="'.$wordbooker_settings['wordbooker_fblike_button'] .'" show_faces="'.$wordbooker_settings['wordbooker_fblike_faces'].'" action="'.$wordbooker_settings['wordbooker_fblike_action'].'" font="'.$wordbooker_settings['wordbooker_fblike_font'].'" colorscheme="'.$wordbooker_settings['wordbooker_fblike_colorscheme'].'"  href="'.$post_link.'" width="'.$wordbooker_settings["wordbooker_like_width"].'" ';
if ($wordbooker_settings['wordbooker_fblike_send_combi']=='true' ) { $like_code.=' send="'.$wordbooker_settings['wordbooker_fblike_send'].'" ';}
$like_code.='> </fb:like> ';}
		return $like_code;
	}
}

function wordbooker_fb_read_inline() {
$wordbooker_settings = wordbooker_options();
if (is_single() && isset($wordbooker_settings['wordbooker_read_button']) ) {
	$read_code='<form><input type="button" value="'.__("Post To Your Timeline ",'wordbooker').'" onclick="wordbooker_read()" /></form>';
	return $read_code;
}
}

function wordbooker_fb_read() {
$wordbooker_settings = wordbooker_options();
if (is_single() && isset($wordbooker_settings['wordbooker_read_button']) ) {
	$read_code='<form><input type="button" value="'.__("Post To Your Timeline ",'wordbooker').'" onclick="wordbooker_read()" /></form>';
	echo $read_code;
}
}

#function wordbooker_fb_comment_insert($template){
#	$comment_code=wordbooker_fb_comment(true);
#	if ($template) {echo $comment_code;} else {return $comment_code;}
#}

function wordbooker_append_post($post_cont) {
	global $post;
	$do_share=0;
	#var_dump(is_page());var_dump(is_category());var_dump(is_front_page());var_dump(is_single());
	$wordbooker_settings = wordbooker_options(); 
	if (!isset($wordbooker_settings['wordbooker_like_button_show']) && !isset($wordbooker_settings['wordbooker_like_share_too'])) {return $post_cont;}
	$post_cont2=$post_cont;
	$post_link = get_permalink($post->ID);
	$share_code=wordbooker_fb_share_inline();
	$like_code=wordbooker_fb_like_inline();
	$send_code=wordbooker_fb_send_inline();
	$comment_code=wordbooker_fb_comment_inline();
	$read_code=wordbooker_fb_read_inline();
if ($wordbooker_settings['wordbooker_fblike_location']!=$wordbooker_settings['wordbooker_fbshare_location']){
	if ($wordbooker_settings['wordbooker_fbshare_location']=='top'){
		$post_cont2= "<div class='wp_fbs_top'>".$share_code."</div>".$post_cont2; 
	} 
	if ($wordbooker_settings['wordbooker_fbshare_location']=='bottom') {
		$post_cont2=$post_cont2."<div class='wp_fbs_bottom'>".$share_code.'</div>';
	}


	if ($wordbooker_settings['wordbooker_fblike_send_combi']=='true'){
		if ($wordbooker_settings['wordbooker_fblike_location']=='bottom'){
			$post_cont2= $post_cont2."<div class='wp_fbl_bottom'>".$like_code.'</div>'; 
		} 
		if ($wordbooker_settings['wordbooker_fblike_location']=='top') {
			$post_cont2= "<div class='wp_fbl_top'>".$like_code.'</div>'.$post_cont2;
		}
	}
}	else {
	#	if ($wordbooker_settings['wordbooker_fblike_location']==$wordbooker_settings['wordbooker_fbshare_location']){
			if ($wordbooker_settings['wordbooker_fblike_location']=='bottom'){
				$post_cont2=$post_cont2."<div class='wb_fb_bottom'>".$like_code.'<div style="float:right;">'.$share_code.'</div></div>'; 
			} 
			if ($wordbooker_settings['wordbooker_fblike_location']=='top'){
				$post_cont2= "<div class='wb_fb_top'>".$like_code.'<div style="float:right;">'.$share_code.'</div></div>'.$post_cont2; 
			}
		#}

	#}
}
	if ($wordbooker_settings['wordbooker_fblike_send_combi']=='false' && $wordbooker_settings['wordbooker_fblike_send']=='true' ){
		if ($wordbooker_settings['wordbooker_fblike_location']==$wordbooker_settings['wordbooker_fbshare_location']){
			if ($wordbooker_settings['wordbooker_fblike_location']=='bottom'){
				$post_cont2=$post_cont2."<div class='wb_fb_bottom'>".$send_code.'<div style="float:right;">'.$share_code.'</div></div>'; 
			} 
			if ($wordbooker_settings['wordbooker_fblike_location']=='top'){
				$post_cont2= "<div class='wb_fb_top'>".$send_code.'<div style="float:right;">'.$share_code.'</div></div>'.$post_cont; 
			}
		} else {
		if ($wordbooker_settings['wordbooker_fblike_location']=='bottom'){
			$post_cont2= $post_cont2."<div class='wp_fbl_bottom'>".$send_code.'</div>'; 
		} 
		if ($wordbooker_settings['wordbooker_fblike_location']=='top') {
			$post_cont2= "<div class='wp_fbl_top'>".$send_code.'</div>'.$post_cont2;
		}
	}
	}
/*
	if ($wordbooker_settings['wordbooker_fbread_location']=='top'){
		$post_cont2= "<div class='wp_fbr_top'>".$read_code."</div>".$post_cont2; 
	} 
	if ($wordbooker_settings['wordbooker_fbread_location']=='bottom') {
		$post_cont2=$post_cont2."<div class='wp_fbr_bottom'>".$read_code.'</div>';
	}
*/
	if ($wordbooker_settings['wordbooker_comment_location']=='bottom') { $post_cont2=$post_cont2."<div class='wb_fb_comment'><br/>".$comment_code."</div>"; }
	return $post_cont2;
}

function wordbooker_get_cache($user_id,$field=null,$table=0) {
	global $wpdb,$blog_id;
	#$blog_id=1;
	if (!isset($user_id)) {return;}
	$tname=WORDBOOKER_USERSTATUS;
	$query_fields='facebook_id,name,url,pic,status,updated,facebook_id';
	$blog_lim=' and blog_id='.$blog_id;
	if ($table==1) {$tname=WORDBOOKER_USERDATA;$query_fields='facebook_id,name,url,pic,status,updated,auths_needed,use_facebook';$blog_lim='';}
	if (isset($field)) {$query_fields=$field;}
	if ($user_id==-99){ 
		$query="select ".$query_fields." from ".$tname."  where blog_id = ".$blog_id; 
	#	var_dump($query);
		$result = $wpdb->get_results($query,ARRAY_N );
		foreach($result as $key){ $newkey[]=$key[0];}
		$result = implode(",",$newkey); 
	}
	else {
	$query="select ".$query_fields." from ".$tname."  where user_ID=".$user_id.$blog_lim;
#	var_dump($query);
	$result = $wpdb->get_row($query); }
	return $result;
}



function wordbooker_check_permissions($wbuser,$user) {
	global $user_ID;
	$perm_miss=wordbooker_get_cache($user_ID,'auths_needed',1);
	if ($perm_miss->auths_needed==0) { return;}
	$perms_to_check= array(WORDBOOKER_FB_PUBLISH_STREAM,WORDBOOKER_FB_STATUS_UPDATE,WORDBOOKER_FB_READ_STREAM,WORDBOOKER_FB_CREATE_NOTE,WORDBOOKER_FB_PHOTO_UPLOAD,WORDBOOKER_FB_VIDEO_UPLOAD,WORDBOOKER_FB_MANAGE_PAGES,WORDBOOKER_FB_READ_FRIENDS);
	$perm_messages= array( __('Publish content to your Wall/Fan pages', 'wordbooker'), __('Update your status', 'wordbooker'), __('Read your News Feed and Wall', 'wordbooker'),__('Create notes', 'wordbooker'),__('Upload photos', 'wordbooker'),__('Upload videos', 'wordbooker'),__('Manage_pages', 'wordbooker'),__('Read friend lists', 'wordbooker'));
	$preamble= __("but requires authorization to ", 'wordbooker');
	$postamble= __(" on Facebook. Click on the following link to grant permission", 'wordbooker');
		$loginUrl2='https://www.facebook.com/dialog/oauth?client_id='.WORDBOOKER_FB_ID.'&redirect_uri=https://wordbooker.tty.org.uk/index2.html?br='.urlencode(get_bloginfo('wpurl')).'&scope='.implode(',',$perms_to_check).'&response_type=token';
	if(is_array($perms_to_check)) {
		foreach(array_keys($perms_to_check) as $key){
			# Bit map check to put out the right text for the missing permissions.
			if (pow(2,$key) & $perm_miss->auths_needed ) {
				$midamble.=$perm_messages[$key].", ";
				}
		}
			$midamble=rtrim($midamble,",");
			$midamble=trim(preg_replace("/(.*?)((,|\s)*)$/m", "$1", $midamble));
			$midamble=substr_replace($midamble, " and ", strrpos($midamble, ","), strlen(","));	
			       echo " ".$preamble.$midamble.$postamble.'</p><div style="text-align: center;"><a href="'.$loginUrl2.'" > <img src="http://static.ak.facebook.com/images/devsite/facebook_login.gif"  alt="Facebook Login Button" /></a><br /></div>';
			
	}
	echo "and then save your settings<br />";
	echo '<form action="'.WORDBOOKER_SETTINGS_URL.'" method="post"> <input type="hidden" name="action" value="" />';
	echo '<p style="text-align: center;"><input type="submit" name="perm_save" class="button-primary" value="'. __('Save Configuration', 'wordbooker').'" /></p></form>';
}

function wordbooker_contributed($url=0) {
	global $user_ID;
	if ($url==0){
		$contributors=array('1595132200','100000818019269','39203171','666800299','500073624','711830142','503549492','100000589976474','254577506873','1567300610','701738627','100000442094620','754015348','29404010','748636937',
 '676888540','768354692','1607820784','1709067850','769804853','100001597808077','1162591229','736138968','532656880','1000013707847','1352285955','836328641',
 '23010694256','129976890383044','679511648','100001305747796','138561766210548','535106029','202891313077099','567894174','10150158518404391','689075829','214145618608444',
'23087261000','195010903860640'
);
		$facebook_id=wordbooker_get_cache($user_ID,'facebook_id');
		return in_array($facebook_id->facebook_id,$contributors);
	}

	if ($url==1){
		$blogs=array(
"Steve's Blog"=>'blogs.canalplan.org.uk/steve',"Powered by Dan!"=>'dangarion.com',"Kathryn's Comments"=>'www.kathrynhuxtable.org/blog',"Luke Writes"=>'www.lukewrites.com',
"It's Nature"=>'www.itsnature.org',"Eat in OC"=>'eatinoc.com',"Christian Albert Muller"=>'christian-albert-mueller.com/blog/',"[overcrooked|de]"=>'blog.overcrooked.de/',
"Jesus is My Buddy"=>'www.jesusismybuddy.com',"Shirts of Bamboo"=>'www.shirtsofbamboo.com', "What's that bug?"=>'www.whatsthatbug.com',"Philip Bussman"=>'www.philipbussmann.com',
"PhantaNews"=>'phantanews.de/wp/', "HKMacs"=>'hkmacs.com/Blog', "Techerator"=>'www.techerator.com', "Mosalar.com"=>'www.mosalar.com/',
"Nono & His Self-Centered Universe"=>'www.noelacosta.com/',"Chart Porn"=>'www.chartporn.org',"Pawesome"=>'www.pawesome.net',"Margaret & Ian's Website"=>'www.margaretandian.com/',
"The GBMINI website"=>'www.gbmini.net',"Roca"=>'rocamusic.ca/home',"Drew Rozell"=>'www.drewrozell.com/',"Kartext"=>'www.nitsche.org/',
"Doug Berch - Musician and Appalachian Mountain Dulcimer Maker"=>'dougberch.com',"My Lifestyle Blog"=>'www.mylifestyleblog.de',
"tina rawatta photography" => 'www.tinarawatta.com',"Gary Said..."=>'GarySaid.com',"Bachateros Online Magazine"=>'www.bachateros.com.au/',"Linh's e-place"=>'www.linh.se',
"InkMusings" => 'www.inkmusings.com',"JĂźrgen Koller's website"=>'www.kollermedia.at',"Walk With Ben"=>'www.walkwithben.com',"GardenFork"=>'www.http://www.gardenfork.tv/',
"A Low Man's Lyric"=>'vivekiyer.net/',"OutofRange.net"=>'www.outofrange.net/',"This Ambitious Orchestra"=>'ambitiousorchestra.com',"Lydia Salnikova"=>'www.lydiasalnikova.com/',
"Westpark Gamers"=>'www.westpark-gamers.de/', "The Camera Zealot"=>'www.camerazealot.com', " Best Raw Organic" => 'BestRawOrganic.com',"Gibson Designs"=>'gibsondesigns.net',
"Looking out from Under"=>'www.lookingoutfromunder.com',"Our Excellent Adventures"=>'www.ourexcellentadventures.com',
"wisiwi.com - Das Magazin fĂźr Unternehmer"=>'www.wisiwi.com/',"Just One Cookbook"=>'justonecookbook.com/blog/',"Surfdog 2011"=>'hastenteufel.name/blog',
"Vice Versa Advertising Photography"=>'www.viceversa.gr/',"Swimming Pools Designs"=>'www.swimming-pools-designs.com',"Eastleigh District Scouts"=>'www.eastleigh-scouts.org.uk',"Sparkpr"=>'www.sparkpr.com',"Charlie Glickman - Adult Sexuality Education"=>'www.charlieglickman.com/',"iEatAtTheBar"=>'www.ieatatthebar.com/',"Devil's Cove | Boats, Booze & Fun on Lake Travis"=>'http://www.devilscove.com/',"Bored. Cure your boredom!"=>'bored.overnow.com/',"KinkyThought"=>'kinkythought.com/',
"The Chronicles of Mommia"=>'www.thechroniclesofmommia.com/',"Total Humour"=>'www.totalhumour.com/',"Six Seconds"=>'www.6seconds.org/',"The APBA Blog"=>'www.apbablog.com',"The Doc is In"=>'www.thedocisin.net'

);
		$keys = array_keys($blogs);
		shuffle($keys);
	
		foreach ( $keys as $key) {
			echo "<a href='http://".htmlspecialchars($blogs[$key])."' target='_new'>".htmlspecialchars($key)."</a>,&nbsp;";
		}
		# And then put canalplan on the end of it - saves us having to do clever things to remove commas
		echo "<a href='http://www.canalplan.org.uk/' target='_new' >CanalPlan AC</a><br />";
	}
}
/******************************************************************************
 * WordPress hooks: update Facebook when a blog entry gets published.
 */

 function wordbooker_remove_HTML($s , $keep = '' , $expand = 'script|style|noframes|select|option'){
        /**///prep the string
        $s = ' ' . $s;
       
        /**///initialize keep tag logic
        if(strlen($keep) > 0){
            $k = explode('|',$keep);
            for($i=0;$i<count($k);$i++){
                $s = str_replace('<' . $k[$i],'[{(' . $k[$i],$s);
                $s = str_replace('</' . $k[$i],'[{(/' . $k[$i],$s);
            }
        }
       
        //begin removal
        /**///remove comment blocks
        while(stripos($s,'<!--') > 0){
            $pos[1] = stripos($s,'<!--');
            $pos[2] = stripos($s,'-->', $pos[1]);
            $len[1] = $pos[2] - $pos[1] + 3;
            $x = substr($s,$pos[1],$len[1]);
            $s = str_replace($x,'',$s);
        }
       
        /**///remove tags with content between them
        if(strlen($expand) > 0){
            $e = explode('|',$expand);
            for($i=0;$i<count($e);$i++){
                while(stripos($s,'<' . $e[$i]) > 0){
                    $len[1] = strlen('<' . $e[$i]);
                    $pos[1] = stripos($s,'<' . $e[$i]);
                    $pos[2] = stripos($s,$e[$i] . '>', $pos[1] + $len[1]);
                    $len[2] = $pos[2] - $pos[1] + $len[1];
                    $x = substr($s,$pos[1],$len[2]);
                    $s = str_replace($x,'',$s);
                }
            }
        }
       
        /**///remove remaining tags
        while(stripos($s,'<') > 0){
            $pos[1] = stripos($s,'<');
            $pos[2] = stripos($s,'>', $pos[1]);
            $len[1] = $pos[2] - $pos[1] + 1;
            $x = substr($s,$pos[1],$len[1]);
            $s = str_replace($x,'',$s);
        }
       
        /**///finalize keep tag
        for($i=0;$i<count($k);$i++){
            $s = str_replace('[{(' . $k[$i],'<' . $k[$i],$s);
            $s = str_replace('[{(/' . $k[$i],'</' . $k[$i],$s);
        }
       
        return trim($s);
    }

function wordbooker_post_excerpt($excerpt, $maxlength,$doyoutube=1) {
	if (function_exists('strip_shortcodes')) {
		$excerpt = strip_shortcodes($excerpt);
	}
	global $wordbooker_post_options;
	if (!isset($maxlength)) {$maxlength=$wordbooker_post_options['wordbooker_extract_length'];}
	if (!isset($maxlength)) {$maxlength=256;}
	$excerpt = trim($excerpt);
	# Now lets strip any tags which dont have balanced ends
	#  Need to put NGgallery tags in there - there are a lot of them and they are all different.
	$open_tags="[simage,[[CP,[gallery,[imagebrowser,[slideshow,[tags,[albumtags,[singlepic,[album";
	$close_tags="],]],],],],],],],]";
	$open_tag=explode(",",$open_tags);
	$close_tag=explode(",",$close_tags);
	foreach (array_keys($open_tag) as $key) {
		if (preg_match_all('/' . preg_quote($open_tag[$key]) . '(.*?)' . preg_quote($close_tag[$key]) .'/i',$excerpt,$matches)) {
			$excerpt=str_replace($matches[0],"" , $excerpt);
		 }
	}

	$excerpt = preg_replace('#(<wpg.*?>).*?(</wpg2>)#', '$1$2', $excerpt);
	$excerpt=wordbooker_translate($excerpt);
	$excerpt = strip_tags($excerpt);
	# Now lets strip off the youtube stuff.
	preg_match_all( '#http://(www.youtube|youtube|[A-Za-z]{2}.youtube)\.com/(watch\?v=|w/\?v=|\?v=)([\w-]+)(.*?)player_embedded#i', $excerpt, $matches );
	$excerpt=str_replace($matches[0],"" , $excerpt);
	preg_match_all( '#http://(www.youtube|youtube|[A-Za-z]{2}.youtube)\.com/(watch\?v=|w/\?v=|\?v=|embed/)([\w-]+)(.*?)#i', $excerpt, $matches );
	$excerpt=str_replace($matches[0],"" , $excerpt);
	$excerpt = apply_filters('wordbooker_post_excerpt', $excerpt);
	if (strlen($excerpt) > $maxlength) {
		# If we've got multibyte support then we need to make sure we get the right length - Thanks to Kensuke Akai for the fix
		if(function_exists('mb_strimwidth')){$excerpt=mb_strimwidth($excerpt, 0, $maxlength, " ...");}
		else { $excerpt=current(explode("SJA26666AJS", wordwrap($excerpt, $maxlength, "SJA26666AJS")))." ...";}
	}
	
	return $excerpt;
}

function wordbooker_translate($text) {
	if (function_exists('qtrans_use')) {
		global $q_config;
		$text=qtrans_use($q_config['language'],$text);
	}	
	return $text;
}

function wordbooker_publish_action($post_id) {
	global $user_ID, $user_identity, $user_login, $wpdb,$wordbooker_post_options,$blog_id,$doing_post;
	if(isset($doing_post)) {wordbooker_debugger("Looks like we've already got a post going on so we can give up","",$post_id,99) ; return;}
	$doing_post="running";
	$x = get_post_meta($post_id, '_wordbooker_options', true); 
		$post=get_post($post_id);
	# Get the settings from the post_meta.
	if (is_array($x)){
		foreach (array_keys($x) as $key ) {
			if (substr($key,0,8)=='wordbook') {
				$wordbooker_post_options[$key]=str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&nbsp;&nbsp;'),array('&','"','\'','<','>',"\t"),$x[$key]);
			}
		}
	}
	
		if (is_array($wordbooker_post_options)){
		foreach (array_keys($wordbooker_post_options) as $key){
			wordbooker_debugger("Post option : ".$key,$wordbooker_post_options[$key],$post->ID) ;
		}
	}
	
	if ($wordbooker_post_options["wordbooker_publish_default"]=="200") { $wordbooker_post_options["wordbooker_publish_default"]='on';}


	# If the user_ID is set then lets use that, if not get the user_id from the post
	$whichuser=$post->post_author;
	if ($user_ID >=1) {$whichuser=$user_ID;} 
	# If the default user is set to 0 then we use the current user (or the author of the post if that isn't set - i.e. if this is a scheduled post)
	if  ($wordbooker_post_options["wordbooker_default_author"] == 0 ) {$wpuserid=$whichuser;} else {$wpuserid=$wordbooker_post_options["wordbooker_default_author"];}
	
		if ($wordbooker_post_options["wordbooker_publish_default"]!="on") {
		wordbooker_debugger("Publish Default is not Set, Giving up ",$wpuserid,$post->ID) ;
	 	return;
	}
	wordbooker_debugger("User has been set to : ",$wpuserid,$post->ID) ;
	#if (!($wbuser = wordbooker_get_userdata($wpuserid)) || !$wbuser->access_token) {
	if (!$wbuser = wordbooker_get_userdata($wpuserid) ) {
		wordbooker_debugger("Unable to get FB session for : ",$wpuserid,$post->ID) ;
		return 28;
	}
	wordbooker_debugger("Posting as user : ",$wpuserid,$post->ID) ;

	wordbooker_debugger("Calling wordbooker_fbclient_publishaction"," ",$post->ID) ;
	wordbooker_fbclient_publishaction($wbuser, $post->ID);
	unset($doing_post);
	return 30;
}
/*
function wordbooker_transition_post_status($newstatus, $oldstatus, $post_id) {

	if ($newstatus == 'publish') {
		return wordbooker_publish_action($post_id);
	}

	return 31;	
}
*/

function wordbooker_delete_post($post_id) {	
	global $blog_id;
	wordbooker_delete_from_errorlogs($post_id,$blog_id);
	wordbooker_delete_from_postlogs($post_id,$blog_id);
	wordbooker_delete_from_commentlogs($post_id,$blog_id);
}

function wordbooker_process_post_queue($post_id) {
	global $wpdb,$blog_id;
	# We need to get the lowest post_id from the post_queue which has the lowest priority ID
}

function wordbooker_process_post_data($newstatus, $oldstatus, $post) {
	global $user_ID, $user_identity, $user_login, $wpdb, $blog_id;
	# If this is an autosave then we give up and return as otherwise we lose user settings.
	if ($_POST['action']=='autosave') { return;}
	if ($_POST['action']=='editpost') { 
				foreach (array_keys($_POST) as $key ) {
				if (substr($key,0,8)=='wordbook') {
					$wordbooker_sets[$key]=str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&nbsp;&nbsp;'),array('&','"','\'','<','>',"\t"),$_POST[$key]);
				}
			}
	#var_dump($wordbooker_sets);
	#var_dump($post->ID);
	update_post_meta($post->ID, '_wordbooker_options', $wordbooker_sets); 
	}
if (!$newstatus=="publish") { return;}
	# If this is a password protected post we give up
	if ($post->post_password != '') {return;}
	# Check for non public custom post types.
	if ( $post->post_status == 'publish' && $post->post_type != 'post' ) {
		$post_type_info = get_post_type_object( $post->post_type );
		if ( $post_type_info && !$post_type_info->public ) { return; }
	}
	# Has this been fired by a post revision rather than a proper publish
	if (wp_is_post_revision($post->ID)) {return;}

	$wordbooker_settings=wordbooker_options();
	$wb_params = get_post_meta($post->ID, '_wordbooker_options', true); 
	if (! wordbooker_get_userdata($post->post_author)) { $wb_user_id=$wordbooker_settings["wordbooker_default_author"];}
	if  ($wordbooker_settings["wordbooker_default_author"] == 0 ) {$wb_user_id=$post->post_author;} else {$wb_user_id=$wordbooker_settings["wordbooker_default_author"];}
	if ( (!is_array($wb_params)) &&((stripos($_POST["_wp_http_referer"],'press-this')) || ( stripos($_POST["_wp_http_referer"],'index.php')) || (!isset($_POST['wordbooker_post_edited']) )) ) {
		wordbooker_debugger("Inside the press this / quick press / remote client block "," ",$post->ID) ;
		# Get the default publish setting for the post type
		if($post->post_type=='page'){
			$publish=$wordbooker_settings["wordbooker_publish_page_default"];		
		}
		else {
			$publish=$wordbooker_settings["wordbooker_publish_post_default"];
		}
		# New get the user level settings from the DB
		$wordbooker_user_settings_id="wordbookuser".$blog_id;
		$wordbookuser=get_usermeta($wb_user_id,$wordbooker_user_settings_id);
		# If we have user settings then lets go through and override the blog level defaults.
		if(is_array($wordbookuser)) {
			foreach (array_keys($wordbookuser) as $key) {
				if ((strlen($wordbookuser[$key])>0) && ($wordbookuser[$key]!="0") ) {
			#		wordbooker_debugger("replacing ".$key." - ".$wordbooker_settings[$key]." with ",$wordbookuser[$key],$post->ID) ;
					$wordbooker_settings[$key]=$wordbookuser[$key];
				} 
			}

		}
		$wordbooker_settings['wordbooker_publish_default']=$publish;
		# Then populate the post array.
		if (is_array($wordbooker_settings)) {
			foreach (array_keys($wordbooker_settings) as $key ) {
				if (substr($key,0,8)=='wordbook') {
					$_POST[$key]=str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&nbsp;&nbsp;'),array('&','"','\'','<','>',"\t"),$wordbooker_settings[$key]);
				}
			}
		}
	}

	if ( !wordbooker_get_userdata($user_ID)) {
		
		$wb_user_id=$wordbooker_settings["wordbooker_default_author"];
		# New get the user level settings from the DB
		$wordbooker_user_settings_id="wordbookuser".$blog_id;
		$wordbookuser=get_usermeta($wb_user_id,$wordbooker_user_settings_id);
		# If we have user settings then lets go through and override the blog level defaults.
		if(is_array($wordbookuser)) {
			foreach (array_keys($wordbookuser) as $key) {
				if ((strlen($wordbookuser[$key])>0) && ($wordbookuser[$key]!="0") ) {
					$wordbooker_settings[$key]=$wordbookuser[$key];
				} 
			}

		}
		# Then populate the post array.
			if(is_array($wordbooker_settings)) {
			foreach (array_keys($wordbooker_settings) as $key ) {
				if (substr($key,0,8)=='wordbook') {
					if (!isset($_POST[$key])){$_POST[$key]=str_replace( array('&amp;','&quot;','&#039;','&lt;','&gt;','&nbsp;&nbsp;'),array('&','"','\'','<','>',"\t"),$wordbooker_settings[$key]);}
				}
			}
		}
	}
	# OK now lets get the settings from the POST array
	foreach (array_keys($_POST) as $key ) {
		if (substr($key,0,8)=='wordbook') {
			$wb_params[$key]=str_replace(array('&','"','\'','<','>',"\t",), array('&amp;','&quot;','&#039;','&lt;','&gt;','&nbsp;&nbsp;'),$_POST[$key]);
		}
	}
	if ($newstatus=="future") { 
		$wb_params['wordbooker_scheduled_post']=1;
		wordbooker_debugger("This looks like a post that is scheduled for future publishing",$newstatus,$post->ID,99);
	}	
	if ($newstatus=="publish" && (!isset($oldstatus) || $oldstatus!="publish") ) { 
		wordbooker_debugger("This looks like a new post being published ",$newstatus,$post->ID,99) ;
		$wb_params['wordbooker_new_post']=1;

	}
	
	update_post_meta($post->ID, '_wordbooker_options', $wb_params); 

	if ($newstatus=="publish") {
		wordbooker_debugger("Calling Wordbooker publishing function",' ',$post->ID,99) ;
		wordbooker_publish($post->ID);
	}
} 

function wordbooker_publish($post_id) {
	global $user_ID, $user_identity, $user_login, $wpdb, $blog_id,$wordbooker_settings;
	$post = get_post($post_id);
	# If its less than 10 seconds since we saw this post last we give up
	#$ts=wordbooker_postlogged($post_id,1);
	#var_dump($ts);
	#if (isset($ts) && $ts<=60 && $ts>1) {wordbooker_debugger("Publish hook re-fire, ignoring ",$ts,$post_id,99) ; return;}
	# Clear down the error / diagnostic logs for this post.
	#wordbooker_deletefrom_errorlogs($post_id);
	if ((isset($user_ID) && $user_ID>0) &&  (!current_user_can(WORDBOOKER_MINIMUM_ADMIN_LEVEL))) { wordbooker_debugger("This user doesn't have enough rights"," ",$post_id,99) ; return; }
	
	wordbooker_debugger("Commence Publish "," ",$post_id,99) ; 
	$wb_params = get_post_meta($post_id, '_wordbooker_options', true); 
	$wordbooker_settings = wordbooker_options();
	# If there is no user row for this user then set the user id to the default author. If the default author is set to 0 (i.e current logged in user) then only blog level settings apply.
	if (! wordbooker_get_userdata($post->post_author)) { $wb_user_id=$wordbooker_settings["wordbooker_default_author"];}
	if  ($wordbooker_settings["wordbooker_default_author"] == 0 ) {$wb_user_id=$post->post_author;} else {$wb_user_id=$wordbooker_settings["wordbooker_default_author"];}
	# If we've no FB user associated with this ID and the blog owner hasn't overridden then we give up.

	if ((! wordbooker_get_userdata($post->post_author))  && ( !isset($wordbooker_settings['wordbooker_publish_no_user'])))  { wordbooker_debugger("Not a WB user (".$post->post_author.") and no overide - give up "," ",$post_id,99) ; return;}
	if ((! wordbooker_get_userdata($wb_user_id))  && ( !isset($wordbooker_settings['wordbooker_publish_no_user'])))  {wordbooker_debugger("Author (".$post->post_author.") not a WB user and no overide- give up "," ",$post_id,99) ;  return;}
		#}

	if ($_POST["wordbooker_default_author"]== 0 ) { wordbooker_debugger("Author of this post is the Post Author"," ",$post->ID,99);  $_POST["wordbooker_default_author"]=$post->post_author; }
	
	// If soupy isn't set then its either a future post or a post inherting another users options so we need to get the meta data rather than rely on post data

	wordbooker_debugger("Options Set - call transition  "," ",$post_id) ;
	$retcode=wordbooker_publish_action($post_id);
	return $retcode;
}


function wordbooker_publish_remote($post_id) {
	global $blog_id;
	$post = get_post($post_id);
	wordbooker_debugger("Commence Remote publish "," ",$post->ID,99) ; 
	$wordbooker_settings = wordbooker_options();

} 


function wordbooker_post_comment($commentid) {
	$wordbooker_settings = wordbooker_options(); 
	if ( !isset($wordbooker_settings['wordbooker_comment_push'])) {	
		return;
	}
	
	global  $wpdb, $user_id,$table_prefix;	
	$comment= get_comment($commentid); 
	$cpid = $comment->comment_post_ID;
	$cstatus=$comment->comment_approved;
	$ctext=$comment->comment_content;
	$caemail=$comment->comment_author_email;
	$cauth=$comment->comment_author;
	$cuid=$comment->user_id;
	$real_comment=true;

	wordbooker_debugger("Start Comment Push "," ",$cpid) ;
	#if (($cuid==0) && ($caemail==$wordbooker_settings['wordbooker_comment_email'])) {$real_comment=false;}
	if ($cuid==0) {$real_comment=false;}
	#if ($ctype=='Facebook Comment') {$real_comment=false;}	
	if ($real_comment) {	
		if ($cstatus==1) {
			$post = get_post($cpid);
$ctextblock = <<<CODEBLOX

Name : $cauth
Comment: [from blog ] : $ctext

CODEBLOX;

			if (($wbuser = wordbooker_get_userdata($post->post_author)) && $wbuser->access_token) {
				#$fbclient = wordbooker_fbclient($wbuser);
				# WE NEED TO CHECK THAT THE FB POST ACTUALLY EXISTS BEFORE WE POST OR it blows up.
				$sql='Select fb_post_id from ' . WORDBOOKER_POSTCOMMENTS . ' where wp_post_id ='.$cpid;
				$rows = $wpdb->get_results($sql);

				wordbooker_debugger("Comment count: ",count($rows),$cpid,0) ;
				if (count($rows)>0) {
					foreach ($rows as $comdata_row) {
						$fb_post_id=$comdata_row->fb_post_id;
						   # @param string $xid   external id associated with the comments
						    #@param string $text  text of the comment
						   # @param int    $uid   user adding the comment (def: session user)
						   # @param string $title optional title for the stream story
						   # @param string $url   optional url for the stream story
						   # @param bool   $publish_to_stream publish a feed story about this comment?
						   #                      a link will be generated to title/url in the story
						#$result2=$fbclient->comments_add('100000384338372_105295439493267', $ctextblock.' ');
						# This returns the comment ID so we should store this as a "made" comment for the post in question so we can exclude it when pulling comments down from facebook.
						try {
						$result2=$fbclient->stream_addComment($fb_post_id , $ctextblock.' ');
						wordbooker_debugger("Comment Posted : ",$result2,$cpid,0) ;
						}
						catch (Exception $e) {
							$error_code = $e->getCode();
							$error_msg = $e->getMessage();
							wordbooker_debugger("Comment Push Error : ",$error_msg,$cpid,99) ;
						}
					} 
				}
			}
		}
	}		
}


function wordbooker_debugger($method,$error_msg,$post_id,$level=9) {

		global $user_ID,$post_ID,$wpdb,$blog_id,$post,$wbooker_user_id;
		if (isset($post_id)){
		$p=get_post($post_id);
		#we dont want to record anything if its an draft of any kind
		if (stristr($p->post_status,'draft')) {return;}
}
		$usid=1;
		$row_id=1;
		if (!isset($post_id)) {$post_id=$post_ID;}
		if (!isset($post_id)) {$post_id=1;}
		if (isset($user_ID)) {$usid=$user_ID;}
		if ($usid==0) {$usid=$wbooker_user_id;}
		if (!isset($usid)) {$usid=wordbooker_get_option('wordbooker_default_author');}
		if (!isset($usid)) {$usid=1;}
		$sql=	"INSERT INTO " . WORDBOOKER_ERRORLOGS . " (
					user_id
					, method
					, error_code
					, error_msg
					, post_id
					, blog_id
					, diag_level
				) VALUES (  
					" . $usid . "
					, '" . mysql_real_escape_string($method) . "'
					, $row_id
					, '" . mysql_real_escape_string($error_msg) . "'
					, " . $post_id . "
					, " . $blog_id ."
					, " . $level ."
				)";
		$result = $wpdb->query($sql);
}

/******************************************************************************
 * Register hooks with WordPress.
 */

/* Plugin maintenance. */
register_activation_hook(__FILE__, 'wordbooker_activate');
# When a user is deleted from the blog we should clear down everything they've done in Wordbooker.
add_action('delete_user', 'wordbooker_remove_user');

add_action ('init', 'wordbooker_init');
 
function wordbooker_init () {
	#load_plugin_textdomain( 'my-plugin', false, dirname( plugin_basename( __FILE__ ) ) )
	#$plugin_dir = basename(dirname(__FILE__));
	load_plugin_textdomain ('wordbooker',false,basename(dirname(__FILE__)).'/languages');
}

function wordbooker_schema($attr) {
        $attr .= " xmlns:fb=\"http://www.facebook.com/2008/fbml\" xmlns:og=\"http://opengraphprotocol.org/schema/\" ";
        return $attr;
}

function wordbooker_get_avatar($avatar, $id_or_email, $size, $default, $alt){
    //$avatar format includes the tag <img>
    $imgpath = "http://website.com/image/myownimage.jpg";
    $my_avatar = "<img src='".$path."' alt='".$alt."' height='".$size."' width='".$size."' />";
    return $my_avatar;
}

function wordbooker_custom_cron_schedules($schedules){
	$schedules['10mins'] = array(
	'interval'   => 600,
	'display'   => __('Every 10 Minutes', 'wordbooker'),
	);

	$schedules['15mins'] = array(
	'interval'   => 900,
	'display'   => __('Every 15 Minutes', 'wordbooker'),
	);

	$schedules['20mins'] = array(
	'interval'   => 1200,
	'display'   => __('Every 20 Minutes', 'wordbooker'),
	);

	$schedules['30mins'] = array(
	'interval'   => 1800,
	'display'   => __('Every 30 Minutes', 'wordbooker'),
	);

	$schedules['45mins'] = array(
	'interval'   => 2700,
	'display'   => __('Every 45 Minutes', 'wordbooker'),
	);

	$schedules['2hours'] = array(
	'interval'   => 7200,
	'display'   => __('Every 2 Hours', 'wordbooker'),
	);

	return array_merge($schedules);
}
	
/* Post/page maintenance and publishing hooks. */
$wordbooker_disabled=wordbooker_get_option('wordbooker_disabled');
# If they've disabled Wordbooker then we don't need any of these
if (!isset($wordbooker_disabled)){
	#add_action('xmlrpc_publish_post', 'wordbooker_publish_remote',20);
	add_action('transition_post_status', 'wordbooker_process_post_data',10,3);
	add_action('delete_post', 'wordbooker_delete_post');
	add_action('wb_cron_job', 'wordbooker_poll_facebook');
	add_action('delete_post', 'wordbooker_delete_post');
	#add_action('comment_post', 'wordbooker_post_comment');
	add_action('wp_head', 'wordbooker_header');
	add_action('wp_footer', 'wordbooker_footer');
	add_filter('language_attributes', 'wordbooker_schema');
	#add_filter('get_avatar','wordbooker_get_avatar');
	#add_action('comment_post', 'wordbooker_post_comment', 20);
	#add_action('wp_set_comment_status', 'wordbooker_set_comment_status', 20, 2);
	add_filter('the_content', 'wordbooker_append_post');
	add_filter('the_excerpt','wordbooker_append_post');
	add_filter('cron_schedules','wordbooker_custom_cron_schedules');
	add_shortcode('wb_fb_like', 'wordbooker_fb_like_inline');
	add_shortcode('wb_fb_send', 'wordbooker_fb_send_inline');
	add_shortcode('wb_fb_share', 'wordbooker_fb_share_inline');
	add_shortcode('wb_fb_comment', 'wordbooker_fb_comment_inline');
	add_shortcode('wb_fb_read','wordbooker_fb_read_inline');

}
#load_plugin_textdomain( 'wordbooker', false,  dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
# Includes - trying to keep my code base tidy.
include("includes/wordbooker_options.php");
# If they've disabled Wordbooker then we don't need to load any of these.
if (!isset($wordbooker_disabled)){
	include("includes/wordbooker_wb_widget.php");
	include("includes/wordbooker_fb_widget.php");
	include("includes/wordbooker_cron.php");
	include("includes/wordbooker_posting.php");
	#include("includes/wordbooker_get_friend.php");
	#include("includes/custom_quick_edit.php");
}
# This is for support for alternative posting processes. Only Curl is supported right now
#if (wordbooker_get_option('wordbooker_fopen_curl')=='fopen'){
	#	include("includes/wordbooker_facebook_fopen.php");
	#}	
#	else {
	include("includes/wordbooker_facebook_curl.php");
#	}

?>
Back to Top