summaryrefslogtreecommitdiff
path: root/Pigeonholes.php
blob: aff3f03e31ab30cb7571af264d0d151060bb956a (plain)
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
<?php
/**
 * @version $Header: /cvsroot/bitweaver/_bit_pigeonholes/Pigeonholes.php,v 1.100 2007/08/24 14:35:23 squareing Exp $
 *
 * +----------------------------------------------------------------------+
 * | Copyright ( c ) 2004, bitweaver.org
 * +----------------------------------------------------------------------+
 * | All Rights Reserved. See copyright.txt for details and a complete list of authors.
 * | Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details
 * |
 * | For comments, please use phpdocu.sourceforge.net documentation standards!!!
 * | -> see http://phpdocu.sourceforge.net/
 * +----------------------------------------------------------------------+
 * | Authors: xing <xing@synapse.plus.com>
 * +----------------------------------------------------------------------+
 *
 * Pigeonholes class
 *
 * @author   xing <xing@synapse.plus.com>
 * @version  $Revision: 1.100 $
 * @package  pigeonholes
 */

/**
 * required setup
 */
require_once( LIBERTY_PKG_PATH.'LibertyAttachable.php' );
require_once( LIBERTY_PKG_PATH.'LibertyStructure.php' );

/**
 * Pigeonholes
 *
 * @package  pigeonholes
 */
class Pigeonholes extends LibertyAttachable {
	/**
	* initiate class
	* @param $pContentId content id of the pigeonhole - use either one of the ids.
	* @param $pStructureId structure id of the pigeonhole - use either one of the ids.
	* @return none
	* @access public
	**/
	function Pigeonholes( $pStructureId=NULL, $pContentId=NULL ) {
		LibertyAttachable::LibertyAttachable();
		$this->registerContentType( PIGEONHOLES_CONTENT_TYPE_GUID, array(
			'content_type_guid' => PIGEONHOLES_CONTENT_TYPE_GUID,
			'content_description' => 'Pigeonhole',
			'handler_class' => 'Pigeonholes',
			'handler_package' => 'pigeonholes',
			'handler_file' => 'Pigeonholes.php',
			'maintainer_url' => 'http://www.bitweaver.org'
		) );
		$this->mContentId = $pContentId;
		$this->mStructureId = $pStructureId;
		$this->mContentTypeGuid = PIGEONHOLES_CONTENT_TYPE_GUID;

		// Permission setup
		$this->mViewContentPerm  = 'p_pigeonholes_view';
		$this->mEditContentPerm  = 'p_pigeonholes_edit';
		$this->mAdminContentPerm = 'p_pigeonholes_edit'; // use edit until we find the need for an admin permission
	}

	/**
	* load the pigeonhole
	* @param $pExtras boolean - if set to true, pigeonhole content is added as well
	* @return bool TRUE on success, FALSE if it's not valid
	* @access public
	**/
	function load( $pExtras=FALSE, $pLoadAttachable=TRUE ) {
		if( @BitBase::verifyId( $this->mContentId ) || @BitBase::verifyId( $this->mStructureId ) ) {
			global $gBitSystem;
			$lookupColumn = ( @BitBase::verifyId( $this->mContentId ) ? 'lc.`content_id`' : 'ls.`structure_id`' );
			$lookupId = ( @BitBase::verifyId( $this->mContentId ) ? $this->mContentId : $this->mStructureId );
			$query = "SELECT pig.*, ls.`root_structure_id`, ls.`parent_id`, lc.`title`, lc.`data`,
				lc.`user_id`, lc.`content_type_guid`, lc.`format_guid`,
				uue.`login` AS modifier_user, uue.`real_name` AS modifier_real_name,
				uuc.`login` AS creator_user, uuc.`real_name` AS creator_real_name
				FROM `".BIT_DB_PREFIX."pigeonholes` pig
				INNER JOIN `".BIT_DB_PREFIX."liberty_content` lc ON ( lc.`content_id` = pig.`content_id` )
				LEFT JOIN `".BIT_DB_PREFIX."liberty_structures` ls ON ( ls.`structure_id` = pig.`structure_id` )
				LEFT JOIN `".BIT_DB_PREFIX."users_users` uue ON ( uue.`user_id` = lc.`modifier_user_id` )
				LEFT JOIN `".BIT_DB_PREFIX."users_users` uuc ON ( uuc.`user_id` = lc.`user_id` )
				WHERE $lookupColumn=?";
			$result = $this->mDb->query( $query, array( $lookupId ) );

			if( $result && $row = $result->fetchRow() ) {
				$this->mInfo = $row;
				$this->mContentId = $row['content_id'];
				$this->mStructureId = $row['structure_id'];
				$this->mInfo['user'] = $row['creator_user'];
				$this->mInfo['real_name'] = ( isset( $row['creator_real_name'] ) ? $row['creator_real_name'] : $row['creator_user'] );
				$this->mInfo['display_name'] = BitUser::getTitle( $this->mInfo );
				$this->mInfo['editor'] = ( isset( $row['modifier_real_name'] ) ? $row['modifier_real_name'] : $row['modifier_user'] );
				$this->mInfo['display_link'] = $this->getDisplayLink();
				$this->mInfo['display_url'] = $this->getDisplayUrl();
				$this->mInfo['parsed_data'] = $this->parseData( $row );
			}

			if( $pLoadAttachable ) {
				LibertyAttachable::load();
			}

			// if the content for the pigeonhole is requested, get it
			if( $pExtras ) {
				$this->mInfo['path'] = $this->getPigeonholePath();
				$this->mInfo['display_path'] = $this->getDisplayPath( $this->mInfo['path'] );
				$this->mInfo['members'] = $this->getMemberList();
				$this->mInfo['members_count'] = count( $this->mInfo['members'] );
			}
		}
		return( count( $this->mInfo ) );
	}

	/**
	* get all content inserted in a given pigeonhole. if no id is given, it gets all content for all pigeonholes
	* @param $pContentId content id of the pigeonhole
	* @return array of pigeonhole members with according title and content type guid
	* @access public
	**/
	function getMemberList( $pListHash=NULL ) {
		global $gBitUser, $gLibertySystem, $gBitSystem;
		$ret = FALSE;

		$select = $where = $join = '';
		$bindVars = array();
		if( @BitBase::verifyId( $this->mContentId ) || @BitBase::verifyId( $pListHash['content_id'] ) ) {
			$where = " WHERE pig.`content_id` = ? ";
			$bindVars[] = @BitBase::verifyId( $pListHash['content_id'] ) ? $pListHash['content_id'] : $this->mContentId;
		}

		if( !empty( $pListHash['content_type_guid'] ) ) {
			$where .= empty( $where ) ? ' WHERE ' : ' AND ';
			$where .= " lc.content_type_guid = ? ";
			$bindVars[] = $pListHash['content_type_guid'];
		}

		if( !empty( $pListHash['title'] ) && is_string( $pListHash['title'] ) ) {
			$where .= empty( $where ) ? ' WHERE ' : ' AND ';
			$where .= " pig.`content_id` = lc2.`content_id` AND UPPER( lc2.`title` ) = ?";
			$join  .= ", `".BIT_DB_PREFIX."liberty_content` lc2";
			$bindVars[] = strtoupper( $pListHash['title'] );
		}

		if( $gBitSystem->isPackageActive( 'wiki' )) {
			$select .=", wp.`description`";
			$join   .= " LEFT OUTER JOIN `".BIT_DB_PREFIX."wiki_pages` wp ON ( wp.`content_id` = lc.`content_id` ) ";
		}

		$order = "ORDER BY lc.`content_type_guid`, lc.`title` ASC";

		$ret = array();
		$query = "
			SELECT pigm.*,
			lc.`content_id`, lc.`last_modified`, lc.`user_id`, lc.`title`, lc.`content_type_guid`, lc.`created`,
			lct.`content_description`,
			uu.`login`, uu.`real_name` $select
			FROM `".BIT_DB_PREFIX."pigeonhole_members` pigm
				INNER JOIN `".BIT_DB_PREFIX."pigeonholes` pig ON ( pig.`content_id` = pigm.`parent_id` )
				INNER JOIN `".BIT_DB_PREFIX."liberty_content` lc ON ( lc.`content_id` = pigm.`content_id` )
				INNER JOIN `".BIT_DB_PREFIX."liberty_content_types` lct ON ( lc.`content_type_guid` = lct.`content_type_guid` )
				INNER JOIN `".BIT_DB_PREFIX."users_users` uu ON ( uu.`user_id` = lc.`user_id` )
			$join $where $order";
		$result = $this->mDb->query( $query, $bindVars, @BitBase::verifyId( $pListHash['max_records'] ) ? $pListHash['max_records'] : NULL );
		$contentTypes = $gLibertySystem->mContentTypes;
		while( $aux = $result->fetchRow() ) {
			if( !empty( $contentTypes[$aux['content_type_guid']] ) ) {
				$type = &$contentTypes[$aux['content_type_guid']];
				if( empty( $type['content_object'] ) ) {
					// create *one* object for each object *type* to  call virtual methods.
					include_once( $gBitSystem->mPackages[$type['handler_package']]['path'].$type['handler_file'] );
					$type['content_object'] = new $type['handler_class']();
				}
				if ($type['content_object']->isViewable($aux['content_id'])) {
					$aux['display_link'] = $type['content_object']->getDisplayLink( $aux['title'], $aux );
					$aux['title'] = $type['content_object']->getTitle( $aux );
					$ret[] = $aux;
				}
			}
		}
		return( !empty( $this->mErrors ) ? $this->mErrors : $ret );
	}

	/**
	* get all items that are not part of a pigeonhole yet
	* @return array of content not in any pigeonhole yet
	* @access public
	**/
	function getAssignableContent( &$pListHash ) {
		global $gBitUser, $gLibertySystem, $gBitSystem;

		$where = '';
		$bindVars = array();
		LibertyContent::prepGetList( $pListHash );

		if( empty( $pListHash['include_members'] ) ) {
			$where .= "WHERE pigm.`content_id` IS NULL";
		}

		if( !empty( $pListHash['find'] ) && is_string( $pListHash['find'] ) ) {
			$where .= empty( $where ) ? ' WHERE ' : ' AND ';
			$where .= " UPPER( lc.`title` ) LIKE ?";
			$bindVars[] = ( '%'.strtoupper( $pListHash['find'] ).'%');
		}

		if( !empty( $pListHash['content_type'] ) ) {
			$where .= empty( $where ) ? ' WHERE ' : ' AND ';
			$where .= " lc.`content_type_guid`=?";
			$bindVars[] = $pListHash['content_type'];
		}

		$where .= empty( $where ) ? ' WHERE ' : ' AND ';
		$where .= " lc.`content_type_guid` != ? ";
		$bindVars[] = PIGEONHOLES_CONTENT_TYPE_GUID;

		if( !empty( $pListHash['sort_mode'] ) ) {
			$order = " ORDER BY ".$this->mDb->convertSortmode( $pListHash['sort_mode'] )." ";
		} else {
			$order = " ORDER BY lc.`content_type_guid`, lc.`title` ASC";
		}

		$query = "SELECT pigm.`parent_id`, lc.`content_id`, lc.`user_id`, lc.`title`, lc.`content_type_guid`, uu.`login`, uu.`real_name`
			FROM `".BIT_DB_PREFIX."liberty_content` lc
			LEFT JOIN `".BIT_DB_PREFIX."pigeonhole_members` pigm ON ( pigm.`content_id` = lc.`content_id` )
			LEFT JOIN `".BIT_DB_PREFIX."users_users` uu ON ( uu.`user_id` = lc.`user_id` )
			$where $order";
		$result = $this->mDb->query( $query, $bindVars, @BitBase::verifyId( $pListHash['max_records'] ) ? $pListHash['max_records'] : NULL , $pListHash['offset']);

		$query = "SELECT count(lc.`content_id`)
			FROM `".BIT_DB_PREFIX."liberty_content` lc
			LEFT JOIN `".BIT_DB_PREFIX."pigeonhole_members` pigm ON ( pigm.`content_id` = lc.`content_id` )
			LEFT JOIN `".BIT_DB_PREFIX."users_users` uu ON ( uu.`user_id` = lc.`user_id` )
			$where";
		$pListHash['cant'] = $this->mDb->getOne( $query, $bindVars);

		$contentTypes = $gLibertySystem->mContentTypes;
		while( $row = $result->fetchRow() ) {
			$i = $row['content_id'];
			$ret[$i] = $row;
			if( !empty( $contentTypes[$row['content_type_guid']] ) ) {
				$type = &$contentTypes[$row['content_type_guid']];
				if( empty( $type['content_object'] ) ) {
					// create *one* object for each object *type* to  call virtual methods.
					include_once( $gBitSystem->mPackages[$type['handler_package']]['path'].$type['handler_file'] );
					$type['content_object'] = new $type['handler_class']();
				}
				$ret[$i]['display_link'] = $type['content_object']->getDisplayLink( $row['title'], $row );
				$ret[$i]['title'] = $type['content_object']->getTitle( $row );
			}

			// generate a map of what items are assigned to what pigeonholes
			if( !empty( $pListHash['include_members'] ) && @BitBase::verifyId( $row['parent_id'] ) ) {
				$map[$i][] = $row['parent_id'];
			}
		}

		// complete the output
		if( !empty( $pListHash['include_members'] ) && !empty( $ret ) ) {
			foreach( $ret as $i => $r ) {
				$ret[$i]['assigned'] = !empty( $map[$i] ) ? $map[$i] : NULL;
			}
		}

		LibertyContent::postGetList( $pListHash );
		return( !empty( $ret ) ? $ret : NULL );
	}

	/**
	 * get an array of paths for all pigeonholes. used for pages where data can be inserted into pigeonholes
	 *
	 * @param numeric $pContentId content id of pigeonhole.
	 * @param numeric $pTruncate Setting this to a number will do some smart truncations depending on how many parents there are
	 *                           setting it to 60 will allow 30 chars for all parents combined and 30 for the actual title
	 * @access public
	 * @return TRUE on success, FALSE if there is no pigeonhole
	 * @TODO We need to sort the returned values that successive pigoenholes are grouped together.
	 */
	function getPigeonholesPathList( $pContentId=NULL, $pTruncate = FALSE ) {
	  	global $gBitSystem;
	  	$where = $join = '';

		if ($gBitSystem->isFeatureActive('pigeonholes_allow_forbid_insertion')) {
		  	$where .= empty( $where ) ? ' WHERE ' : ' AND ';
			$where .= ' lcp.`pref_value` IS NULL OR lcp.`pref_value` != \'on\' ';
			$join .= ' LEFT JOIN `'.BIT_DB_PREFIX.'liberty_content_prefs` lcp ON (pig.`content_id` = lcp.`content_id` AND lcp.`pref_name` = \'no_insert\') ';
		}


		$query = "SELECT pig.`content_id`, pig.`structure_id`
			FROM `".BIT_DB_PREFIX."pigeonholes` pig
			INNER JOIN `".BIT_DB_PREFIX."liberty_structures` ls ON ( ls.`structure_id` = pig.`structure_id` )
			$join
			$where
			ORDER BY ls.`root_structure_id`, ls.`structure_id` ASC";
		$result = $this->mDb->query( $query );
		$pigeonholes = $result->getRows();
		foreach( $pigeonholes as $pigeonhole ) {
			$ret[$pigeonhole['content_id']] = $this->getPigeonholePath( $pigeonhole['structure_id'] );
		}

		if( !empty( $ret ) ) {
			if( $pTruncate ) {
				foreach( $ret as $cid => $path ) {
					// count here to minimise speed loss
					$count = count( $path );
					foreach( $path as $pos => $pig ) {
						// calculate limit at which category is truncated
						if( $count == 1 ) {
							$limit = $pTruncate;
						} elseif( $pos == $count - 1 ) {
							$limit = ceil( $pTruncate / 2 );
						} else {
							$limit = ceil( $pTruncate / 2 / $count );
						}
						$ret[$cid][$pos]['title'] = substr( $pig['title'], 0, $limit ).( ( strlen( $pig['title'] ) <= $limit ) ? '' : '...' );
					}
				}
			}

			// sort the pathlist to make the display nicer
			uasort( $ret, 'pigeonholes_pathlist_sorter' );

			if( @BitBase::verifyId( $pContentId ) && $assigned = $this->getPigeonholesFromContentId( $pContentId ) ) {
				foreach( $assigned as $a ) {
					$ret[$a['content_id']][0]['selected'] = TRUE;
				}
			}
		}

		return( !empty( $ret ) ? $ret : array() );
	}

	/**
	* get all pigeonholes where the contenent has been inserted
	* @param $pContentId content id of item in question
	* @return basic information about item requested
	* @access public
	**/
	function getPigeonholesFromContentId( $pContentId ) {
		if( @BitBase::verifyId( $pContentId ) ) {
			$query = "SELECT ls.*
				FROM `".BIT_DB_PREFIX."pigeonhole_members` pigm
				INNER JOIN `".BIT_DB_PREFIX."pigeonholes` pig ON ( pig.`content_id` = pigm.`parent_id` )
				INNER JOIN `".BIT_DB_PREFIX."liberty_structures` ls ON ( pig.`structure_id` = ls.`structure_id` )
				WHERE pigm.`content_id`=?";
			$ret = $this->mDb->getAll( $query, array( $pContentId ) );
		}
		return( !empty( $ret ) ? $ret : FALSE );
	}

	/**
	* get the path of a pigeonhole
	* @param $pStructureId structure id of pigeonhole, if no id is given, it gets the id from $this->mStructureId
	* @return path in form of an array
	* @access public
	**/
	function getPigeonholePath( $pStructureId=NULL ) {
		if( !@BitBase::verifyId( $pStructureId ) ) {
			$pStructureId = $this->mStructureId;
		}

		if( @BitBase::verifyId( $pStructureId ) ) {
			global $gStructure;
			// create new object if needed
			if( empty( $gStructure ) ) {
				$gStructure = new LibertyStructure();
			}
			// get the structure path
			$ret = $gStructure->getPath( $pStructureId );
		}
		return( !empty( $ret ) ? $ret : FALSE );
	}

	/**
	* Converts a structure path into valid html links
	* @param $pPath path given by getPigeonholePath()
	* @return the link to display the page.
	*/
	function getDisplayPath( $pPath ) {
		global $gBitSystem;
		$ret = '';
		if( !empty( $pPath ) && is_array( $pPath ) ) {
			foreach( $pPath as $node ) {
				$title = htmlspecialchars( $node['title'] );
				$ret .= ( @BitBase::verifyId( $node['parent_id'] ) ? ' &raquo; ' : '' ).'<a title="'.$title.'" href="'.$this->getDisplayUrl( $node['content_id'] ).'">'.$title.'</a>';
			}
		}
		return $ret;
	}

	/**
	* get list of all pigeonholes
	* @param $pListHash contains array of items used to limit search results
	* @param $pListHash[sort_mode] column and orientation by which search results are sorted
	* @param $pListHash[find] search for a pigeonhole title - case insensitive
	* @param $pListHash[max_records] maximum number of rows to return
	* @param $pListHash[offset] number of results data is offset by
	* @param $pListHash[title] pigeonhole name
	* @param $pListHash[parent_id] pigeonhole parent_id, optional
	* @param $pListHash[root_structure_id] only load the pigoenhole this root_structure_id is part of
	* @param $pListHash[load_only_root] only load top most items
	* @param $pListHash[parent_content_id] all the sons of the pigeonhole parent content_id , optional
	* @param $pListHash[load_also_root] if parent_content_id is set load also the father, optionnal
	* @return array of pigeonholes in 'data' and count of pigeonholes in 'cant'
	* @access public
	**/
	function getList( &$pListHash ) {
		global $gBitSystem, $gBitUser, $gBitDbType;
		LibertyContent::prepGetList( $pListHash );

		$ret = $bindVars = array();
		$where = $order = $join = $select = '';

		if( @BitBase::verifyId( $pListHash['root_structure_id'] ) ) {
			$where .= empty( $where ) ? ' WHERE ' : ' AND ';
			$where .= " ls.`root_structure_id`=? ";
			$bindVars[] = $pListHash['root_structure_id'];
		}

		if( !empty( $pListHash['load_only_root'] ) ) {
			$where .= empty( $where ) ? ' WHERE ' : ' AND ';
			$where .= " ls.`structure_id`=ls.`root_structure_id` ";
		}

		if( !empty( $pListHash['find'] ) ) {
			$where .= empty( $where ) ? ' WHERE ' : ' AND ';
			$where .= " UPPER( lc.`title` ) LIKE ? ";
			$bindVars[] = '%'.strtoupper( $pListHash['find'] ).'%';
		}

		if( !empty( $pListHash['title'] ) ) {
			$where .= empty( $where ) ? ' WHERE ' : ' AND ';
			$where .=  ' lc.`title` = ?';
			$bindVars[] = $pListHash['title'];
		}

		if( $gBitSystem->isFeatureActive( 'pigeonholes_allow_forbid_insertion' ) && !empty( $pListHash['insertable'] )) {
		  	$where .= empty( $where ) ? ' WHERE ' : ' AND ';
			$where .= ' lcp.`pref_value` IS NULL OR lcp.`pref_value` != \'on\' ';
			$join .= ' LEFT JOIN `'.BIT_DB_PREFIX.'liberty_content_prefs` lcp ON (lc.`content_id` = lcp.`content_id` AND lcp.`pref_name` = \'no_insert\') ';
			$select .= ' , lcp.`pref_value` AS no_insert ';
		}

		if( isset( $pListHash['parent_id'] ) ) {
			$where .= empty( $where ) ? ' WHERE ' : ' AND ';
			$where .= ' ls.`parent_id` = ? ';
			$bindVars[] = $pListHash['parent_id'];
		}

		if( !empty( $pListHash['parent_content_id'] ) ) {
			$join .= 'INNER JOIN `'.BIT_DB_PREFIX.'liberty_structures` lsf ON (ls.`parent_id` = lsf.`structure_id`';
			if ( !empty( $pListHash['load_also_root'] ) ) {
			 	$join .= ' OR ls.`structure_id`= lsf.`structure_id`';
			}
			$join .= ')';
			$where .= empty( $where ) ? ' WHERE ' : ' AND ';
			$where .= ' lsf.`content_id` = ? ';
			$bindVars[] = $pListHash['parent_content_id'];
		}

		if( !empty( $pListHash['sort_mode'] ) ) {
			$order .= " ORDER BY ".$this->mDb->convertSortmode( $pListHash['sort_mode'] )." ";
		} else {
			// default sort mode makes list look nice
			$order .= " ORDER BY ls.`root_structure_id`, ls.`structure_id` ASC";
		}

		$query = "SELECT pig.*, ls.`root_structure_id`, ls.`parent_id`, lc.`title`, lc.`data`, lc.`user_id`, lc.`content_type_guid`, lc.`format_guid`,
			uue.`login` AS modifier_user, uue.`real_name` AS modifier_real_name,
			uuc.`login` AS creator_user, uuc.`real_name` AS creator_real_name $select, (
				SELECT COUNT( pm.`content_id` )
				FROM `".BIT_DB_PREFIX."pigeonhole_members` pm
				WHERE pm.`parent_id`=pig.`content_id`
			) AS members_count
			FROM `".BIT_DB_PREFIX."pigeonholes` pig
				INNER JOIN `".BIT_DB_PREFIX."liberty_content` lc ON ( lc.`content_id` = pig.`content_id` )
				LEFT JOIN `".BIT_DB_PREFIX."users_users` uue ON ( uue.`user_id` = lc.`modifier_user_id` )
				LEFT JOIN `".BIT_DB_PREFIX."users_users` uuc ON ( uuc.`user_id` = lc.`user_id` )
				INNER JOIN `".BIT_DB_PREFIX."liberty_structures` ls ON ( ls.`structure_id` = pig.`structure_id` )
			$join $where $order";

		$result = $this->mDb->query( $query, $bindVars, $pListHash['max_records'], $pListHash['offset'] );

		while( $aux = $result->fetchRow() ) {
			$content_ids[] = $aux['content_id'];
			$aux['user'] = $aux['creator_user'];
			$aux['real_name'] = ( isset( $aux['creator_real_name'] ) ? $aux['creator_real_name'] : $aux['creator_user'] );
			$aux['display_name'] = BitUser::getTitle( $aux );
			$aux['editor'] = ( isset( $aux['modifier_real_name'] ) ? $aux['modifier_real_name'] : $aux['modifier_user'] );
			$aux['display_link'] = Pigeonholes::getDisplayLink( $aux['title'], $aux );
			if (!empty($pListHash['parse_data']) && !empty($aux['data'])) {
			    $aux['parsed_data'] = $this->parseData($aux['data'], $aux['format_guid']);
			}
			if( !empty( $pListHash['force_extras'] ) || ( !empty( $pListHash['load_extras'] ) && $aux['structure_id'] == @$pListHash['structure_id'] ) ) {
				$aux['path'] = $this->getPigeonholePath( $aux['structure_id'] );
				$aux['display_path'] = Pigeonholes::getDisplayPath( $aux['path'] );
				if( empty( $pListHash['content_type_guid'] )) {
				  $aux['members'] = $this->getMemberList( array( 'content_id' => $aux['content_id'] ));
				} else {
				  $aux['members'] = $this->getMemberList( array( 'content_id' => $aux['content_id'], 'content_type_guid' =>  $pListHash['content_type_guid'] ));
				}
				//$aux['members_count'] = count( $aux['members'] );
				if( $gBitSystem->getConfig( 'pigeonholes_list_style' ) == 'table' ) {
					$this->alphabetiseMembers( $aux['members'] );
				}
			}

			$ret[$aux['structure_id']] = $aux;
		}

		$query = "SELECT COUNT( lc.`title` )
			FROM `".BIT_DB_PREFIX."pigeonholes` pig
				INNER JOIN `".BIT_DB_PREFIX."liberty_content` lc ON ( lc.`content_id` = pig.`content_id` )
				LEFT JOIN `".BIT_DB_PREFIX."users_users` uue ON ( uue.`user_id` = lc.`modifier_user_id` )
				LEFT JOIN `".BIT_DB_PREFIX."users_users` uuc ON ( uuc.`user_id` = lc.`user_id` )
				INNER JOIN `".BIT_DB_PREFIX."liberty_structures` ls ON ( ls.`structure_id` = pig.`structure_id` )
			$join $where";
		$pListHash['cant'] = $this->mDb->getOne( $query, $bindVars );

		LibertyContent::postGetList( $pListHash );
		return $ret;
	}

	/**
	* Check permissions of all nodes that lead to this
	* @return a nicely grouped set of pigeonhole members in a set of columns and starting letters.
	* @access public
	**/
	function checkPathPermissions( $pPath ) {
		global $gBitUser, $gBitSystem;
		if( !empty( $pPath ) && is_array( $pPath )) {
			foreach( $pPath as $path ) {
				$contentIds[] = $path['content_id'];
			}
			if( !empty( $contentIds ) ) {
				$query = "SELECT `pref_name`, `pref_value` FROM `".BIT_DB_PREFIX."liberty_content_prefs` WHERE `content_id` IN( ".preg_replace( "/,$/", "", str_repeat( "?,", count( $contentIds ) ) )." ) ";
				$result = $this->mDb->query( $query, $contentIds );
				while( $aux = $result->fetchRow() ) {
					${$aux['pref_name']} = $aux['pref_value'];
					if( ( !empty( $group_id ) && !$gBitUser->isInGroup( $group_id ) ) || ( !empty( $permission ) && !$gBitUser->hasPermission( $permission ) ) ) {
						return FALSE;
					}
				}
			}
		}
		return TRUE;
	}

	/**
	* Alphabetise all member items
	* @return a nicely grouped set of pigeonhole members in a set of columns and starting letters.
	* @access public
	**/
	function alphabetiseMembers( &$pMememberHash ) {
		global $gBitSystem;
		if( !empty( $pMememberHash ) ) {
			usort( $pMememberHash, "pigeonholes_alphabetiser" );
			$per_column = ceil( count( $pMememberHash ) / $gBitSystem->getConfig( 'pigeonhole_display_columns', 3 ) );
			$i = 1;
			$j = 1;
			foreach( $pMememberHash as $member ) {
				$column = ( $i++ % $per_column == 0 ) ? $j++ : $j;
				$index = strtoupper( substr( $member['title'], 0, 1 ) );
				// check if the previous column was using the same letter as we want to use in the new column
				if(  !empty( $ret[$column - 1][$index] ) || !empty( $ret[$column - 1]["&hellip;".$index] ) ) {
					$index = "&hellip;".$index;
				}
				$ret[$column][$index][] = $member;
			}
			$pMememberHash = $ret;
			unset( $ret );
		}
	}

	/**
	* Store pigeonhole data
	* @param $pParamHash contains all data to store the pigeonholes
	* @param $pParamHash[title] title of the new pigeonhole
	* @param $pParamHash[edit] description of the pigeonhole
	* @param $pParamHash[members] array of content_ids that are associated with this pigeonhole
	* @param $pParamHash[root_structure_id] if this is set, it will add the pigeonhole to this structure. if it's not set, a new structure / top level pigeonhole is created
	* @param $pParamHash[parent_id] set the structure_id that will server as the parent in the structure
	* @return bool TRUE on success, FALSE if store could not occur. If FALSE, $this->mErrors will have reason why
	* @access public
	**/
	function store( &$pParamHash ) {
		if( $this->verify( $pParamHash ) && LibertyAttachable::store( $pParamHash ) ) {
			$table = BIT_DB_PREFIX."pigeonholes";
			$this->mDb->StartTrans();

			// this really confusing, strange order way of saving items is due to strange behaviour of GenID
			// probably has to do with not null default nextval('public.liberty_structures_id_seq'::text)
			if( !empty( $pParamHash['update'] ) ) {
				if( !empty( $pParamHash['pigeonhole_store'] ) ) {
					$result = $this->mDb->associateUpdate( $table, $pParamHash['pigeonhole_store'], array("content_id" => $this->mContentId ) );
				}
				$pParamHash['structure_location_id'] = $this->mStructureId;
			} else {
				// update the pigeonhole_store and structure_store content_id with the one from LibertyAttachable::store()
				$pParamHash['structure_store']['content_id'] = $pParamHash['content_id'];
				$pParamHash['pigeonhole_store']['content_id'] = $pParamHash['content_id'];

				// we need to store the new structure node now
				global $gStructure;
				// create new object if needed
				if( empty( $gStructure ) ) {
					$gStructure = new LibertyStructure();
				}
				$pParamHash['structure_location_id'] = $gStructure->storeNode( $pParamHash['structure_store'] );

				// get the corrent structure_id
				// structure_id has to be done like this since it's screwed up in the schema
				$pParamHash['pigeonhole_store']['structure_id'] =  $this->mDb->getOne( "SELECT MAX( `structure_id` ) FROM `".BIT_DB_PREFIX."liberty_structures`" );
				$result = $this->mDb->associateInsert( $table, $pParamHash['pigeonhole_store'] );
			}

			// store content items
			if( !empty( $pParamHash['pigeonhole_members_store'] ) ) {
				// remove items first
				$this->expungePigeonholeMember( array( 'parent_id' => $this->mContentId ) );
				if( !$this->insertPigeonholeMember( $pParamHash['pigeonhole_members_store'] ) ) {
					$this->mErrors['store'] = 'The content could not be inserted into the respective categories.';
				}
			}

			$this->mDb->CompleteTrans();
			$this->load();
		}
		return( count( $this->mErrors ) == 0 );
	}

	/**
	* verify, clean up and prepare data to be stored
	* @param $pParamHash all information that is being stored. will update $pParamHash by reference with fixed array of itmes
	* @return bool TRUE on success, FALSE if store could not occur. If FALSE, $this->mErrors will have reason why
	* @access private
	**/
	function verify( &$pParamHash ) {
		// make sure we're all loaded up if everything is valid
		if( $this->isValid() && empty( $this->mInfo ) ) {
			$this->load( TRUE );
		}

		// It is possible a derived class set this to something different
		if( empty( $pParamHash['content_type_guid'] ) ) {
			$pParamHash['content_type_guid'] = $this->mContentTypeGuid;
		}

		if( @BitBase::verifyId( $this->mContentId ) ) {
			$pParamHash['content_id'] = $this->mContentId;
			$pParamHash['update'] = TRUE;
		}

		// content store
		// check for name issues, first truncate length if too long
		if( !empty( $pParamHash['title'] ) )  {
			if( !@BitBase::verifyId( $this->mContentId ) ) {
				if( empty( $pParamHash['title'] ) ) {
					$this->mErrors['title'] = 'You must enter a name for this category.';
				} else {
					$pParamHash['content_store']['title'] = substr( $pParamHash['title'], 0, 160 );
				}
			} else {
				$pParamHash['content_store']['title'] = ( isset( $pParamHash['title'] ) ) ? substr( $pParamHash['title'], 0, 160 ) : $this->mInfo['title'];
			}
		} elseif( empty( $pParamHash['title'] ) ) {
			// no name specified
			$this->mErrors['title'] = 'You must enter a name for this category.';
		}

		// sort out the description
		if( $this->isValid() && !empty( $this->mInfo['data'] ) && empty( $pParamHash['edit'] ) ) {
			$pParamHash['edit'] = '';
		} elseif( empty( $pParamHash['edit'] ) ) {
			unset( $pParamHash['edit'] );
		}

		// pigeonhole member store
		// work out what to do with the content of the pigeonhole
		if( $this->isValid() && !empty( $this->mInfo['members'] ) && empty( $pParamHash['members'] ) ) {
			$pParamHash['pigeonhole_members_store']['members'] = '';
		} elseif( empty( $pParamHash['members'] ) ) {
			unset( $pParamHash['members'] );
		} else {
			$i = 1;
			foreach( $pParamHash['members'] as $c_id ) {
				$pParamHash['pigeonhole_members_store'][$i]['content_id'] = $c_id;
				$i++;
			}
		}

		// individual pigeonhole preference store
		global $gBitSystem;
		if( $gBitSystem->isFeatureActive('pigeonholes_allow_forbid_insertion') && empty( $pParamHash['prefs']['no_insert'] ) ) {
			$pParamHash['prefs']['no_insert'] = '0';
		}
		$pParamHash['preferences_store'] = !empty( $pParamHash['prefs'] ) ? $pParamHash['prefs'] : NULL;

		// structure store
		if( @BitBase::verifyId( $pParamHash['root_structure_id'] ) ) {
			$pParamHash['structure_store']['root_structure_id'] = $pParamHash['root_structure_id'];
		} else {
			$pParamHash['structure_store']['root_structure_id'] = NULL;
		}

		if( @BitBase::verifyId( $pParamHash['parent_id'] ) ) {
			$pParamHash['structure_store']['parent_id'] = $pParamHash['parent_id'];
		} else {
			$pParamHash['structure_store']['parent_id'] = NULL;
		}

		return( count( $this->mErrors ) == 0 );
	}

	/**
	* Store pigeonhole member
	* @param $pParamHash an array of content to be stored.
	* @param $pParamHash[parent_id] id of pigeonhole it belongs to, default is $this->mContentId
	* @param $pParamHash[content_id] content_id of the item to be stored
	* @return bool TRUE on success, FALSE if store could not occur. If FALSE, $this->mErrors will have reason why
	* @access public
	**/
	function insertPigeonholeMember( &$pParamHash ) {
		if( $this->verifyPigeonholeMember( $pParamHash ) ) {
			foreach( $pParamHash['member_store'] as $item ) {
				$result = $this->mDb->associateInsert( BIT_DB_PREFIX."pigeonhole_members", $item );
			}
		} else {
			vd( $this->mErrors );
		}
		return( count( $this->mErrors ) == 0 );
	}

	/**
	* verify, clean up and prepare data to be stored
	* @param $pParamHash all information that is being stored. will update $pParamHash by reference with fixed array of itmes
	* @return bool TRUE on success, FALSE if store could not occur. If FALSE, $this->mErrors will have reason why
	* @access private
	**/
	function verifyPigeonholeMember( &$pParamHash ) {
		$this->mDb->StartTrans();
		foreach( $pParamHash as $key => $item ) {
			if( isset( $item['parent_id'] ) && @BitBase::verifyId( $item['parent_id'] ) ) {
				$tmp['member_store'][$key]['parent_id'] = $item['parent_id'];
			} elseif( @BitBase::verifyId( $this->mContentId ) ) {
				$tmp['member_store'][$key]['parent_id'] = $this->mContentId;
				$pParamHash[$key]['parent_id'] = $this->mContentId;
			} else {
				$this->mErrors['store_members'] = tra( 'The content could not be inserted because the parent_id was missing.' );
			}

			if( isset( $item['content_id'] ) && @BitBase::verifyId( $item['content_id'] ) ) {
				$tmp['member_store'][$key]['content_id'] = $item['content_id'];
			} else {
				$this->mErrors['store_members'] = 'The content id is not valid.';
			}
		}

		$this->mDb->CompleteTrans();
		$pParamHash = $tmp;
		return( count( $this->mErrors ) == 0 );
	}

	/**
	* Expunge pigeonhole member
	* @param $pParamHash['parent_id'] parent_id of content to be deleted
	* @param $pParamHash['member_id'] content_id of content to be deleted
	* @param $pParamHash['deletables'] array of content_ids to check against when deleting. makes sure that only members of a given structure are removed
	*	Note if only one of the 2 ids is given, all items with that id will be removed. if both are given, only that one particular entry is removed
	* @return bool TRUE on success, FALSE if store could not occur. If FALSE, $this->mErrors will have reason why
	* @access public
	**/
	function expungePigeonholeMember( $pParamHash ) {
		if( @BitBase::verifyId( $pParamHash['parent_id'] ) || @BitBase::verifyId( $pParamHash['member_id'] ) ) {
			$where = '';
			$bindVars = array();

			if( @BitBase::verifyId( $pParamHash['parent_id'] ) ) {
				$where .= " WHERE `parent_id`=? ";
				$bindVars[] = $pParamHash['parent_id'];
			}

			if( @BitBase::verifyId( $pParamHash['member_id'] ) ) {
				$where .= ( empty( $where ) ? " WHERE " : " AND " )." `content_id`=? ";
				$bindVars[] = $pParamHash['member_id'];
			}

			if( !empty( $pParamHash['deletables'] ) && is_array( $pParamHash['deletables'] ) ) {
				// only delete member data when it's part of the deletable structure
				$where .= ( empty( $where ) ? " WHERE " : " AND " )." `parent_id` IN( ".preg_replace( "/,$/", "", str_repeat( "?,", count( $pParamHash['deletables'] ) ) )." ) ";
				$bindVars = array_merge( $bindVars, $pParamHash['deletables'] );
			}

			// now we're ready to remove the actual members
			$query = "DELETE FROM `".BIT_DB_PREFIX."pigeonhole_members` $where";
			$result = $this->mDb->query( $query, $bindVars );
		} else {
			$this->mErrors['members_store'] = 'The category member(s) could not be removed.';
		}
		return( count( $this->mErrors ) == 0 );
	}

	/**
	* Expunge currently loaded pigeonhole
	* @return bool TRUE on success, FALSE if store could not occur.
	* @access public
	**/
	function expunge( $pStructureId = NULL ) {
		$ret = FALSE;
		// if we have a custom structure id we want to remove, load it
		if( @BitBase::verifyId( $pStructureId ) ) {
			$this->mStructureId = $pStructureId;
			$this->load();
		}

		if( $this->isValid() ) {
			$this->mDb->StartTrans();
			// get all items that are part of the sub tree
			require_once( LIBERTY_PKG_PATH.'LibertyStructure.php' );
			$struct = new LibertyStructure();

			// include the current structure id as well
			$structureIds[] = $this->mStructureId;
			$tree = $struct->getSubTree( $this->mStructureId );
			foreach( $tree as $node ) {
				$structureIds[] = $node['structure_id'];
			}

			$structureIds = array_unique( $structureIds );
			$where = '';
			foreach( $structureIds as $structureId ) {
				$where .= ( empty( $where ) ? " WHERE " : " OR ")."`structure_id`=?";
			}
			$result = $this->mDb->query( "SELECT `content_id` FROM `".BIT_DB_PREFIX."liberty_structures` $where", $structureIds );
			$contentIds = $result->getRows();

			foreach( $contentIds as $id ) {
				// now we have the content ids - let the nuking begin
				$query = "DELETE FROM `".BIT_DB_PREFIX."pigeonholes` WHERE `content_id` = ?";
				$result = $this->mDb->query( $query, array( $id['content_id'] ) );
				$query = "DELETE FROM `".BIT_DB_PREFIX."pigeonhole_members` WHERE `parent_id` = ?";
				$result = $this->mDb->query( $query, array( $id['content_id'] ) );

				// remove all entries from content tables
				$this->mContentId = $id['content_id'];
				if( LibertyAttachable::expunge() ) {
					$ret = TRUE;
					$this->mDb->CompleteTrans();
				} else {
					$this->mDb->RollbackTrans();
				}
			}

			// finally nuke the structure in liberty_structures
			$struct->removeStructureNode( $this->mStructureId, FALSE );
		}
		return $ret;
	}

	/**
	* Generates the URL to this pigeonhole
	* @param $pContentId is the pigeonhole id we want to see
	* @return the link to display the page.
	*/
	function getDisplayUrl( $pContentId=NULL, $pMixed=NULL ) {
		global $gBitSystem;
		$ret = NULL;
		// try to get the correct content_id from anywhere possible
		if( !@BitBase::verifyId( $pContentId ) && !empty( $this->mContentId ) ) {
			$pContentId = $this->mContentId;
		} elseif( !@BitBase::verifyId( $pContentId ) && !empty( $pMixed ) ) {
			$pContentId = $pMixed['content_id'];
		}

		if( @BitBase::verifyId( $pContentId ) ) {
			$rewrite_tag = $gBitSystem->isFeatureActive( 'pretty_urls_extended' ) ? 'view/' : '';
			if( $gBitSystem->isFeatureActive( 'pretty_urls' ) || $gBitSystem->isFeatureActive( 'pretty_urls_extended' ) ) {
				$ret = PIGEONHOLES_PKG_URL.$rewrite_tag.$pContentId;
			} else {
				$ret = PIGEONHOLES_PKG_URL.'view.php?content_id='.$pContentId;
			}
		}
		return $ret;
	}

	/**
	* Returns HTML link to display a pigeonhole
	* @param $pTitle is the pigeonhole we want to see
	* @param $pContentId content id of the pigeonhole in question
	* @return the link to display the page.
	*/
	function getDisplayLink( $pTitle=NULL, $pMixed=NULL ) {
		global $gBitSystem;
		if( empty( $pTitle ) && !empty( $this ) ) {
			$pTitle = $this->getTitle();
		}

		if( empty( $pMixed ) && !empty( $this ) ) {
			$pMixed = $this->mInfo;
		}

		$ret = $pTitle;
		if( !empty( $pTitle ) && !empty( $pMixed ) ) {
			if( $gBitSystem->isPackageActive( 'pigeonholes' ) ) {
				$ret = '<a title="'.htmlspecialchars( $pTitle ).'" href="'.Pigeonholes::getDisplayUrl( $pMixed['content_id'] ).'">'.htmlspecialchars( $pTitle ).'</a>';
			}
		}

		return $ret;
	}
}

function pigeonholes_alphabetiser( $a, $b ) {
	return strcasecmp( $a["title"], $b["title"] );
}

function pigeonholes_pathlist_sorter( $aa, $ab ) {
	foreach( $aa as $key => $a ) {
		if( !empty( $ab[$key] ) ) {
			if( $a['structure_id'] < $ab[$key]['structure_id'] ) {
				return -1;
			} elseif( $a['structure_id'] > $ab[$key]['structure_id'] ) {
				return 1;
			}
		} else {
			return 1;
		}
	}
}


// ============= SERVICE FUNCTIONS =============

function pigeonholes_content_display( &$pObject ) {
	global $gBitSystem, $gBitSmarty, $gBitUser, $gBitThemes;
	$pigeonholes = new Pigeonholes();

	// first we need to check permissions
	if( $gBitSystem->isFeatureActive( 'pigeonhole_permissions' ) || $gBitSystem->isFeatureActive( 'pigeonholes_groups' )) {
		if( $pigeons = $pigeonholes->getPigeonholesFromContentId( $pObject->mContentId )) {
			foreach( $pigeons as $pigeon ) {
				// we will loop through here until we get one pigeonhole that allows access
				if( empty( $access_granted )) {
					if( $pigeonholes->checkPathPermissions( $pigeonholes->getPigeonholePath( $pigeon['structure_id'] ))) {
						$access_granted = TRUE;
					} else {
						$access_granted = FALSE;
					}
				}
			}
		}

		// we need to check all pigeonholes in the path, load the prefs and work out if the user is allowed to view the page
		if( isset( $access_granted ) && $access_granted === FALSE ) {
			$msg = tra( "This content is part of a category to which you have no access to. Please log in or request the appropriate permission from the site administrator." );
			$gBitSystem->fatalPermission( NULL, $msg );
		}
	}

	if( $gBitSystem->isFeatureActive( 'pigeonholes_display_members' ) || $gBitSystem->isFeatureActive( 'pigeonholes_display_path' )) {
		if( $gBitUser->hasPermission( 'p_pigeonholes_view' )) {
			if( $pigeons = $pigeonholes->getPigeonholesFromContentId( $pObject->mContentId )) {
				foreach( $pigeons as $key => $pigeon ) {
					$pigeonholes->mContentId = $pigeon['content_id'];
					$pigeonholes->load( TRUE, FALSE );
					$pigeonData[] = $pigeonholes->mInfo;

					// set the theme chosen for this page - virtually random if page is part of multiple themes
					if( $gBitSystem->isFeatureActive( 'pigeonholes_themes' )) {
						// loadPreferences is called by getPreference if needed
						$gBitThemes->setStyle( $pigeonholes->getPreference( 'style' ));
					}
				}
				$gBitSmarty->assign( 'pigeonData', !empty( $pigeonData ) ? $pigeonData : FALSE );
			}
		}
	}
}

function pigeonholes_content_edit( $pObject=NULL ) {
	global $gBitSmarty, $gBitUser, $gBitSystem;
	$pigeonPathList = array();

	if( $gBitUser->hasPermission( 'p_pigeonholes_insert_member' ) ) {
		$pigeonholes = new Pigeonholes();

		// get pigeonholes path list
		if( $pigeonPathList = $pigeonholes->getPigeonholesPathList(( !empty( $pObject->mContentId ) ? $pObject->mContentId : NULL ), ( $gBitSystem->isFeatureActive( 'pigeonholes_use_jstab' ) ? FALSE : 100 ))) {
			$gBitSmarty->assign( 'pigeonPathList', $pigeonPathList );
		}
	}
}

function pigeonholes_content_expunge( $pObject=NULL ) {
	$pigeonholes = new Pigeonholes();
	$pigeonholes->expungePigeonholeMember( array( 'member_id' => $pObject->mContentId ) );
}

function pigeonholes_content_preview() {
	global $gBitSmarty, $gBitUser;
	$pigeonPathList = array();

	if( $gBitUser->hasPermission( 'p_pigeonholes_insert_member' ) ) {
		$pigeonholes = new Pigeonholes();

		// get pigeonholes path list
		if( $pigeonPathList = $pigeonholes->getPigeonholesPathList() ) {
			foreach( $pigeonPathList as $key => $path ) {
				if( !empty( $_REQUEST['pigeonholes']['pigeonhole'] ) && in_array( $key, $_REQUEST['pigeonholes']['pigeonhole'] ) ) {
					$pigeonPathList[$key][0]['selected'] = TRUE;
				} else {
					$pigeonPathList[$key][0]['selected'] = FALSE;
				}
			}
			$gBitSmarty->assign( 'pigeonPathList', $pigeonPathList );
		}
	}
}

function pigeonholes_content_store( $pObject, $pParamHash ) {
	global $gBitSmarty, $gBitUser;
	if( $gBitUser->hasPermission( 'p_pigeonholes_insert_member' ) ) {
		if( !empty( $pParamHash['content_id'] ) ) {
			if( is_object( $pObject ) && empty( $pParamHash['content_id'] ) ) {
				$pParamHash['content_id'] = $pObject->mContentId;
			}

			$pigeonholes = new Pigeonholes();
			$pigeonPathList = $pigeonholes->getPigeonholesPathList( $pParamHash['content_id'] );

			// here we need to work out if we need to save at all
			// get all originally selected items
			$selectedItem = array();
			if( !empty( $pigeonPathList ) ) {
				foreach( $pigeonPathList as $path ) {
					if( !empty( $path[0]['selected'] ) ) {
						$pathItem = array_pop( $path );
						$selectedItem[] = $pathItem['content_id'];
					}
				}
			}

			// quick and dirty check to start off with
			if( empty( $_REQUEST['pigeonholes'] ) || count( $_REQUEST['pigeonholes']['pigeonhole'] ) != count( $selectedItem ) ) {
				$modified = TRUE;
			} else {
				// more thorough check
				foreach( $selectedItem as $item ) {
					if( !in_array( $item, $_REQUEST['pigeonholes']['pigeonhole'] ) ) {
						$modified = TRUE;
					}
				}
			}

			if( !empty( $modified ) ) {
				// first remove all entries with this content_id
				if( $pigeonholes->expungePigeonholeMember( array( 'member_id' => $pParamHash['content_id'] ) ) && !empty( $_REQUEST['pigeonholes'] ) ) {
					// insert the content into the desired pigeonholes
					foreach( $_REQUEST['pigeonholes']['pigeonhole'] as $p_id ) {
						$memberHash[] = array(
							'parent_id' => $p_id,
							'content_id' => $pParamHash['content_id']
						);
					}

					if( !$pigeonholes->insertPigeonholeMember( $memberHash ) ) {
						$gBitSmarty->assign( 'msg', tra( "There was a problem inserting the content into the pigeonholes." ) );
						$gBitSystem->display( 'error.tpl' );
						die;
					}
				}
			}
		}
	}
}

/**
 * When the list function is called and the template, a filter option will appear based on categories
 * 
 * @param array $pObject Current object
 * @param array $pParamHash Parameter hash - only works if $_REQUEST[pigeonholes][filter] is passed back to the list sql funciton
 * @access public
 * @return void
 */
function pigeonholes_content_list( &$pObject, $pParamHash = NULL ) {
	global $gBitSystem, $gBitSmarty;
	if( $gBitSystem->isFeatureActive( 'pigeonholes_list_filter' )) {
		$pigeonholes = new Pigeonholes();
		$listHash = array(
			'sort_mode' => array(
				'root_structure_id_asc', 'title_asc'
			),
			'insertable' => TRUE,
		);
		$pigeonList = $pigeonholes->getList( $listHash );
		$list = array();
		foreach( $pigeonList as $content_id => $pigeon ) {
			$list[$content_id] = $pigeon['display_link'];
		}
		$gBitSmarty->assign( 'pigeonList', $list );
	}
}

/**
 * filter the search with pigeonholes
 * @param $pParamHash['pigeonholes']['filter'] - a pigeonhole or an array of pigeonhole content_id
 **/
function pigeonholes_content_list_sql( &$pObject, $pParamHash = NULL ) {
	global $gBitSystem;
	$ret = array();

	if( !empty( $pParamHash['pigeonholes']['filter'] )) {
		$pParamHash['liberty_categories'] = $pParamHash['pigeonholes']['filter'];
	}

	if( !empty( $pParamHash['liberty_categories'] )) {
		$ret['join_sql'] = "LEFT JOIN `".BIT_DB_PREFIX."pigeonhole_members` pm ON (lc .`content_id`= pm.`content_id`)";
		if( is_array( $pParamHash['liberty_categories'] )) {
			$ret['where_sql'] = ' AND pm.`parent_id` in ('.implode( ',', array_fill( 0, count( $pParamHash['liberty_categories']  ), '?' )).')';
			$ret['bind_vars'] = $pParamHash['liberty_categories'];
		} else {
			$ret['where_sql'] = " AND pm.`parent_id`=? ";
			$ret['bind_vars'][] = $pParamHash['liberty_categories'];
		}
	}

	return $ret;
}
?>