/
fotobook.php
1680 lines (1450 loc) · 54.5 KB
/
fotobook.php
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
<?php
/*
Plugin Name: Fotobook with Pages and Groups
Plugin URI: http://www.aaronharp.com/dev/wp-fotobook/,
Description: Fotobook allows you to import Facebook photo galleries directly into WordPress. <strong>Requires PHP 5.</strong>
Author: Aaron Harp
Author URI: http://www.aaronharp.com/
Version: 3.2.2_PandG-ASK
*/
/*
Copyright 2010 Aaron Harp
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 3 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, see <http://www.gnu.org/licenses/>.
*/
global $table_prefix, $wp_version;
// plugin configuration variables
define('FB_ALBUM_TABLE', $table_prefix.'fb_albums');
define('FB_PHOTO_TABLE', $table_prefix.'fb_photos');
define('FB_POSTS_TABLE', $table_prefix.'posts');
define('FB_PLUGIN_PATH', WP_PLUGIN_DIR.'/fotobook/');
define('FB_PLUGIN_URL', plugins_url().'/fotobook/');
define('FB_STYLE_URL', FB_PLUGIN_URL.'styles/'.get_option('fb_style').'/');
define('FB_STYLE_PATH', FB_PLUGIN_PATH.'styles/'.get_option('fb_style').'/');
define('FB_MANAGE_URL', (get_bloginfo('version') >= 2.7 ? 'media-new.php' : 'edit.php') .'?page=fotobook/manage-fotobook.php');
define('FB_OPTIONS_URL', 'options-general.php?page=fotobook/options-fotobook.php');
define('FB_WEBSITE', 'http://www.aaronharp.com/dev/wp-fotobook/');
define('FB_VERSION', 3.22);
define('FB_DONATE', 'https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=aaron%40freshwebs%2enet&item_name=Fotobook%20Donation&no_shipping=0&no_note=1&tax=0¤cy_code=USD&lc=US&bn=PP%2dDonationsBF&charset=UTF%2d8');
// facebook configuration variables
define('FB_API_SERVER', 'http://api.facebook.com');
define('FB_LOGIN_SERVER', 'http://www.facebook.com');
define('FB_REST_SERVER', FB_API_SERVER.'/restserver.php');
define('FB_API_KEY', '759543efe161e1085f7f6c97791e1eab');
define('FB_API_SECRET', '639a774490d803ce22cf8b7277403914');
// upgrade if needed
if(fb_needs_upgrade()) {
fb_initialize();
}
$fb_message = null;
function fb_admin_scripts() {
wp_enqueue_style('fotobook-css', FB_PLUGIN_URL.'styles/admin-styles.css');
wp_enqueue_script('fotobook-js', FB_PLUGIN_URL.'js/admin.js', array('jquery', 'jquery-ui-sortable'), FB_VERSION);
wp_enqueue_script('colorbox', FB_PLUGIN_URL.'styles/colorbox/js/colorbox.js');
wp_enqueue_script('colorbox', FB_PLUGIN_URL.'styles/colorbox/js/colorbox.js');
wp_enqueue_style('colorbox', FB_PLUGIN_URL.'styles/colorbox/colorbox.css');
}
add_action('load-fotobook/manage-fotobook.php', 'fb_admin_scripts');
add_action('load-fotobook/options-fotobook.php', 'fb_admin_scripts');
//--------------------//
//---FACEBOOK-CLASS---//
//--------------------//
class FacebookAPI {
var $facebook = null;
var $sessions = array();
var $token = null;
var $error = false;
var $msg = null;
var $secret = null;
var $progress = 0;
var $increment = null;
function FacebookAPI() {
if(!class_exists('FB_Facebook'))
include_once('facebook-platform/facebook.php');
$facebook = new FB_Facebook(FB_API_KEY, FB_API_SECRET, null, true);
$this->facebook = $facebook->api_client;
global $fb_message;
$this->msg = &$fb_message;
// check if the facebook session is the structure from older
// versions of Fotobook, if so remove it to start over
$sessions = get_option('fb_facebook_session');
if(isset($sessions['session_key'])) {
update_option('fb_facebook_session', '');
}
// set sessions to the object
$this->set_sessions();
// get token every time for additional users
$this->token = $this->get_auth_token();
// determine how much to increment the progress bar after each request
$this->progress = get_option('fb_update_progress');
$this->increment = count($this->sessions) > 0 ? 100 / (count($this->sessions) * 3) : 0;
}
/**
* Activates the provided UID to perform actions on that account.
* @param int $uid
* @return bool Whether or not the UID was found
*/
function select_session($uid) {
foreach ($this->sessions as $session) {
if ($session['uid'] == $uid) {
$this->facebook->set_user($uid);
$this->facebook->use_session_secret($session['secret']);
$this->facebook->session_key = $session['session_key'];
return true;
}
}
return false;
}
function link_active() {
return count($this->sessions) > 0;
}
function get_auth_token() {
$this->facebook->session_key = '';
$this->facebook->secret = FB_API_SECRET;
$this->token = $this->facebook->auth_createToken();
if(!$this->token) {
$this->error = true;
$this->msg = 'Fotobook is unable to connect to Facebook. Either there are problems communicating with their servers or your server does not allow requests to external servers. For a host that does allow this, sign up for a <a href="http://www.dreamhost.com/r.cgi?275020/signup|fotobook">Dreamhost account</a> using the promo code "Fotobook" and you will receive a discount.';
}
return $this->token;
}
function set_sessions() {
$sessions = get_option('fb_facebook_session');
if(!$sessions)
return false;
// make sure all accounts are still active
foreach($sessions as $key => $session) {
$this->select_session($session['uid']);
$user = $this->facebook->users_getInfo($session['uid'], array('name'));
if($this->facebook->error_code == 102) {
// if it can't get the user than remove it from the Facebook session array because
// the link isn't active anymore
$this->msg = 'The link to '.$sessions[$key]['name'].'\'s account was lost. Please authorize the account again.';
unset($sessions[$key]);
update_option('fb_facebook_session', $sessions);
}
}
$this->sessions = $sessions;
return count($sessions) > 0;
}
function get_auth_session($token) {
$sessions = $this->sessions;
try {
$new_session = $this->facebook->auth_getSession($token);
}
catch( Exception $e ) {
$this->error = true;
$this->msg = 'Unable to activate account: ' . $e->getMessage();
return false;
}
// check to see if this account is already linked
$active = array();
if(is_array($sessions)) {
foreach($sessions as $value) { $active[] = $value['uid']; }
}
if(in_array($new_session['uid'], $active)) {
$this->msg = 'That user is already linked to Fotobook.';
return false;
}
// get user's name
$this->select_session($new_session['uid']);
$user = $this->facebook->users_getInfo($new_session['uid'], array('name'));
$new_session['name'] = $user[0]['name'];
//if(!$new_session['name'])
//return false;
if(!is_array($sessions)) $sessions = array();
$sessions[] = $new_session;
update_option('fb_facebook_session', $sessions);
$this->msg = 'Fotobook is now linked to '.$new_session['name'].'\'s Facebook account. Now you need to <a href="'.FB_MANAGE_URL.'">import</a> your albums.';
$this->set_sessions();
return count($sessions) > 0;
}
function remove_user($key) {
// remove all of this user's albums and photos
global $wpdb;
$albums = fb_get_album(0, $this->sessions[$key]['uid']);
if(is_array($albums)) {
foreach($albums as $album) {
fb_delete_page($album['page_id']);
}
}
$wpdb->query('DELETE FROM `'.FB_ALBUM_TABLE."` WHERE `owner` = '".$this->sessions[$key]['uid'] . "'");
$wpdb->query('DELETE FROM `'.FB_PHOTO_TABLE."` WHERE `owner` = '".$this->sessions[$key]['uid'] . "'");
$this->msg = 'The link to '.$this->sessions[$key]['name'].'\'s Facebook account has been removed.';
unset($this->sessions[$key]);
update_option('fb_facebook_session', $this->sessions);
}
function update_progress($reset = false) {
if($reset == true) {
$this->progress = 0;
}
else {
$this->progress = $this->progress + $this->increment;
}
if($this->progress > 100) {
$this->progress = 100;
}
update_option('fb_update_progress', $this->progress);
return $this->progress;
}
function increase_time_limit() {
// allow the script plenty of time to make requests
if(!ini_get('safe_mode') && !strstr(ini_get('disabled_functions'), 'set_time_limit'))
set_time_limit(500);
}
function update_albums() {
global $wpdb;
$this->increase_time_limit();
// reset album import progress
$this->update_progress(true);
// if this is the first import then reset the order at the end to make the newest on top
$reset_order = count(fb_get_album()) > 0 ? false : true;
// get albums for each user from Facebook
$fb_albums = array(); $fb_photos = array();
foreach($this->sessions as $key=>$session) {
// setup general info
$uid = $session['uid'];
$this->select_session($uid);
try{
//START CHANGES HERE
if(is_numeric($session['gid'])){
//groups don't have albums, just photos. Here we get all the photos and fake an album
$gid=$session['gid'];
$group_photos=$this->facebook->fql_query("SELECT pid, aid, owner, src, src_big, src_small, link, caption, created FROM photo WHERE pid IN (SELECT pid FROM photo_tag WHERE subject=$gid)");
//$this->facebook->call_method('Photos.get', array('subj_id' => $gid)); -this is supposed to get all a groups photos but doesnt
if($group_photos) {
foreach($group_photos as $key=>$value){
$value['aid'] = $gid; //this may cause some problems
$value['owner'] = $gid; //this is fine, I think
array_push($fb_photos,$value);
}
//get group info
$group_info=$this->facebook->fql_query("SELECT gid,name FROM group WHERE gid=$gid");
//fake an album
$fb_albums[] = array(
'aid'=>$gid, //this may cause some problems
'cover_pid'=>$group_photos[0]['pid'],
'owner'=>$gid, //this is fine, I think
'name'=>$group_info[0]['name'].' Group Photos',
'created'=>time(),
'modified'=>time(),
'description'=>'',
'location'=>'',
'link'=>"http://www.facebook.com/group.php?v=photos&ref=ts&gid=".$gid,
'size'=>count($group_photos)
);
}
}
//END CHANGES HERE (the code in the else below is original)
else{
// get all albums
$result = $this->facebook->photos_getAlbums($uid, null);
if(!is_array($result)) // the current user has no photos so move on
continue;
$fb_albums = array_merge($fb_albums, $result);
$this->update_progress();
}
// get all photos - queries are limited to 5,000 items per query so we need to split them up
// technically this could still error out if the user 100+ photos per album, in that case
// the following number would need to change to 25 or lower
$albums_per_query = 50; $i = 0; $album_offset = 0;
while ($album_offset < count($result)) {
$photos = $this->facebook->fql_query("SELECT pid, aid, owner, src, src_big, src_small, link, caption, created FROM photo WHERE aid IN (SELECT aid FROM album WHERE owner = '$uid' LIMIT $albums_per_query OFFSET $album_offset)");
$fb_photos = array_merge($fb_photos, (array) $photos);
$album_offset = ($albums_per_query * ++$i);
}
$this->update_progress();
// get photos of user
$fb_user_photos = $this->facebook->photos_get($uid, null, null);
if($fb_user_photos) {
foreach($fb_user_photos as $k=>$v) $fb_user_photos[$k]['aid'] = $uid;
$fb_photos = array_merge($fb_photos, (array)$fb_user_photos);
$fb_albums[] = array(
'aid'=>$uid,
'cover_pid'=>$fb_user_photos[0]['pid'],
'owner'=>$uid,
'name'=>'Photos of '.(count($this->sessions) > 1 ? $session['name'] : 'Me'),
'created'=>time(),
'modified'=>time(),
'description'=>'',
'location'=>'',
'link'=>"http://www.facebook.com/photo_search.php?id=$uid",
'size'=>count($fb_user_photos)
);
}
}
catch (Exception $e) {
if ($e->getCode() == 102) {
unset($this->sessions[$key]);
update_option('fb_facebook_session', $this->sessions);
$this->msg = "The account for {$session['name']} is no longer active. Please add the account again from the settings panel.";
}
else {
$this->msg = "There was an error while retrieving your photos: {$e->getMessage()} [Error #{$e->getCode()}]";
}
return false;
}
}
// put all the albums in an array with the aid as the key
$albums = fb_get_album();
if($albums) {
foreach($albums as $album) {
$wp_albums[$album['aid']] = $album;
}
}
// go through all the facebook albums see which ones need to be added
foreach($fb_albums as $fb_album) {
$wp_album = isset($wp_albums[$fb_album['aid']]) ? $wp_albums[$fb_album['aid']] : false;
$album_data = array(
'cover_pid' => $fb_album['cover_pid'],
'owner' => $fb_album['owner'],
'name' => $fb_album['name'],
'created' => !empty($fb_album['created']) ? date('Y-m-d H:i:s', $fb_album['created']) : '',
'modified' => !empty($fb_album['modified']) ? date('Y-m-d H:i:s', $fb_album['modified']) : '',
'description' => $fb_album['description'],
'location' => $fb_album['location'],
'link' => $fb_album['link'],
'size' => $fb_album['size']
);
// if it already exists, just update it with any updated info
if ($wp_album) {
// check to make sure the page exists and update the name of the page if needed
if(fb_page_exists($wp_album['page_id'])) {
$album_data['page_id'] = $wp_album['page_id'];
if($fb_album['name'] != $wp_album['name']) {
fb_update_page($wp_album['page_id'], $fb_album['name']);
}
}
else {
$album_data['page_id'] = fb_add_page($fb_album['name']);
}
$wpdb->update(FB_ALBUM_TABLE, $album_data, array('aid' => $fb_album['aid']));
}
// it doesn't exist so create it
else {
$album_data['aid'] = $fb_album['aid'];
$album_data['page_id'] = fb_add_page($fb_album['name']);
$album_data['hidden'] = 0;
$album_data['ordinal'] = fb_get_next_ordinal();
$wpdb->insert(FB_ALBUM_TABLE, $album_data);
}
}
// update the photos
$wpdb->query('DELETE FROM '.FB_PHOTO_TABLE);
$ordinal = 1;
foreach($fb_photos as $photo) {
if($last_aid !== $photo['aid']) { // reset ordinal if we're on a new album now
$ordinal = 1;
}
$album_data = array(
'pid' => $photo['pid'],
'aid' => $photo['aid'],
'owner' => $photo['owner'],
'src' => $photo['src'],
'src_big' => $photo['src_big'],
'src_small' => $photo['src_small'],
'link' => $photo['link'],
'caption' => $photo['caption'],
'created' => date('Y-m-d H:i:s', $photo['created']),
'ordinal' => $ordinal
);
$wpdb->insert(FB_PHOTO_TABLE, $album_data);
// handle ordinal
$last_aid = $photo['aid'];
$ordinal++;
}
// put IDs of all albums in an array
foreach($fb_albums as $fb_album) {
$album_ids[] = $fb_album['aid'];
}
$wp_albums = fb_get_album();
if(count($wp_albums) > 0) {
// delete albums that have been removed off of Facebook
foreach($wp_albums as $fb_album) {
if(!@in_array($fb_album['aid'], $album_ids)) {
fb_delete_page($fb_album['page_id']);
$wpdb->query('DELETE FROM `'.FB_ALBUM_TABLE."` WHERE `aid` = '".$fb_album['aid']."'");
}
}
// delete superfluous pages
foreach($wp_albums as $fb_album) {
$album_pages[] = $fb_album['page_id'];
}
$wp_pages = $wpdb->get_results('SELECT `ID` FROM `'.FB_POSTS_TABLE."` WHERE `post_parent` = '".get_option('fb_albums_page')."'", ARRAY_A);
foreach($wp_pages as $page) {
if(!in_array($page['ID'], $album_pages)) {
fb_delete_page($page['ID']);
}
}
}
// now reset the order if needed
if($reset_order) {
fb_reset_album_order();
}
if(!$this->msg) {
$this->msg = 'Albums imported successfully.';
}
$this->update_progress(true);
}
}
//---------------------//
//---SETUP-FUNCTIONS---//
//---------------------//
function fb_initialize() {
global $wpdb;
// add default options
add_option('fb_version', FB_VERSION);
add_option('fb_albums_page', 0);
add_option('fb_number_rows', 5);
add_option('fb_number_cols', 3);
add_option('fb_album_cmts', 1);
add_option('fb_thumb_size', 130);
add_option('fb_albums_per_page', 0);
add_option('fb_style', 'colorbox');
add_option('fb_embedded_width', 0);
add_option('fb_hide_pages', 0);
$photo_table_query = "CREATE TABLE `".FB_PHOTO_TABLE."` (
`pid` varchar(40),
`aid` varchar(40),
`owner` bigint(20) unsigned,
`src` varchar(255) NOT NULL default '',
`src_big` varchar(255) NOT NULL default '',
`src_small` varchar(255) NOT NULL default '',
`link` varchar(255) NOT NULL default '',
`caption` text,
`created` datetime,
`ordinal` int(11) unsigned NOT NULL default 0,
KEY `pid` (`pid`)
) TYPE = MyISAM";
$album_table_query = "CREATE TABLE `".FB_ALBUM_TABLE."` (
`aid` varchar(40),
`page_id` bigint(20) unsigned,
`cover_pid` varchar(40),
`owner` bigint(20) unsigned,
`name` varchar(255) NOT NULL default '',
`description` text,
`location` varchar(255) NOT NULL default '',
`link` varchar(255) NOT NULL,
`size` int(11) unsigned NOT NULL default 0,
`created` datetime,
`modified` datetime,
`hidden` tinyint(1) unsigned NOT NULL default 0,
`ordinal` int(11) unsigned NOT NULL default 0,
UNIQUE KEY `aid` (`aid`)
) TYPE = MyISAM";
// this is an upgrade from v1
if(fb_table_exists(FB_ALBUM_TABLE) && $wpdb->get_results('SHOW COLUMNS FROM '.FB_ALBUM_TABLE." WHERE Field = 'timecached'")) {
$wpdb->query('DROP TABLE '.FB_ALBUM_TABLE);
$wpdb->query('DROP TABLE '.FB_PHOTO_TABLE);
}
if(!fb_table_exists(FB_PHOTO_TABLE)) {
$wpdb->query($photo_table_query);
}
if(!fb_table_exists(FB_ALBUM_TABLE)) {
$wpdb->query($album_table_query);
}
fb_upgrade_tables();
update_option('fb_version', FB_VERSION);
}
function fb_table_exists($table_name) {
global $wpdb;
foreach ($wpdb->get_col("SHOW TABLES",0) as $table ) {
if ($table == $table_name) return true;
}
return false;
}
function fb_needs_upgrade() {
$upgrade = get_option('fb_version') != FB_VERSION ? true : false;
if($upgrade)
$tables = fb_table_exists(FB_ALBUM_TABLE);
else
$tables = false;
return ($upgrade && $tables);
}
function fb_upgrade_tables() {
global $wpdb;
$version = get_option('fb_version');
// this is an upgrade to fix the duplicate key issue
if($version < 3.16 && !$wpdb->get_results('SHOW COLUMNS FROM '.FB_PHOTO_TABLE." WHERE Field = 'id'")) {
$wpdb->query('ALTER TABLE '.FB_PHOTO_TABLE.' DROP INDEX id, ADD COLUMN id BIGINT(20) AUTO_INCREMENT NOT NULL FIRST, ADD PRIMARY KEY(id)');
}
// allow captions to contain more than 255 characters
if($version < 3.17) {
$wpdb->query('ALTER TABLE '.FB_PHOTO_TABLE.' CHANGE `caption` `caption` TEXT');
}
// allow underscores in photo and album IDs
if($version < 3.18) {
$wpdb->query("ALTER TABLE ".FB_PHOTO_TABLE." CHANGE `pid` `pid` varchar(25) NOT NULL DEFAULT ''");
$wpdb->query("ALTER TABLE ".FB_PHOTO_TABLE." CHANGE `aid` `aid` varchar(25) NOT NULL DEFAULT ''");
$wpdb->query("ALTER TABLE ".FB_ALBUM_TABLE." CHANGE `aid` `aid` varchar(25) NOT NULL DEFAULT ''");
$wpdb->query("ALTER TABLE ".FB_ALBUM_TABLE." CHANGE `cover_pid` `cover_pid` varchar(25) NOT NULL DEFAULT ''");
}
// tweak the database to better accomodate the data coming in from Facebook and to
// protect against future errors
if ($version < 3.2) {
$wpdb->query("ALTER TABLE ".FB_PHOTO_TABLE." DROP `id`");
$wpdb->query("ALTER TABLE ".FB_PHOTO_TABLE." CHANGE `pid` `pid` varchar(40)");
$wpdb->query("ALTER TABLE ".FB_PHOTO_TABLE." ADD INDEX `pid` (`pid`)");
$wpdb->query("ALTER TABLE ".FB_PHOTO_TABLE." CHANGE `aid` `aid` varchar(40)");
$wpdb->query("ALTER TABLE ".FB_PHOTO_TABLE." CHANGE `owner` `owner` bigint(20) unsigned");
$wpdb->query("ALTER TABLE ".FB_PHOTO_TABLE." CHANGE `created` `created` datetime");
$wpdb->query("ALTER TABLE ".FB_PHOTO_TABLE." CHANGE `ordinal` `ordinal` int(11) unsigned NOT NULL DEFAULT 0");
$wpdb->query("ALTER TABLE ".FB_ALBUM_TABLE." CHANGE `aid` `aid` varchar(40)");
$wpdb->query("ALTER TABLE ".FB_ALBUM_TABLE." CHANGE `page_id` `page_id` bigint(20) unsigned");
$wpdb->query("ALTER TABLE ".FB_ALBUM_TABLE." CHANGE `cover_pid` `cover_pid` varchar(40)");
$wpdb->query("ALTER TABLE ".FB_ALBUM_TABLE." CHANGE `owner` `owner` bigint(20) unsigned");
$wpdb->query("ALTER TABLE ".FB_ALBUM_TABLE." CHANGE `description` `description` text");
$wpdb->query("ALTER TABLE ".FB_ALBUM_TABLE." CHANGE `size` `size` int(11) unsigned NOT NULL DEFAULT 0");
$wpdb->query("ALTER TABLE ".FB_ALBUM_TABLE." CHANGE `hidden` `hidden` tinyint(1) unsigned NOT NULL DEFAULT 0");
$wpdb->query("ALTER TABLE ".FB_ALBUM_TABLE." CHANGE `ordinal` `ordinal` int(11) unsigned NOT NULL DEFAULT 0");
$wpdb->query("ALTER TABLE ".FB_ALBUM_TABLE." CHANGE `created` `created` datetime");
$wpdb->query("ALTER TABLE ".FB_ALBUM_TABLE." CHANGE `modified` `modified` datetime");
}
}
function fb_add_pages() {
if(get_bloginfo('version') >= 2.7)
add_media_page('Media › Fotobook', 'Fotobook', 8, 'fotobook/manage-fotobook.php');
else
add_management_page('Manage › Fotobook', 'Fotobook', 8, 'fotobook/manage-fotobook.php');
add_options_page('Settings › Fotobook', 'Fotobook', 8, 'fotobook/options-fotobook.php');
}
function fb_action_link($actions) {
array_unshift($actions, '<a href="' . FB_OPTIONS_URL . '">Settings</a>');
return $actions;
}
//---------------------//
//--WP-PAGE-FUNCTIONS--//
//---------------------//
function fb_add_page($name) {
// disable conflicting Wordbook actions
remove_action('publish_page', 'wordbook_publish');
remove_action('publish_post', 'wordbook_publish');
remove_action('transition_post_status', 'wordbook_transition_post_status');
$post = array(
'post_type' => 'page',
'post_content' => '',
'post_title' => $name,
'post_status' => 'publish',
'post_parent' => get_option('fb_albums_page'),
'comment_status' => get_option('fb_album_cmts') ? 'open' : 'closed'
);
return wp_insert_post($post);
}
function fb_delete_page($id) {
if(fb_page_exists($id)) {
// disable conflicting Wordbook action
remove_action('delete_post', 'wordbook_delete_post');
wp_delete_post($id);
}
}
function fb_update_page($id, $name, $hidden = false) {
global $wpdb;
$parent = get_option('fb_albums_page');
$comment_status = get_option('fb_album_cmts') ? 'open' : 'closed';
$array = array(
'post_author' => 1,
'post_category' => 0,
'comment_status' => $comment_status,
'post_parent' => $parent,
'ID' => $id,
'post_title' => addslashes($name),
'post_name' => sanitize_title($name)
);
if(get_bloginfo('version') >= 2.1) {
$array['post_status'] = 'publish';
$array['post_type'] = 'page';
} else {
$array['post_status'] = 'static';
}
return wp_update_post($array);
}
function fb_page_exists($id) {
global $wpdb;
$page_row = $wpdb->get_row('SELECT * FROM `'.FB_POSTS_TABLE."` WHERE `ID` = '$id'");
return $page_row ? true : false;
}
//----------------------------//
//--OPTIONS/MANAGE-FUNCTIONS--//
//----------------------------//
function fb_ajax_handler() {
if(!isset($_POST['action']) || $_POST['action'] != 'fotobook')
return false;
// handle hide/unhide requests
if(isset($_POST['hide'])) {
fb_toggle_album_hiding($_POST['hide']);
echo 'success';
}
// handle order change
elseif(isset($_POST['order'])) {
fb_update_album_order($_POST['order']);
echo 'success';
}
// handle order reset
elseif(isset($_POST['reset_order'])) {
fb_reset_album_order();
echo 'The albums have been ordered by their modification date.';
}
// handle remove all
elseif(isset($_POST['remove_all'])) {
fb_remove_all();
echo 'All albums have been removed.';
}
// handle update progress request
elseif(isset($_POST['progress'])) {
echo round(get_option('fb_update_progress'));
}
// handle update albums request
elseif(isset($_POST['update'])) {
$facebook = new FacebookAPI;
if($facebook->link_active()) {
$facebook->update_albums();
echo $facebook->msg;
} else {
echo 'There are no accounts linked to Fotobook.';
}
}
// handle albums list request
elseif(isset($_POST['albums_list'])) {
fb_display_manage_list($_POST['message']);
}
exit;
}
function fb_options_update_albums_page($new_id) {
global $wpdb;
$old_id = get_option('fb_albums_page');
if($old_id == $new_id) {
return true;
}
$albums = fb_get_album();
if(sizeof($albums) > 0) {
foreach($albums as $album) {
$wpdb->update(FB_POSTS_TABLE, array('post_parent' => $new_id), array('ID' => $album['page_id']));
}
}
update_option('fb_albums_page', $new_id);
}
function fb_options_toggle_comments($status = true) {
global $wpdb;
if($status) $status = 'open';
else $status = 'closed';
$fb_albums_page = get_option('fb_albums_page');
$wpdb->update(FB_POSTS_TABLE, array('comment_status' => $status), array('post_parent' => $fb_albums_page));
}
function fb_albums_page_is_set() {
global $wpdb;
$album_page = get_option('fb_albums_page');
return $wpdb->get_var("SELECT `ID` FROM `$wpdb->posts` WHERE `ID` = '$album_page'") ? true : false;
}
function fb_get_styles() {
// get styles
$styles = array();
if ($handle = opendir(FB_PLUGIN_PATH.'styles')) {
while (false !== ($file = readdir($handle))) {
if(substr($file, 0, 1) != '.' && is_dir(FB_PLUGIN_PATH.'styles/'.$file))
$styles[] = $file;
}
closedir($handle);
}
sort($styles);
return $styles;
}
function fb_parent_dropdown( $default = 0, $parent = 0, $level = 0 ) {
global $wpdb;
$albums_page = get_option('fb_albums_page');
$items = $wpdb->get_results( "SELECT `ID`, `post_parent`, `post_title` FROM `$wpdb->posts` WHERE `post_parent` = '$parent' AND `post_type` = 'page' AND `post_parent` != '$albums_page' ORDER BY `menu_order`" );
if ( $items ) {
foreach ( $items as $item ) {
$pad = str_repeat( ' ', $level * 3 );
if ( $item->ID == $default)
$current = ' selected="selected"';
else
$current = '';
echo "\n\t<option value='$item->ID'$current>$pad " . wp_specialchars($item->post_title) . "</option>";
fb_parent_dropdown( $default, $item->ID, $level +1 );
}
} else {
return false;
}
}
function fb_days_used() {
global $wpdb;
$status = $wpdb->get_row("SHOW TABLE STATUS FROM ".DB_NAME." WHERE `Name` = '".FB_ALBUM_TABLE."'", ARRAY_A);
$created = $status['Create_time'];
$days = ceil((time() - strtotime($created)) / (60 * 60 * 24));
return $days > 2190 || $days < 0 ? 0 : $days;
}
function fb_cron_url() {
$secret = get_option('fb_secret');
if(!$secret) {
$secret = substr(md5(uniqid(rand(), true)), 0, 12);
update_option('fb_secret', $secret);
}
return FB_PLUGIN_URL.'cron.php?secret='.$secret.'&update';
}
//-------------------------//
//--ALBUM/PHOTO-FUNCTIONS--//
//-------------------------//
function fb_get_album($album_id = 0, $user_id = null, $displayed_only = false) {
global $wpdb;
$query = 'SELECT * FROM `'.FB_ALBUM_TABLE.'` ';
$where = '';
if($album_id || $user_id || $displayed_only)
$query .= "WHERE ";
if($album_id) {
$query .= "`aid` = '$album_id' ";
$array = $wpdb->get_results($query, ARRAY_A);
return $array[0];
}
if($user_id) {
if($where) $where .= "AND ";
$where .= "`owner` = '$user_id' ";
}
if($displayed_only) {
if($where) $where .= "AND ";
$where .= "`hidden` = 0 ";
}
$query .= $where."ORDER BY `ordinal` DESC";
$results = $wpdb->get_results($query, ARRAY_A);
return $results;
}
function fb_get_album_id($page_id) {
global $wpdb;
return $wpdb->get_var("SELECT `aid` FROM `".FB_ALBUM_TABLE."` WHERE `page_id` = '$page_id'");
}
function fb_update_album_order($order) {
global $wpdb;
$order = array_reverse($order);
foreach($order as $key=>$value) {
$wpdb->update(FB_ALBUM_TABLE, array('ordinal' => $key), array('aid' => $value));
}
}
function fb_reset_album_order() {
global $wpdb;
$albums = $wpdb->get_results('SELECT `aid` FROM `'.FB_ALBUM_TABLE.'` ORDER BY `modified` ASC', ARRAY_A);
if(!$albums)
return false;
foreach($albums as $key=>$album) {
$wpdb->update(FB_ALBUM_TABLE, array('ordinal' => $key), array('aid' => $album['aid']));
}
return true;
}
function fb_remove_all() {
global $wpdb;
$pages = $wpdb->get_results('SELECT `ID` FROM `'.FB_POSTS_TABLE."` WHERE `post_parent` = '".get_option('fb_albums_page')."'", ARRAY_A);
if($pages) {
foreach($pages as $page) {
// I would use the wp_delete_post function here but I'm getting a strange error
$wpdb->query('DELETE FROM `'.FB_POSTS_TABLE."` WHERE `ID` = '{$page['ID']}'");
}
}
$wpdb->query('DELETE FROM '.FB_ALBUM_TABLE);
$wpdb->query('DELETE FROM '.FB_PHOTO_TABLE);
return;
}
function fb_get_next_ordinal() {
global $wpdb;
$highest = $wpdb->get_var('SELECT `ordinal` FROM `'.FB_ALBUM_TABLE.'` ORDER BY `ordinal` DESC LIMIT 1');
return ($highest + 1);
}
function fb_toggle_album_hiding($id) {
global $wpdb;
$old = $wpdb->get_row("SELECT `hidden` FROM `".FB_ALBUM_TABLE."` WHERE `aid` = '$id'");
$new = ($old->hidden == 1) ? 0 : 1;
$wpdb->update(FB_ALBUM_TABLE, array('hidden' => $new), array('aid' => $id));
return true;
}
function fb_get_photos($album_id = 0) {
global $wpdb;
$query = 'SELECT * FROM `'.FB_PHOTO_TABLE.'` ';
if($album_id != 0) $query .= "WHERE `aid` = '$album_id' ";
$query .= "ORDER BY `ordinal` ASC";
$photos = $wpdb->get_results($query, ARRAY_A);
return $photos;
}
function fb_get_photo($id, $size = null) {
global $wpdb;
$query = 'SELECT * FROM `'.FB_PHOTO_TABLE."` WHERE `pid` = '$id'";
$photo = $wpdb->get_row($query, ARRAY_A);
switch ($size) {
case 'small':
return $photo['src_small'];
break;
case 'thumb':
return $photo['src'];
break;
case 'full':
return $photo['src_big'];
break;
default:
return $photo;
break;
}
}
function fb_get_random_photos($count) {
global $wpdb;
$query = "SELECT `".FB_PHOTO_TABLE."`.`link`, `pid`, `src`, `src_big`, `src_small`, `caption`
FROM `".FB_PHOTO_TABLE."`, `".FB_ALBUM_TABLE."`
WHERE `".FB_PHOTO_TABLE."`.`aid` = `".FB_ALBUM_TABLE."`.`aid` AND `".FB_ALBUM_TABLE."`.`hidden` = 0
ORDER BY rand() LIMIT ".$count;
$photos = $wpdb->get_results($query, ARRAY_A);
for($i = 0; $i < count($photos); $i++) {
$photos[$i]['link'] = fb_get_photo_link($photos[$i]['pid']);
}
return $photos;
}
function fb_get_recent_photos($count) {
global $wpdb;
$query = "SELECT `".FB_PHOTO_TABLE."`.`link`, `pid`, `src`, `src_big`, `src_small`, `caption`
FROM `".FB_PHOTO_TABLE."`, `".FB_ALBUM_TABLE."`
WHERE `".FB_PHOTO_TABLE."`.`aid` = `".FB_ALBUM_TABLE."`.`aid` AND `".FB_ALBUM_TABLE."`.`hidden` = 0
ORDER BY `".FB_PHOTO_TABLE."`.`created` DESC LIMIT ".$count;
$photos = $wpdb->get_results($query, ARRAY_A);
for($i = 0; $i < count($photos); $i++) {
$photos[$i]['link'] = fb_get_photo_link($photos[$i]['pid']);
}
return $photos;
}
function fb_get_photo_link($photo) { // accepts either photo id or array of photo
if(!is_array($photo)) {
$photo = fb_get_photo($photo);
}
$album = fb_get_album($photo['aid']);
$page_id = $album['page_id'];
$page_link = get_permalink($page_id);
$number_cols = get_option('fb_number_cols');
$number_rows = get_option('fb_number_rows');
if($number_rows == 0)
$number_rows = ceil($photo_count / $number_cols);
$photos_per_page = $number_cols * $number_rows;
$album_p = $photos_per_page == 0 ? 1 : ceil($photo['ordinal'] / $photos_per_page);
switch (get_option('fb_style')) {
case 'lightbox':
case 'colorbox':
$page_link .= strstr($page_link, '?') ? '&' : '?';
$page_link .= 'album_p='.$album_p;
$page_link .= '#photo'.($photo['ordinal']);
break;
case 'embedded':
$page_link .= strstr($page_link, '?') ? '&' : '?';
$page_link .= 'photo='.($photo['ordinal']);
break;
}
return htmlentities($page_link);
}
function fb_hidden_pages($array = array()) {
global $wpdb;
if(get_option('fb_hide_pages') == 1) {
$query = 'SELECT `page_id` FROM `'.FB_ALBUM_TABLE.'`';
} else {
$query = 'SELECT `page_id` FROM `'.FB_ALBUM_TABLE.'` WHERE `hidden` = 1';
}
$results = $wpdb->get_results($query, ARRAY_A);
if(!$results) return $array;
foreach($results as $result) {
$array[] = $result['page_id'];
}
return $array;
}