File: WidgetLayoutManager.class.php

package info (click to toggle)
fusionforge 5.3.2%2B20141104-3
  • links: PTS, VCS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 60,472 kB
  • sloc: php: 271,846; sql: 36,817; python: 14,575; perl: 6,406; sh: 5,980; xml: 4,294; pascal: 1,411; makefile: 911; cpp: 52; awk: 27
file content (898 lines) | stat: -rw-r--r-- 31,895 bytes parent folder | download | duplicates (3)
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
<?php
/**
 * Copyright (c) Xerox Corporation, Codendi Team, 2001-2009. All rights reserved
 * Copyright (C) 2011 Alain Peyrat - Alcatel-Lucent
 * Copyright 2013, Franck Villaume - TrivialDev
 *
 * This file is a part of Fusionforge.
 *
 * Fusionforge 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.
 *
 * Fusionforge 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 Fusionforge. If not, see <http://www.gnu.org/licenses/>.
 */

require_once $gfcommon.'widget/WidgetLayout.class.php';
require_once $gfcommon.'widget/Widget.class.php';
require_once $gfcommon.'include/preplugins.php';

/**
 * WidgetLayoutManager
 *
 * Manage layouts for users, groups and homepage
 */
class WidgetLayoutManager {
	const OWNER_TYPE_USER  = 'u';
	/**
	 * Layout for project home
	 * @var string
	 */
	const OWNER_TYPE_GROUP = 'g';
	const OWNER_TYPE_HOME  = 'h';

	/**
	 * displayLayout
	 *
	 * Display the default layout for the "owner". It may be the home page, the project summary page or /my/ page.
	 *
	 * @param	int		$owner_id
	 * @param	string	$owner_type
	 */
	function displayLayout($owner_id, $owner_type) {
		$sql = "SELECT * from owner_layouts where owner_id=$1 and owner_type=$2";
		$res = db_query_params($sql, array($owner_id, $owner_type));
		if($res && db_numrows($res)<1) {
			if($owner_type == self::OWNER_TYPE_USER) {
				$this->createDefaultLayoutForUser($owner_id);
				$this->displayLayout($owner_id,$owner_type);
			} else {
				$this->createDefaultLayoutForProject($owner_id,1);
				$this->displayLayout($owner_id,$owner_type);
			}
		} else {
			$sql = "SELECT l.*
				FROM layouts AS l INNER JOIN owner_layouts AS o ON(l.id = o.layout_id)
				WHERE o.owner_type = $1
				AND o.owner_id = $2
				AND o.is_default = 1
				";
			$req = db_query_params($sql, array($owner_type ,$owner_id));
			if ($data = db_fetch_array($req)) {
				$readonly = !$this->_currentUserCanUpdateLayout($owner_id, $owner_type);
//				if (!$readonly) {
//					echo '<p class="customize"><a href="/widgets/widgets.php?owner='. $owner_type.$owner_id .'&amp;layout_id='. $data['id'] .'">'. _("Customize") .'</a></p>';
//				} elseif ($owner_type === self::OWNER_TYPE_GROUP) {
//					echo '<br />';
//				}
				$layout = new WidgetLayout($data['id'], $data['name'], $data['description'], $data['scope']);
				$sql = 'SELECT * FROM layouts_rows WHERE layout_id = $1 ORDER BY rank';
				$req_rows = db_query_params($sql,array($layout->id));
				while ($data = db_fetch_array($req_rows)) {
					$row = new WidgetLayout_Row($data['id'], $data['rank']);
					$sql = 'SELECT * FROM layouts_rows_columns WHERE layout_row_id = $1';
					$req_cols = db_query_params($sql,array($row->id));
					while ($data = db_fetch_array($req_cols)) {
						$col = new WidgetLayout_Row_Column($data['id'], $data['width']);
						$sql = "SELECT * FROM layouts_contents WHERE owner_type = $1  AND owner_id = $2 AND column_id = $3 ORDER BY rank";
						$req_content = db_query_params($sql,array($owner_type, $owner_id, $col->id));
						while ($data = db_fetch_array($req_content)) {
							$c = Widget::getInstance($data['name']);
							if ($c && $c->isAvailable()) {
								$c->loadContent($data['content_id']);
								$col->add($c, $data['is_minimized'], $data['display_preferences']);
							}
							unset($c);
						}
						$row->add($col);
						unset($col);
					}
					$layout->add($row);
					unset($row);
				}
				$layout->display($readonly, $owner_id, $owner_type);
			}
		}
	}

	/**
	 * _currentUserCanUpdateLayout
	 *
	 * @param	int		$owner_id
	 * @param	string	$owner_type
	 * @return	boolean true if the user can update the layout (add/remove widget, collapse, set preferences, ...)
	 */
	function _currentUserCanUpdateLayout($owner_id, $owner_type) {
		$readonly = true;
		$request =& HTTPRequest::instance();
		switch ($owner_type) {
			case self::OWNER_TYPE_USER:
				if (user_getid() == $owner_id) { //Current user can only update its own /my/ page
					$readonly = false;
				}
				break;
			case self::OWNER_TYPE_GROUP:
				if (forge_check_perm('project_admin', $owner_id, NULL)) { //Only project admin
					$readonly = false;
				}
				break;
			case self::OWNER_TYPE_HOME:
				//Only site admin
				break;
			default:
				break;
		}
		return !$readonly;
	}
	/**
	 * createDefaultLayoutForUser
	 *
	 * Create the first layout for the user and add some initial widgets:
	 * - MyArtifacts
	 * - MyProjects
	 * - MyBookmarks
	 * - MySurveys
	 * - MyMonitoredFP
	 * - MyMonitoredForums
	 * - and widgets of plugins if they want to listen to the event default_widgets_for_new_owner
	 *
	 * @param	int	$owner_id The id of the newly created user
	 */
	function createDefaultLayoutForUser($owner_id) {
		$owner_type = self::OWNER_TYPE_USER;
		db_begin();
		$success = true;
		$sql = "INSERT INTO owner_layouts(layout_id, is_default, owner_id, owner_type) VALUES (1, 1, $1, $2)";
		if (db_query_params($sql, array($owner_id, $owner_type))) {

			$sql = "INSERT INTO layouts_contents(owner_id, owner_type, layout_id, column_id, name, rank) VALUES ";

			$args[] = "($1, $2, 1, 1, 'myprojects', 0)";
			$args[] = "($1, $2, 1, 1, 'mybookmarks', 1)";
			$args[] = "($1, $2, 1, 1, 'mymonitoredforums', 2)";
			$args[] = "($1, $2, 1, 1, 'mysurveys', 4)";
			$args[] = "($1, $2, 1, 2, 'myartifacts', 0)";
			$args[] = "($1, $2, 1, 2, 'mymonitoredfp', 1)";

			foreach($args as $a) {
				if (!db_query_params($sql.$a,array($owner_id,$owner_type))) {
					$success = false;
					break;
				}
			}

			/*  $em =& EventManager::instance();
			    $widgets = array();
			    $em->processEvent('default_widgets_for_new_owner', array('widgets' => &$widgets, 'owner_type' => $owner_type));
			    foreach($widgets as $widget) {
			    $sql .= ",($13, $14, 1, $15, $16, $17)";
			    }*/
		} else
			$success = false;
		if (!$success) {
			$success = db_error();
			db_rollback();
			exit_error(sprintf(_('DB Error: %s'), $success), 'widgets');
		}
		db_commit();
	}

	/**
	 * createDefaultLayoutForProject
	 *
	 * Create the first layout for a new project, based on its parent template.
	 * Add some widgets based also on its parent configuration and on its service configuration.
	 *
	 * @param	int	$group_id  the id of the newly created project
	 * @param	int	$template_id  the id of the project template
	 */
	function createDefaultLayoutForProject($group_id, $template_id) {
		$pm = ProjectManager::instance();
		$project = $pm->getProject($group_id);
		$sql = "INSERT INTO owner_layouts(layout_id, is_default, owner_id, owner_type)
			SELECT layout_id, is_default, $1, owner_type
			FROM owner_layouts
			WHERE owner_type = $2
			AND owner_id = $3
			";
		if (db_query_params($sql,array($group_id, self::OWNER_TYPE_GROUP,$template_id))) {
			$sql = "SELECT layout_id, column_id, name, rank, is_minimized, is_removed, display_preferences, content_id
				FROM layouts_contents
				WHERE owner_type = $1
				AND owner_id = $2
				";
			if ($req = db_query_params($sql,array( self::OWNER_TYPE_GROUP,$template_id))) {
				while($data = db_fetch_array($req)) {
					$w = Widget::getInstance($data['name']);
					if ($w) {
						$w->setOwner($template_id, self::OWNER_TYPE_GROUP);
						if ($w->canBeUsedByProject($project)) {
							$content_id = $w->cloneContent($w->content_id, $group_id, self::OWNER_TYPE_GROUP);
							$sql = "INSERT INTO layouts_contents(owner_id, owner_type, content_id, layout_id, column_id, name, rank, is_minimized, is_removed, display_preferences)
								VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10);
							";
							db_query_params($sql, array($group_id , self::OWNER_TYPE_GROUP , $content_id ,  $data['layout_id'] ,  $data['column_id'] ,  $data['name'] ,  $data['rank'] ,  $data['is_minimized'] ,  $data['is_removed'] ,  $data['display_preferences'] ));
							echo db_error();
						}
					}
				}
			}
		}
		echo db_error();
	}

	/**
	 * displayAvailableWidgets - Display all widgets that the user can add to the layout
	 *
	 * @param	int		$owner_id
	 * @param	string	$owner_type
	 * @param	int		$layout_id
	 */
	function displayAvailableWidgets($owner_id, $owner_type, $layout_id) {
		// select already used widgets
		$used_widgets = array();
		$sql = "SELECT *
			FROM layouts_contents
			WHERE owner_type = $1
			AND owner_id = $2
			AND layout_id = $3
			AND content_id = 0 AND column_id <> 0";
		$res = db_query_params($sql,array($owner_type,$owner_id,$layout_id));
		while($data = db_fetch_array($res)) {
			$used_widgets[] = $data['name'];
		}
		// display contextual toolbar
		echo '<ul class="widget_toolbar">';
		$url = "/widgets/widgets.php?owner=".HTTPRequest::instance()->get('owner').
			"&amp;layout_id=".HTTPRequest::instance()->get('layout_id');

		$update_layout = (HTTPRequest::instance()->get('update') == 'layout');
		if ($update_layout) {
			// customized selected
			echo '<li><a href="'. $url .'">'. _("Add widgets") .'</a></li>';
			echo '<li class="current"><a href="'. $url.'&amp;update=layout' .'">'. _("Customize Layout") .'</a></li>';
			$action = 'layout';
		} else {
			// add selected, or default when first displayed
			echo '<li class="current"><a href="'. $url .'">'. _("Add widgets") .'</a></li>';
			echo '<li><a href="'. $url.'&amp;update=layout' .'">'. _("Customize Layout") .'</a></li>';
			$action = 'widget';
		}
		echo '</ul>';
		echo '<form action="/widgets/updatelayout.php?owner='. $owner_type.$owner_id .'&amp;action='. $action .'&amp;layout_id='. $layout_id .'" method="post">';
		if ($update_layout) {
			?>
			<script type='text/javascript'>//<![CDATA[
				var controllerLayoutBuilder;
				jQuery(document).ready(function() {
					controllerLayoutBuilder = new LayoutBuilderController({
						buttonAddRow:		jQuery('.layout-manager-row-add'),
						buttonAddColumn:	jQuery('.layout-manager-column-add'),
						buttonRemoveColumn:	jQuery('.layout-manager-column-remove')
					});
					jQuery('#save').click(function(){
						if (jQuery('#layout_custom').is(':checked')) {
							var form = jQuery('#layout-manager').parents('form').first();
							jQuery('#layout-manager').find('.layout-manager-row').each(function(i, e) {
								jQuery('<input>', {
									type: 'hidden',
									name: 'new_layout[]',
									value: jQuery(e).find('.layout-manager-column input[type=number]').map(function(){ return this.value;}).get().join(',')
									}).appendTo(form);
							});
						}
					});
					jQuery('.layout-manager-chooser').each(function(i, e) {
						jQuery(e).find('input[type=radio]').change(function() {
							jQuery('.layout-manager-chooser').each(function(i, e) {
								jQuery(e).removeClass('layout-manager-chooser_selected');
							});
							jQuery(e).addClass('layout-manager-chooser_selected');
						});
					});
				});
			//]]></script>
			<?php
			$sql = "SELECT * FROM layouts WHERE scope='S' ORDER BY id ";
			$req_layouts = db_query_params($sql,array());
			echo '<table>';
			$is_custom = true;
			while ($data = db_fetch_array($req_layouts)) {
				$checked = $layout_id == $data['id'] ? 'checked="checked"' : '';
				$is_custom = $is_custom && !$checked;
				echo '<tr class="layout-manager-chooser '. ($checked ? 'layout-manager-chooser_selected' : '') .'" ><td>';
				echo '<input type="radio" name="layout_id" value="'. $data['id'] .'" id="layout_'. $data['id'] .'" '. $checked .'/>';
				echo '</td><td>';
				echo '<label for="layout_'. $data['id'] .'">';
				echo html_image('layout/'. strtolower(preg_replace('/(\W+)/', '-', $data['name'])) .'.png');
				echo '</label>';
				echo '</td><td>';
				echo '<label for="layout_'. $data['id'] .'"><strong>'. $data['name'] .'</strong><br />';
				echo $data['description'];
				echo '</label>';
				echo '</td></tr>';
			}
			/* Custom layout are not available yet */
			$checked = $is_custom ? 'checked="checked"' : '';
			echo '<tr class="layout-manager-chooser '. ($checked ? 'layout-manager-chooser_selected' : '') .'"><td>';
			echo '<input type="radio" name="layout_id" value="-1" id="layout_custom" '. $checked .'/>';
			echo '</td><td>';
			echo '<label for="layout_custom">';
			echo html_image('layout/custom.png', '', '', array('style' => 'vertical-align:top;float:left;'));
			echo '</label>';
			echo '</td><td>';
			echo '<label for="layout_custom"><strong>'. _('Custom') .'</strong><br />';
			echo _('Define your own layout:');
			echo '</label>';
			echo '<table id="layout-manager">
				<tr>
				<td>
				<div class="layout-manager-row-add">+</div>';
			$sql = 'SELECT * FROM layouts_rows WHERE layout_id = $1 ORDER BY rank';
			$req_rows = db_query_params($sql,array($layout_id));
			while ($data = db_fetch_array($req_rows)) {
				echo '<table class="layout-manager-row">
					<tr>
					<td class="layout-manager-column-add">+</td>';
				$sql = 'SELECT * FROM layouts_rows_columns WHERE layout_row_id = $1';
				$req_cols = db_query_params($sql,array($data['id']));
				while ($data = db_fetch_array($req_cols)) {
					echo '<td class="layout-manager-column">
						<div class="layout-manager-column-remove">x</div>
						<div class="layout-manager-column-width">
						<input type="number" value="'. $data['width'] .'" size="1" maxlength="3" />%
						</div>
						</td>
						<td class="layout-manager-column-add">+</td>';
				}
				echo '  </tr>
					</table>
					<div class="layout-manager-row-add">+</div>';
			}
			echo '    </td>
				</tr>
				</table>';
			echo '</td></tr>';
			echo '</table>';
			echo '<input type="submit" id="save" value="'. _("Submit") .'" />';
		} else {
			// display the widget selection form
			$after = '';
			echo '<table>
				<tbody>
				<tr class="top">
				<td>';
			$after .= $this->_displayWidgetsSelectionForm(sprintf(_("%s Widgets"),  forge_get_config('forge_name')), Widget::getCodendiWidgets($owner_type), $used_widgets);
			echo '</td>
				<td id="widget-content-categ">'. $after .'</td>
				</tr>
				</tbody>
				</table>';
		}
		echo '</form>';
	}

	function updateLayout($owner_id, $owner_type, $layout, $custom_layout) {
		$sql = "SELECT l.*
			FROM layouts AS l INNER JOIN owner_layouts AS o ON(l.id = o.layout_id)
			WHERE o.owner_type = $1
			AND o.owner_id = $2
			AND o.is_default = 1
			";
		$req = db_query_params($sql,array($owner_type,$owner_id));
		if ($data = db_fetch_array($req)) {
			if ($this->_currentUserCanUpdateLayout($owner_id, $owner_type)) {
				$old_scope         = $data['scope'];
				$old_layout_id = $data['id'];
				$new_layout_id = null;
				if ($layout == '-1' && is_array($custom_layout)) {
					//Create a new layout based on the custom layout structure defined by the user
					$rows = array();
					foreach($custom_layout as $widths) {
						$row = array();
						$cols = explode(',', $widths);
						foreach($cols as $col) {
							if ($width = (int)$col) {
								$row[] = $width;
							}
						}
						if (count($row)) {
							$rows[] = $row;
						}
					}
					//If the structure contains at least one column, create a new layout
					if (count($rows)) {
						$sql = "INSERT INTO layouts(name, description, scope)
							VALUES ('custom', '', 'P')";
						if ($res = db_query_params($sql, array())) {
							if ($new_layout_id = db_insertid($res, 'layouts', 'id')) {
								//Create rows & columns
								$rank = 0;
								foreach($rows as $cols) {
									$sql = "INSERT INTO layouts_rows(layout_id, rank)
										VALUES ($1,$2)";
									if ($res = db_query_params($sql, array($new_layout_id, $rank++))) {
										if ($row_id = db_insertid($res,'layouts_rows', 'id')) {
											foreach($cols as $width) {
												$sql = "INSERT INTO layouts_rows_columns(layout_row_id, width)
													VALUES ($1,$2)";
												db_query_params($sql, array($row_id, $width));
											}
										}
									}
								}
							}
						}
					}
				} else {
					$new_layout_id = $layout;
				}

				if ($new_layout_id) {
					//Retrieve columns of old layout
					$old = $this->_retrieveStructureOfLayout($old_layout_id);

					//Retrieve columns of new layout
					$new = $this->_retrieveStructureOfLayout($new_layout_id);

					// Switch content from old columns to new columns
					$last_new_col_id = null;
					reset($new['columns']);
					foreach($old['columns'] as $old_col) {
						if (list(,$new_col) = each($new['columns'])) {
							$last_new_col_id = $new_col['id'];
						}
						$sql = "UPDATE layouts_contents
							SET layout_id  = $1
							, column_id  =$2
							WHERE owner_type =$3
							AND owner_id   =$4
							AND layout_id  =$5
							AND column_id  =$6;";
						db_query_params($sql,array($new_layout_id,$last_new_col_id,$owner_type,$owner_id,$old_layout_id,$old_col['id']));
					}
					$sql = "UPDATE owner_layouts
						SET layout_id  = $1
						WHERE owner_type = $2
						AND owner_id   = $3
						AND layout_id  = $4";
					db_query_params($sql, array($new_layout_id, $owner_type, $owner_id, $old_layout_id));

					//If the old layout is custom remove it
					if ($old_scope != 'S') {
						$structure = $this->_retrieveStructureOfLayout($old_layout_id);
						foreach($structure['rows'] as $row) {
							$sql = "DELETE FROM layouts_rows
								WHERE id  = $1";
							db_query_params($sql, array($row['id']));
							$sql = "DELETE FROM layouts_rows_columns
								WHERE layout_row_id  = $1";
							db_query_params($sql, array($row['id']));
						}
						$sql = "DELETE FROM layouts
							WHERE id  = $1";
						db_query_params($sql, array($old_layout_id));
					}

				}
			}
		}
		$this->feedback($owner_id, $owner_type);
	}

	function _retrieveStructureOfLayout($layout_id) {
		$structure = array('rows' => array(), 'columns' => array());
		$sql = 'SELECT * FROM layouts_rows WHERE layout_id = $1 ORDER BY rank';
		$req_rows = db_query_params($sql,array($layout_id));
		while ($row = db_fetch_array($req_rows)) {
			$structure['rows'][] = $row;
			$sql = 'SELECT * FROM layouts_rows_columns WHERE layout_row_id =$1 ORDER BY id';
			$req_cols = db_query_params($sql,array($row['id']));
			while ($col = db_fetch_array($req_cols)) {
				$structure['columns'][] = $col;
			}
		}
		return $structure;
	}

	/**
	 * _displayWidgetsSelectionForm - displays a widget selection form
	 *
	 * @param  title
	 * @param  widgets
	 * @param  used_widgets
     * @return string
     */
	function _displayWidgetsSelectionForm($title, $widgets, $used_widgets) {
		$hp = Codendi_HTMLPurifier::instance();
		$additionnal_html = '';
		if (count($widgets)) {
			$categs = $this->getCategories($widgets);
			$widget_rows = array();
			if (count($categs)) {
				// display the categories selector in left panel
				foreach($categs as $c => $ws) {
					$widget_rows[$c] = '<a class="widget-categ-switcher" id="widget-categ-switcher-'. $c .'" href="#widget-categ-'. $c .'" onClick="jQuery(\'.widget-categ-class-void\').hide();jQuery(\'.widget-categ-switcher\').removeClass(\'selected\');jQuery(\'#widget-categ-'. $c .'\').show();jQuery(\'#widget-categ-switcher-'. $c .'\').addClass(\'selected\');" ><span>'.  str_replace('_',' ', $hp->purify($c, CODENDI_PURIFIER_CONVERT_HTML))  .'</span></a>';
				}
				uksort($widget_rows, 'strnatcasecmp');
				echo '<ul id="widget-categories">';
				foreach($widget_rows as $row) {
					echo '<li>'. $row .'</li>';
				}
				echo '</ul>';
			} else {
				foreach($widgets as $widget_name) {
					if ($widget = Widget::getInstance($widget_name)) {
						if ($widget->isAvailable()) {
							$row = '';
							$row .= '<td>'. $widget->getTitle() . $widget->getInstallPreferences() .'</td>';
							$row .= '<td class="align-right">';
							if ($widget->isUnique() && in_array($widget_name, $used_widgets)) {
								$row .= '<em>'. _("Already used") .'</em>';
							} else {
								$row .= '<input type="submit" name="name['. $widget_name .'][add]" value="'. _("Add") .'" />';
							}
							$row .= '</td>';
							$widget_rows[$widget->getTitle()] = $row;
						}
					}
				}
				$i = 0;
				foreach($widget_rows as $row) {
					echo '<tr class="'. (count($widget_rows) ? '' : util_get_alt_row_color($i++)) .'">'. $row .'</tr>';
				}
			}
			if (count($categs)) {
				foreach($categs as $c => $ws) {
					$i = 0;
					$widget_rows = array();
					// display widgets of the category
					foreach($ws as $widget_name => $widget) {
						$row = '';
						$row .= '<div class="widget-preview '. $widget->getPreviewCssClass() .'">';
						$row .= '<h3>'. $widget->getTitle()  .'</h3>';
						$row .= '<p>'. $widget->getDescription() .'</p>';
						$row .= $widget->getInstallPreferences();
						$row .= '</div><div style="text-align:right; border-bottom:1px solid #ddd; padding-bottom:10px; margin-bottom:20px;">';
						if ($widget->isUnique() && in_array($widget_name, $used_widgets)) {
							$row .= '<em>'. _("Already used") .'</em>';
						} else {
							$row .= '<input type="submit" name="name['. $widget_name .'][add]" value="'. _("Add") .'" />';
						}
						$row .= '</div>';
						$widget_rows[$widget->getTitle()] = $row;
					}
					uksort($widget_rows, 'strnatcasecmp');
					$additionnal_html .= '<div id="widget-categ-'. $c .'" style="display:none" class="widget-categ-class-void" ><h2 class="boxtitle">'. str_replace('_',' ',$hp->purify($c, CODENDI_PURIFIER_CONVERT_HTML)) .'</h2>';
					foreach($widget_rows as $row) {
						$additionnal_html .= $row;
					}
					$additionnal_html .= '</div>';
				}
			}
		}
		return $additionnal_html;
	}

	/**
	 * getCategories - sort the widgets in their different categories
	 *
	 * @param array $widgets
	 * @return array (category => widgets)
	 */
	function getCategories($widgets) {
		$categ = array();
		foreach($widgets as $widget_name) {
			if ($widget = Widget::getInstance($widget_name)) {
				if ($widget->isAvailable()) {
					$category = str_replace(' ', '_', $widget->getCategory());
					$cs = explode(',', $category);
					foreach($cs as $c) {
						if ($c = trim($c)) {
							if (!isset($categ[$c])) {
								$categ[$c] = array();
							}
							$categ[$c][$widget_name] = $widget;
						}
					}
				}
			}
		}
		return $categ;
	}
	/**
	 * addWidget
	 *
	 * @param	int		$owner_id
	 * @param	string	$owner_type
	 * @param	int		$layout_id
	 * @param	string	$name
	 * @param	object	$widget
	 * @param	object	$request
	 */
	function addWidget($owner_id, $owner_type, $layout_id, $name, &$widget, &$request) {
		//Search for the right column. (The first used)
		$sql = "SELECT u.column_id AS id
			FROM layouts_contents AS u
			LEFT JOIN (SELECT r.rank AS rank, c.id as id
					FROM layouts_rows AS r INNER JOIN layouts_rows_columns AS c
					ON (c.layout_row_id = r.id)
					WHERE r.layout_id = $1) AS col
			ON (u.column_id = col.id)
			WHERE u.owner_type = $2
			AND u.owner_id = $3
			AND u.layout_id = $4
			AND u.column_id <> 0
			ORDER BY col.rank, col.id";
		$res = db_query_params($sql,array($layout_id,$owner_type,$owner_id,$layout_id));
		echo db_error();
		$column_id = db_result($res, 0, 'id');
		if (!$column_id) {
			$sql = "SELECT r.rank AS rank, c.id as id
				FROM layouts_rows AS r
				INNER JOIN layouts_rows_columns AS c
				ON (c.layout_row_id = r.id)
				WHERE r.layout_id = $1
				ORDER BY rank, id";
			$res = db_query_params($sql,array($layout_id));
			$column_id = db_result($res, 0, 'id');
		}

		//content_id
		if ($widget->isUnique()) {
			//unique widgets do not have content_id
			$content_id = 0;
		} else {
			$content_id = $widget->create($request);
		}

		//See if it already exists but not used
		$sql = "SELECT column_id FROM layouts_contents
			WHERE owner_type =$1
			AND owner_id = $2
			AND layout_id = $3
			AND name = $4";
		$res = db_query_params($sql,array($owner_type,$owner_id,$layout_id, $name));
		echo db_error();
		if (db_numrows($res) && !$widget->isUnique() && db_result($res, 0, 'column_id') == 0) {
			//search for rank
			$sql = "SELECT min(rank) - 1 AS rank FROM layouts_contents WHERE owner_type =$1 AND owner_id = $2 AND layout_id = $3 AND column_id = $4 ";
			$res = db_query_params($sql,array($owner_type, $owner_id, $layout_id,$column_id));
			echo db_error();
			$rank = db_result($res, 0, 'rank');

			//Update
			$sql = "UPDATE layouts_contents
				SET column_id = $1, rank = $2
				WHERE owner_type = $3
				AND owner_id = $4
				AND name = $5
				AND layout_id = $6";
			$res = db_query_params($sql,array($column_id,$rank,$owner_type, $owner_id,$name, $layout_id));
			echo db_error();
		} else {
			//Insert
			$sql = "INSERT INTO layouts_contents(owner_type, owner_id, layout_id, column_id, name, content_id, rank)
				SELECT R1.owner_type, R1.owner_id, R1.layout_id, R1.column_id, $1, $2, coalesce(R2.rank, 1) - 1
				FROM ( SELECT $3::character varying(1) AS owner_type, $4::integer AS owner_id, $5::integer AS layout_id, $6::integer AS column_id ) AS R1
				LEFT JOIN layouts_contents AS R2 USING ( owner_type, owner_id, layout_id, column_id )
				ORDER BY rank ASC
				LIMIT 1";
			if (forge_get_config('sysdebug_enable')) {
				$myfile=fopen('/tmp/debug','a');
				$params = array($name,$content_id,$owner_type,$owner_id,$layout_id,$column_id);
				fwrite($myfile, $sql." devient:\n");
				fwrite($myfile, str_replace(array("$1","$2","$3","$4","$5","$6"),$params,$sql));
				fwrite($myfile, "\n request content=".$request->get('content_id'));
			}
			db_query_params($sql,array($name,$content_id,$owner_type,$owner_id,$layout_id,$column_id));
			echo db_error();
		}
		$this->feedback($owner_id, $owner_type);
	}

	protected function feedback($owner_id, $owner_type) {
		$link = '/';
		if ($owner_type == self::OWNER_TYPE_GROUP) {
			//retrieve the short name of the project
			if ($project = ProjectManager::instance()->getProject($owner_id)) {
				$hp = Codendi_HTMLPurifier::instance();
				$link = '/projects/'.  $hp->purify($project->getUnixName(), CODENDI_PURIFIER_CONVERT_HTML) ;
			}
		} elseif ($owner_type == self::OWNER_TYPE_USER) {
			$link = '/my/';
		}
		$GLOBALS['feedback'] .= _('Your dashboard has been updated.');
	}

	/**
	 * removeWidget
	 *
	 * @param	int		$owner_id
	 * @param	string	$owner_type
	 * @param	int		$layout_id
	 * @param	string	$name
	 * @param	int		$instance_id
	 * @param	object	$widget
	 */
	function removeWidget($owner_id, $owner_type, $layout_id, $name, $instance_id, &$widget) {
		$sql = "DELETE FROM layouts_contents WHERE owner_type =$1 AND owner_id = $2 AND layout_id = $3 AND name = $4 AND content_id = $5";
		db_query_params($sql,array($owner_type,$owner_id,$layout_id,$name,$instance_id));
		if (!db_error()) {
			$widget->destroy($instance_id);
		}
	}

	/**
	 * mimizeWidget
	 *
	 * @param	int		$owner_id
	 * @param	string	$owner_type
	 * @param	int		$layout_id
	 * @param	string	$name
	 * @param	int		$instance_id
	 */
	function mimizeWidget($owner_id, $owner_type, $layout_id, $name, $instance_id) {
		$sql = "UPDATE layouts_contents SET is_minimized = 1 WHERE owner_type = $1 AND owner_id = $2 AND layout_id = $3 AND name = $4 AND content_id = $5";
		db_query_params($sql,array($owner_type,$owner_id,$layout_id,$name,$instance_id));
		echo db_error();
	}

	/**
	 * maximizeWidget
	 *
	 * @param	int		$owner_id
	 * @param	string	$owner_type
	 * @param	int		$layout_id
	 * @param	string	$name
	 * @param	int		$instance_id
	 */
	function maximizeWidget($owner_id, $owner_type, $layout_id, $name, $instance_id) {
		$sql = "UPDATE layouts_contents SET is_minimized = 0 WHERE owner_type =$1 AND owner_id =$2 AND layout_id = $3 AND name = $4 AND content_id = $5";
		db_query_params($sql,array($owner_type,$owner_id,$layout_id,$name,$instance_id));
		echo db_error();
	}

	/**
	 * displayWidgetPreferences
	 *
	 * @param	int		$owner_id
	 * @param	string	$owner_type
	 * @param	int		$layout_id
	 * @param	string	$name
	 * @param	int		$instance_id
	 */
	function displayWidgetPreferences($owner_id, $owner_type, $layout_id, $name, $instance_id) {
		$sql = "UPDATE layouts_contents SET display_preferences = 1, is_minimized = 0 WHERE owner_type = $1 AND owner_id = $2 AND layout_id = $3 AND name = $4 AND content_id = $5";
		db_query_params($sql,array($owner_type,$owner_id,$layout_id,$name,$instance_id));
		echo db_error();
	}

	/**
	 * hideWidgetPreferences
	 *
	 * @param	int		$owner_id
	 * @param	string	$owner_type
	 * @param	int		$layout_id
	 * @param	string	$name
	 * @param	int		$instance_id
	 */
	function hideWidgetPreferences($owner_id, $owner_type, $layout_id, $name, $instance_id) {
		$sql = "UPDATE layouts_contents SET display_preferences = 0 WHERE owner_type = $1 AND owner_id = $2 AND layout_id = $3 AND name = $4 AND content_id = $5";
		db_query_params($sql,array($owner_type,$owner_id,$layout_id,$name,$instance_id));
		echo db_error();
	}

	/**
	 * reorderLayout
	 *
	 * @param	int		$owner_id
	 * @param	string	$owner_type
	 * @param	int		$layout_id
	 * @param	object	$request
	 */
	function reorderLayout($owner_id, $owner_type, $layout_id, &$request) {
		$keys = array_keys($_REQUEST);
		foreach($keys as $key) {
			if (preg_match('`widgetlayout_col_\d+`', $key)) {

				$split = explode('_', $key);
				$column_id = (int)$split[count($split)-1];

				$names = array();
				foreach($request->get($key) as $name) {
					list($name, $id) = explode('-', $name);
					$names[] = array($id, $name);
				}

				//Compute differences
				$originals = array();
				$sql = "SELECT * FROM layouts_contents WHERE owner_type = $1 AND owner_id = $2 AND column_id = $3 ORDER BY rank";
				$res = db_query_params($sql,array($owner_type, $owner_id, $column_id));
				echo db_error();
				while($data = db_fetch_array($res)) {
					$originals[] = array($data['content_id'], $data['name']);
				}

				//delete removed contents
				$deleted_names = $this->_array_diff_names($originals, $names);
				if (count($deleted_names)) {
					$_and = '';
					foreach($deleted_names as $id => $name) {
						if ($_and) {
							$_and .= ' OR ';
						} else {
							$_and .= ' AND (';
						}
						$_and .= " (name = '".$name[1]."' AND content_id = ". $name[0] .") ";
					}
					$_and .= ')';
					$sql = "UPDATE layouts_contents
						SET column_id = 0
						WHERE owner_type = $1
						AND owner_id = $2
						AND column_id = $3". $_and;
					$res = db_query_params($sql,array($owner_type, $owner_id, $column_id));
					echo db_error();
				}

				//Insert new contents
				$added_names = $this->_array_diff_names($names, $originals);
				if (count($added_names)) {
					$_and = '';
					foreach($added_names as $name) {
						if ($_and) {
							$_and .= ' OR ';
						} else {
							$_and .= ' AND (';
						}
						$_and .= " (name = '".$name[1]."' AND content_id = ". $name[0] .") ";
					}
					$_and .= ')';
					//old and new column must be part of the same layout
					$sql = 'UPDATE layouts_contents
						SET column_id = $1
						WHERE owner_type = $2
						AND owner_id = $3' . $_and ."
						AND layout_id = $4";
					$res = db_query_params($sql,array($column_id,$owner_type,$owner_id,$layout_id));
					echo db_error();
				}

				//Update ranks
				$rank = 0;
				$values = array();
				foreach($names as $name) {
					$sql = 'UPDATE layouts_contents SET rank = $1 WHERE owner_type =$2 AND owner_id = $3 AND column_id = $4 AND name = $5 AND content_id = $6';
					db_query_params($sql, array($rank++,$owner_type,$owner_id,$column_id,$name[1],$name[0]));
					echo db_error();
				}
			}
		}
	}

	/**
	 * compute the differences between two arrays
	 */
	function _array_diff_names($tab1, $tab2) {
		$diff = array();
		foreach($tab1 as $e1) {
			$found = false;
			reset($tab2);
			while(!$found && list(,$e2) = each($tab2)) {
				$found = !count(array_diff($e1, $e2));
			}
			if (!$found) {
				$diff[] = $e1;
			}
		}
		return $diff;
	}
}