Projet

Général

Profil

Paste
Statistiques
| Branche: | Révision:

ryxeo-glpi-git / htdocs / inc / db.function.php @ 1c14bcc4

Historique | Voir | Annoter | Télécharger (25,3 ko)

1
<?php
2
/*
3
 * @version $Id: db.function.php 7876 2009-01-23 15:50:37Z moyo $
4
 -------------------------------------------------------------------------
5
 GLPI - Gestionnaire Libre de Parc Informatique
6
 Copyright (C) 2003-2009 by the INDEPNET Development Team.
7

8
 http://indepnet.net/   http://glpi-project.org
9
 -------------------------------------------------------------------------
10

11
 LICENSE
12

13
 This file is part of GLPI.
14

15
 GLPI is free software; you can redistribute it and/or modify
16
 it under the terms of the GNU General Public License as published by
17
 the Free Software Foundation; either version 2 of the License, or
18
 (at your option) any later version.
19

20
 GLPI is distributed in the hope that it will be useful,
21
 but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23
 GNU General Public License for more details.
24

25
 You should have received a copy of the GNU General Public License
26
 along with GLPI; if not, write to the Free Software
27
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
28
 --------------------------------------------------------------------------
29
 */
30

    
31
// ----------------------------------------------------------------------
32
// Original Author of file:
33
// Purpose of file:
34
// ----------------------------------------------------------------------
35

    
36
if (!defined('GLPI_ROOT')){
37
        die("Sorry. You can't access directly to this file");
38
        }
39

    
40
/**
41
 * Count the number of elements in a table.
42
 *
43
 * @param $table string: table name
44
 * @param $condition string: condition to use
45
 *
46
 * return int nb of elements in table
47
 */
48
function countElementsInTable($table,$condition=""){
49
        global $DB;
50
        $query="SELECT count(*) AS cpt
51
                FROM `$table`";
52
        if (!empty($condition)){
53
                $query.=" WHERE $condition ";
54
        }
55
        $result=$DB->query($query);
56
        $ligne = $DB->fetch_array($result);
57
        return $ligne['cpt'];
58
}
59

    
60
/**
61
 * Count the number of elements in a table for a specific entity
62
 *
63
 * @param $table string: table name
64
 *
65
 * return int nb of elements in table
66
 */
67
function countElementsInTableForMyEntities($table){
68
        global $CFG_GLPI;
69
        return countElementsInTable($table,getEntitiesRestrictRequest("",$table,'','',in_array($table,$CFG_GLPI["recursive_type"])));
70
}
71
/**
72
 * Count the number of elements in a table for a specific entity
73
 *
74
 * @param $table string: table name
75
 * @param $entity integer: the entity ID
76
 *
77
 * return int nb of elements in table
78
 */
79
function countElementsInTableForEntity($table,$entity){
80
        global $CFG_GLPI;
81
        return countElementsInTable($table,getEntitiesRestrictRequest("",$table,'',$entity,in_array($table,$CFG_GLPI["recursive_type"])));
82
}
83
/**
84
 * Get datas from a table in an array : CAUTION TO USE ONLY FOR SMALL TABLES OR USING A STRICT CONDITION
85
 * 
86
 * @param $table string: table name
87
 * @param $condition string: condition to use
88
 *
89
 * return array containing all the datas
90
 */
91
function getAllDatasFromTable($table,$condition=""){
92
        global $DB;
93
        $datas=array();
94
        $query="SELECT * FROM `$table` ";
95

    
96
        if (!empty($condition)){
97
                $query.=" WHERE $condition ";
98
        }
99

    
100
        if ($result=$DB->query($query)){
101
                while ($data=$DB->fetch_assoc($result)){
102
                        $datas[$data['ID']]=$data;
103
                }
104
        }
105
        return $datas;
106
}
107

    
108
/**
109
 * Get the Name of the element of a Dropdown Tree table
110
 *
111
 * @param $table string: Dropdown Tree table
112
 * @param $ID integer: ID of the element
113
 * @param $withcomments boolean: 1 if you want to give the array with the comments
114
 * @return string : name of the element
115
 * @see getTreeValueCompleteName
116
 */
117
function getTreeLeafValueName($table,$ID,$withcomments=false){
118
        global $DB,$LANG;
119

    
120
        $name="";
121
        $comments="";
122
        if ($ID==0 && $table=="glpi_entities") {
123
                $name = $LANG["entity"][2];
124
                
125
        } else if ($ID==0 && $table=="glpi_dropdown_kbcategories") {
126
                $name = $LANG["knowbase"][12];
127
                
128
        } else {
129
                $query = "SELECT *
130
                        FROM `$table` 
131
                        WHERE (ID = '$ID')";
132
                if ($result=$DB->query($query)){
133
                        if ($DB->numrows($result)==1){
134
                                $name=$DB->result($result,0,"name");
135
                                $comments=$DB->result($result,0,"comments");
136
                        }
137
        
138
                }
139
        }
140
        if ($withcomments){
141
                return array("name"=>$name,"comments"=>$comments);
142
        } else {
143
                return $name;
144
        }
145
}
146

    
147
/**
148
 * Get completename of a Dropdown Tree table
149
 *
150
 * @param $table string: Dropdown Tree table
151
 * @param $ID integer: ID of the element
152
 * @param $withcomments boolean: 1 if you want to give the array with the comments
153
 * @return string : completename of the element
154
 * @see getTreeLeafValueName
155
 */
156
function getTreeValueCompleteName($table,$ID,$withcomments=false){
157
        global $DB,$LANG;
158
        $name="";
159
        $comments="";
160

    
161
        if ($ID==0 && $table=="glpi_entities") {
162
                $name = $LANG["entity"][2];
163

    
164
        } else if ($ID==0 && $table=="glpi_dropdown_kbcategories") {
165
                $name = $LANG["knowbase"][12];
166
                
167
        } else {
168
                $query = "SELECT *
169
                        FROM `$table` 
170
                        WHERE (ID = '$ID')";
171
                if ($result=$DB->query($query)){
172
                        if ($DB->numrows($result)==1){
173
                                $name=$DB->result($result,0,"completename");
174
                                $comments=$name.":<br>";
175
                                $comments.=$DB->result($result,0,"comments");
176
                        }
177
        
178
                }
179
        }
180
        if (empty($name)) {
181
                $name="&nbsp;";
182
        }
183
        if ($withcomments) {
184
                return array("name"=>$name,"comments"=>$comments);
185
        } else {
186
                return $name;
187
        }
188
}
189

    
190
/**
191
 * show name category
192
 * DO NOT DELETE THIS FUNCTION : USED IN THE UPDATE
193
 *
194
 * @param $table string: table name
195
 * @param $ID integer: value ID
196
 * @param $wholename string : current name to complete (use for recursivity)
197
 * @param $level integer: current level of recursion
198
 * @return string name
199
 */
200
function getTreeValueName($table,$ID, $wholename="",$level=0){
201
        global $DB,$LANG;
202

    
203
        $query = "SELECT *
204
                FROM `$table`
205
                WHERE (ID = '$ID')";
206
        $name="";
207

    
208
        if ($result=$DB->query($query)){
209
                if ($DB->numrows($result)>0){
210

    
211
                        $row=$DB->fetch_array($result);
212

    
213
                        $parentID = $row["parentID"];
214
                        if($wholename == "")
215
                        {
216
                                $name = $row["name"];
217
                        } else
218
                        {
219
                                $name = $row["name"] . " > ";
220
                        }
221
                        $level++;
222
                        list($tmpname,$level)=getTreeValueName($table,$parentID, $name,$level);
223
                        $name =  $tmpname. $name;
224
                }
225

    
226
        }
227
        return array($name,$level);
228
}
229

    
230

    
231
/**
232
 * Get the ancestors of an entity
233
 * result is cached in session
234
 *
235
 * @param $ID integer: The ID of the entity
236
 * @return array of IDs of the ancestors
237
 */
238
function getEntityAncestors ($ID){
239
        if (!isset($_SESSION['glpi_entities_ancestors'][$ID])){
240
                $_SESSION['glpi_entities_ancestors'][$ID]=getAncestorsOfTreeItem("glpi_entities",$ID);
241
        }
242
        return $_SESSION['glpi_entities_ancestors'][$ID];
243
}
244

    
245
/**
246
 * Get the sons of an entity
247
 * result is cached in session
248
 *
249
 * @param $ID integer: The ID of the entity
250
 * @return array of IDs of the sons (including ID of the searched entity)
251
 */
252
function getEntitySons ($ID){
253
        if (!isset($_SESSION['glpi_entities_sons'][$ID])){
254
                $_SESSION['glpi_entities_sons'][$ID]=getSonsOfTreeItem("glpi_entities",$ID);
255
        }
256
        return $_SESSION['glpi_entities_sons'][$ID];
257
}
258

    
259
/**
260
 * Get the ancestors of an item in a tree dropdown
261
 *
262
 * @param $table string: table name
263
 * @param $IDf integer: The ID of the item
264
 * @return array of IDs of the ancestors
265
 */
266
function getAncestorsOfTreeItem($table,$IDf){
267
        global $DB;
268

    
269
        // IDs to be present in the final array
270
        $id_found=array();
271
        
272
        // Get the leafs of previous founded item
273
        while ($IDf>0){
274
                // Get next elements
275
                $query="SELECT parentID
276
                        FROM `$table` 
277
                        WHERE ID = '$IDf'";
278

    
279
                $result=$DB->query($query);
280
                if ($DB->numrows($result)>0){
281
                        $IDf=$DB->result($result,0,0);
282
                } else {
283
                        $IDf=0;
284
                }
285
                if ($IDf>=0&&!in_array($IDf,$id_found)){
286
                        $id_found[]=$IDf;
287
                } else {
288
                        $IDf=0;
289
                }
290
        }
291
        return $id_found;
292

    
293
}
294

    
295
/**
296
 * Get the sons of an item in a tree dropdown
297
 *
298
 * @param $table string: table name
299
 * @param $IDf integer: The ID of the father
300
 * @return array of IDs of the sons
301
 */
302
function getSonsOfTreeItem($table,$IDf){
303
        global $DB;
304

    
305
        // IDs to be present in the final array
306
        $id_found=array($IDf);
307
        // current ID found to be added
308
        $found=array();
309
        // First request init the  varriables
310
        $query="SELECT ID
311
                FROM `$table` 
312
                WHERE parentID = '$IDf'
313
                ORDER BY name";
314

    
315
        if ( ($result=$DB->query($query)) && ($DB->numrows($result)>0) ){
316
                while ($row=$DB->fetch_array($result)){
317
                        array_push($id_found,$row['ID']);
318
                        array_push($found,$row['ID']);
319
                }
320
        } else return $id_found;
321

    
322
        // Get the leafs of previous founded item
323
        while (count($found)>0){
324
                $first=true;
325
                // Get next elements
326
                $query="SELECT ID
327
                        FROM `$table` 
328
                        WHERE ";
329
                foreach ($found as $key => $val){
330
                        if (!$first) $query.=" OR ";
331
                        else $first=false;
332
                        $query.= " parentID = '$val' ";
333
                }
334
                        
335

    
336
                // CLear the found array
337
                unset($found);
338
                $found=array();
339

    
340
                $result=$DB->query($query);
341
                if ($DB->numrows($result)>0){
342
                        while ($row=$DB->fetch_array($result)){
343
                                if (!in_array($row['ID'],$id_found)){
344
                                        array_push($id_found,$row['ID']);
345
                                        array_push($found,$row['ID']);
346
                                }
347
                        }                
348
                }
349
        }
350
        return $id_found;
351

    
352
}
353

    
354
/**
355
 * Get the sons of an item in a tree dropdown
356
 *
357
 * @param $table string: table name
358
 * @param $IDf integer: The ID of the father
359
 * @return array of IDs of the sons
360
 */
361
function getTreeForItem($table,$IDf){
362
        global $DB;
363

    
364
        // IDs to be present in the final array
365
        $id_found=array();
366

    
367
        // current ID found to be added
368
        $found=array();
369
        // First request init the  varriables
370
        $query="SELECT *
371
                FROM `$table` 
372
                WHERE parentID = '$IDf' ORDER BY name";
373
        if ( ($result=$DB->query($query)) && ($DB->numrows($result)>0) ){
374
                while ($row=$DB->fetch_array($result)){
375
                        $id_found[$row['ID']]['parent']=$IDf;
376
                        $id_found[$row['ID']]['name']=$row['name'];
377
                        array_push($found,$row['ID']);
378
                }
379
        }
380

    
381
        // Get the leafs of previous founded item
382
        while (count($found)>0){
383
                $first=true;
384
                // Get next elements
385
                $query="SELECT *
386
                        FROM `$table` 
387
                        WHERE ";
388
                foreach ($found as $key => $val){
389
                        if (!$first) $query.=" OR ";
390
                        else $first=false;
391
                        $query.= " parentID = '$val' ";
392
                }
393
                $query.=" ORDER BY name";
394
                // CLear the found array
395
                unset($found);
396
                $found=array();
397

    
398
                $result=$DB->query($query);
399
                if ($DB->numrows($result)>0){
400
                        while ($row=$DB->fetch_array($result)){
401
                                if (!in_array($row['ID'],$id_found)){
402
                                        $id_found[$row['ID']]['parent']=$row['parentID'];
403
                                        $id_found[$row['ID']]['name']=$row['name'];
404
                                        array_push($found,$row['ID']);
405
                                }
406
                        }                
407
                }
408
        }
409
        $tree[$IDf]['name']=getDropdownName($table,$IDf);
410
        $tree[$IDf]['tree']=contructTreeFromList($id_found,$IDf);
411
        return $tree;
412

    
413
}
414

    
415
/**
416
 * Construct a tree from a list structure
417
 *
418
 * @param $list array: the list
419
 * @param $root integer: root of the tree
420
 * @return list of items in the tree
421
 */
422
function contructTreeFromList($list,$root){
423
        $tree=array();
424
        
425

    
426
        foreach ($list as $ID => $data){
427
                if ($data['parent']==$root){
428
                        unset($list[$ID]);
429
                        $tree[$ID]['name']=$data['name'];
430
                        $tree[$ID]['tree']=contructTreeFromList($list,$ID);
431
                }
432
        }
433
        return $tree;
434

    
435
}
436

    
437
/**
438
 * Construct a list from a tree structure
439
 *
440
 * @param $tree array: the tree
441
 * @param $parent integer: root of the tree
442
 * @return list of items in the tree
443
 */
444
function contructListFromTree($tree,$parent=0){
445
        $list=array();
446
        foreach ($tree as $root => $data){
447
                $list[$root]=$parent;
448
                if (is_array($data['tree'])&&count($data['tree'])){
449
                        foreach ($data['tree'] as $ID => $underdata){
450
                                $list[$ID]=$root;
451
                                if (is_array($underdata['tree'])&&count($underdata['tree'])){
452
                                        $list+=contructListFromTree($underdata['tree'],$ID);
453
                                }
454
                        }
455
                }
456
        }
457
        return $list;
458

    
459
}
460

    
461
/**
462
 * Get the equivalent search query using ID of soons that the search of the father's ID argument
463
 *
464
 * @param $table string: table name
465
 * @param $IDf integer: The ID of the father
466
 * @param $reallink string: real field to link ($table.ID if not set)
467
 * @return string the query
468
 */
469
function getRealQueryForTreeItem($table,$IDf,$reallink=""){
470

    
471
        global $DB;
472

    
473
        if (empty($IDf)) return "";
474

    
475
        if (empty($reallink)) $reallink=$table.".ID";
476

    
477
        $id_found=getSonsOfTreeItem($table,$IDf);
478

    
479

    
480
        // Construct the final request
481
        if (count($id_found)>0){
482
                $ret=" ( ";
483
                $i=0;
484
                foreach ($id_found as $key => $val){
485
                        if ($i>0) $ret.=" OR ";
486
                        $ret.="$reallink = '$val' ";
487
                        $i++;
488
                }
489
                $ret.=") ";
490

    
491
                return $ret;
492
        } else return " ( $reallink = '$IDf') ";
493
}
494

    
495

    
496
/*  // NOT USED
497
 * Get the level for an item in a tree structure
498
 *
499
 * @param $table table name
500
 * @param $ID ID of the item
501
 * @return int level
502
 *
503
function getTreeItemLevel($table,$ID){
504
        global $DB;
505
        $level=0;
506

507
        $query="SELECT parentID 
508
                FROM $table 
509
                WHERE ID='$ID'";
510
        while (1)
511
        {
512
                if (($result=$DB->query($query))&&$DB->numrows($result)==1){
513
                        $parentID=$DB->result($result,0,"parentID");
514
                        if ($parentID==0) return $level;
515
                        else {
516
                                $level++;
517
                                $query="SELECT parentID 
518
                                        FROM $table 
519
                                        WHERE ID='$parentID'";
520
                        }
521
                }
522
        }
523

524

525
        return -1;
526

527
}
528
*/
529

    
530
/**
531
 * Compute all completenames of Dropdown Tree table
532
 *
533
 * @param $table : dropdown tree table to compute
534
 * @return nothing
535
 */
536
function regenerateTreeCompleteName($table){
537
        global $DB;
538
        $query="SELECT ID
539
                FROM `$table`";
540
        $result=$DB->query($query);
541
        if ($DB->numrows($result)>0){
542
                while ($data=$DB->fetch_array($result)){
543
                        list($name,$level)=getTreeValueName($table,$data['ID']);
544
                        $query="UPDATE $table 
545
                                SET completename='".addslashes($name)."', level='$level' 
546
                                WHERE ID='".$data['ID']."'";
547
                        $DB->query($query);
548
                }
549
        }
550
}
551

    
552
/**
553
 * Compute completename of Dropdown Tree table under the element of ID $ID
554
 *
555
 * @param $table : dropdown tree table to compute
556
 * @param $ID : root ID to used : regenerate all under this element
557
 * @return nothing
558
 */
559
function regenerateTreeCompleteNameUnderID($table,$ID){
560
        global $DB;
561

    
562
        list($name,$level)=getTreeValueName($table,$ID);
563

    
564
        $query="UPDATE $table
565
                SET completename='".addslashes($name)."', level='$level'
566
                WHERE ID='".$ID."'";
567
        $DB->query($query);
568
        $query="SELECT ID
569
                FROM `$table` 
570
                WHERE parentID='$ID'";
571
        $result=$DB->query($query);
572
        if ($DB->numrows($result)>0){
573
                while ($data=$DB->fetch_array($result)){
574
                        regenerateTreeCompleteNameUnderID($table,$data["ID"]);
575
                }
576
        }
577

    
578
}
579

    
580
/**
581
 * Get the ID of the next Item
582
 *
583
 * @param $table table to search next item
584
 * @param $ID current ID
585
 * @param $condition condition to add to the search
586
 * @param $nextprev_item field used to sort
587
 * @return the next ID, -1 if not exist
588
 */
589
function getNextItem($table,$ID,$condition="",$nextprev_item=""){
590
        global $DB,$CFG_GLPI;
591

    
592
        if (empty($nextprev_item)){
593
                $nextprev_item=$CFG_GLPI["nextprev_item"];
594
        }
595

    
596
        $search=$ID;
597

    
598
        if ($nextprev_item!="ID"){
599
                $query="SELECT `".$nextprev_item."`
600
                        FROM `$table`
601
                        WHERE ID='$ID'";
602
                if ($result=$DB->query($query)){
603
                        if ($DB->numrows($result)>0){
604
                                $search=addslashes($DB->result($result,0,0));
605
                        } else {
606
                                $nextprev_item="ID";
607
                        }
608
                }
609
        }
610

    
611
        $LEFTJOIN='';
612
        if ($table=="glpi_users"){
613
                $LEFTJOIN=' LEFT JOIN glpi_users_profiles ON (glpi_users.ID = glpi_users_profiles.FK_users)';
614
        }
615

    
616
        $query = "SELECT `$table`.ID
617
                FROM `$table` $LEFTJOIN
618
                WHERE ( `$table`.`".$nextprev_item."` > '$search' ";
619

    
620
        // Same name case
621
        if ($nextprev_item!="ID"){
622
                $query .= " OR (`$table`.`".$nextprev_item."` = '$search' AND `$table`.ID > '$ID') ";
623
        }
624

    
625
        $query.=" ) ";
626

    
627
        if (!empty($condition)){
628
                $query.=" AND $condition";
629
        }
630
        if (in_array($table,$CFG_GLPI["deleted_tables"]))
631
                $query.=" AND `$table`.deleted='0' ";
632
        if (in_array($table,$CFG_GLPI["template_tables"]))
633
                $query.=" AND `$table`.is_template='0' ";
634

    
635
        // Restrict to active entities
636
        if (in_array($table,$CFG_GLPI["specif_entities_tables"])){
637
                $query.=getEntitiesRestrictRequest("AND",$table,'','',in_array($table,$CFG_GLPI["recursive_type"]));
638
        } else if ($table=="glpi_users"){
639
                $query.=getEntitiesRestrictRequest("AND","glpi_users_profiles");
640
        }
641

    
642
        //$query.=" ORDER BY ".$nextprev_item." ASC, ID ASC";
643
        $query.=" ORDER BY `$table`.`$nextprev_item` ASC, `$table`.ID ASC";
644

    
645
        $result=$DB->query($query);
646
        if ($result&&$DB->numrows($result)>0)
647
                return $DB->result($result,0,"ID");
648
        else return -1;
649

    
650
}
651

    
652
/**
653
 * Get the ID of the previous Item
654
 *
655
 * @param $table table to search next item
656
 * @param $ID current ID
657
 * @param $condition condition to add to the search
658
 * @param $nextprev_item field used to sort
659
 * @return the previous ID, -1 if not exist
660
 */
661
function getPreviousItem($table,$ID,$condition="",$nextprev_item=""){
662
        global $DB,$CFG_GLPI;
663

    
664
        if (empty($nextprev_item)){
665
                $nextprev_item=$CFG_GLPI["nextprev_item"];
666
        }
667

    
668
        $search=$ID;
669
        if ($nextprev_item!="ID"){
670
                $query="SELECT `".$nextprev_item."`
671
                        FROM `$table`
672
                        WHERE ID='$ID'";
673
                $result=$DB->query($query);
674
                if ($DB->numrows($result)>0){
675
                        $search=addslashes($DB->result($result,0,0));
676
                } else {
677
                        $nextprev_item="ID";
678
                }
679
        }
680

    
681
        $LEFTJOIN='';
682
        if ($table=="glpi_users"){
683
                $LEFTJOIN=' LEFT JOIN glpi_users_profiles ON (glpi_users.ID = glpi_users_profiles.FK_users)';
684
        }
685

    
686
        $query = "SELECT `$table`.ID
687
                FROM `$table` $LEFTJOIN
688
                WHERE  (`$table`.`".$nextprev_item."` < '$search' ";
689

    
690
        // Same name case
691
        if ($nextprev_item!="ID"){
692
                $query .= " OR (`$table`.`".$nextprev_item."` = '$search' AND `$table`.ID < '$ID') ";
693
        }
694

    
695
        $query.=" ) ";
696

    
697

    
698
        if (!empty($condition)){
699
                $query.=" AND $condition";
700
        }
701

    
702
        if (in_array($table,$CFG_GLPI["deleted_tables"]))
703
                $query.="AND `$table`.deleted='0'";
704
        if (in_array($table,$CFG_GLPI["template_tables"]))
705
                $query.="AND `$table`.is_template='0'";
706

    
707
        // Restrict to active entities
708
        if (in_array($table,$CFG_GLPI["specif_entities_tables"])){
709
                $query.=getEntitiesRestrictRequest("AND",$table,'','',in_array($table,$CFG_GLPI["recursive_type"]));
710
        } else if ($table=="glpi_users"){
711
                $query.=getEntitiesRestrictRequest("AND","glpi_users_profiles");
712
        }
713

    
714
        $query.=" ORDER BY `$table`.`".$nextprev_item."` DESC, `$table`.ID DESC";
715

    
716
        $result=$DB->query($query);
717
        if ($result&&$DB->numrows($result)>0)
718
                return $DB->result($result,0,"ID");
719
        else return -1;
720

    
721
}
722

    
723
/**
724
 * Format a user name
725
 *
726
 *@param $ID int : ID of the user.
727
 *@param $login string : login of the user
728
 *@param $realname string : realname of the user
729
 *@param $firstname string : firstname of the user
730
 *@param $link int : include link (only if $link==1)
731
 *@param $cut int : limit string length (0 = no limit)
732
 *
733
 *@return string : formatted username
734
 *
735
 **/
736
function formatUserName($ID,$login,$realname,$firstname,$link=0,$cut=0){
737
        global $CFG_GLPI;
738
        $before="";
739
        $after="";
740
        $viewID="";
741
        if (strlen($realname)>0) {
742
                $temp=$realname;
743
                
744
                if (strlen($firstname)>0)$temp.=" ".$firstname;
745

    
746
                if($cut>0&&strlen($temp) > $cut){
747
                        $temp=utf8_substr($temp,0,$cut);
748
                        $temp.=" ..."; 
749
                }
750
        }
751
        else {
752
                $temp=$login;
753
        }
754

    
755
        if ($ID>0&&(strlen($temp)==0||$CFG_GLPI["view_ID"])){
756
                $viewID="&nbsp;($ID)";
757
        }
758

    
759
        if ($link==1&&$ID>0){
760
                $before="<a href=\"".$CFG_GLPI["root_doc"]."/front/user.form.php?ID=".$ID."\" title=\"".$temp."\">";
761
                $after="</a>";
762
        }
763

    
764
        $username=$before.$temp.$viewID.$after;
765

    
766
        return $username;
767

    
768

    
769
}
770

    
771
/**
772
 * Get name of the user with ID=$ID (optional with link to user.form.php)
773
 *
774
 *@param $ID int : ID of the user.
775
 *@param $link int : 1 = Show link to user.form.php 2 = return array with comments and link
776
 *
777
 *@return string : username string (realname if not empty and name if realname is empty).
778
 *
779
 **/
780
function getUserName($ID,$link=0){
781
        global $DB,$CFG_GLPI,$LANG;
782

    
783
        $user="";
784
        if ($link==2){
785
                $user=array("name"=>"","link"=>"","comments"=>"");
786
        }
787
        if ($ID){
788
                $query="SELECT * 
789
                        FROM glpi_users 
790
                        WHERE ID='$ID'";
791
                $result=$DB->query($query);
792
                
793
                if ($link==2) $user=array("name"=>"","comments"=>"","link"=>"");
794
                if ($DB->numrows($result)==1){
795
                        $data=$DB->fetch_assoc($result);
796
                        
797
                        $username=formatUserName($data["ID"],$data["name"],$data["realname"],$data["firstname"],$link);
798
                        if ($link==2){
799
                                $user["name"]=$username;
800
                                $user["link"]=$CFG_GLPI["root_doc"]."/front/user.form.php?ID=".$ID;
801
                                $user["comments"]=$LANG["common"][16].": ".$username."<br>";
802
                                $user["comments"].=$LANG["setup"][18].": ".$data["name"]."<br>";
803
                                if (!empty($data["email"]))
804
                                        $user["comments"].=$LANG["setup"][14].": ".$data["email"]."<br>";
805
                                if (!empty($data["phone"]))
806
                                        $user["comments"].=$LANG["help"][35].": ".$data["phone"]."<br>";
807
                                if (!empty($data["mobile"]))
808
                                        $user["comments"].=$LANG["common"][42].": ".$data["mobile"]."<br>";
809
                                if ($data["location"]>0){
810
                                        $user["comments"].=$LANG["common"][15].": ".getDropdownName("glpi_dropdown_locations",$data["location"])."<br>";
811
                                }
812
                        } else {
813
                                $user=$username;
814
                        }
815
                }
816
        }
817
        return $user;                
818
}
819

    
820
/**
821
 * Verify if a DB table exists
822
 *
823
 *@param $tablename string : Name of the table we want to verify.
824
 *
825
 *@return bool : true if exists, false elseway.
826
 *
827
 **/
828
function TableExists($tablename) {
829

    
830
        global $DB;
831
        // Get a list of tables contained within the database.
832
        $result = $DB->list_tables("%".$tablename."%");
833
        if ($rcount = $DB->numrows($result)){
834
                while ($data=$DB->fetch_row($result)){
835
                        if ($data[0]===$tablename){
836
                                return true;
837
                        }
838
                }
839
        }
840
        $DB->free_result($result);
841
        return false;
842
}
843

    
844
/**
845
 * Verify if a DB field exists
846
 *
847
 *@param $table string : Name of the table we want to verify.
848
 *@param $field string : Name of the field we want to verify.
849
 *
850
 *@return bool : true if exists, false elseway.
851
 *
852
 **/
853
function FieldExists($table, $field) {
854
        global $DB;
855

    
856
        if ($fields = $DB->list_fields($table)){
857

    
858
                if (isset($fields[$field]))
859
                        return true;
860
                else return false;
861
        } else return false;
862
}
863

    
864
/**
865
 * Determine if an index exists in database
866
 *
867
 * @param $table string : table of the index
868
 * @param $field string : name of the index
869
 *
870
 * @return boolean : index exists ?
871
 *
872
 **/
873
function isIndex($table, $field) {
874

    
875
        global $DB;
876
        $result = $DB->query("SHOW INDEX FROM `". $table."`");
877
        if ($result&&$DB->numrows($result)){
878
                while ($data=$DB->fetch_assoc($result))
879
                        if ($data["Key_name"]==$field){
880
                                //                        echo $table.".".$field."-> INDEX<br>";
881
                                return true;
882
                        }
883
        }
884
        //echo $table.".".$field."-> NOT INDEX<br>";
885
        return false;                
886
}
887

    
888

    
889
/**
890
 * Export an array to be stored in a simple field in the database
891
 *
892
 * @param $TAB Array to export / encode (one level depth)
893
 *
894
 * @return string containing encoded array
895
 *
896
 **/
897
function exportArrayToDB($TAB) {
898
        $EXPORT = "";
899
        while (list($KEY,$VALUE) = each($TAB)) {
900
                $EXPORT .= urlencode($KEY)."=>".(is_array($VALUE)?" ".exportArrayToDB($VALUE):urlencode($VALUE))." ";
901
        }
902
        return $EXPORT;
903
}
904

    
905
/**
906
 * Import an array encoded in a simple field in the database
907
 *
908
 * @param $DATA data readed in DB to import
909
 *
910
 * @return array containing datas
911
 *
912
 **/
913
function importArrayFromDB($DATA) {
914
        $TAB = array();
915

    
916
        foreach(explode(" ", $DATA) as $ITEM) {
917
                $A = explode("=>", $ITEM);
918
                if (strlen($A[0])&&isset($A[1]))
919
                        $TAB[urldecode($A[0])] = urldecode($A[1]);
920
        }
921
        return $TAB;
922
}
923

    
924

    
925
/**
926
 * Create a new name using a autoname field defined in a template
927
 *
928
 * @param $objectName autoname template
929
 * @param $field field to autoname
930
 * @param $isTemplate true if create an object from a template 
931
 * @param $type device type
932
 * @param $FK_entities limit generation to an entity
933
 *
934
 * @return new auto string
935
 *
936
 **/
937
function autoName($objectName, $field, $isTemplate, $type,$FK_entities=-1){
938
        global $LINK_ID_TABLE,$DB,$CFG_GLPI;
939

    
940
        //$objectName = isset($object->fields[$field]) ? $object->fields[$field] : '';
941

    
942
        $len = strlen($objectName);
943
        if($isTemplate && $len > 8 && substr($objectName,0,4) === '&lt;' && substr($objectName,$len - 4,4) === '&gt;') {
944
                $autoNum = substr($objectName, 4, $len - 8);
945
                $mask = '';
946
                if(preg_match( "/\\#{1,10}/", $autoNum, $mask)){
947
                        $global = strpos($autoNum, '\\g') !== false && $type != INFOCOM_TYPE ? 1 : 0;
948
                        $autoNum = str_replace(array('\\y','\\Y','\\m','\\d','_','%','\\g'), array(date('y'),date('Y'),date('m'),date('d'),'\\_','\\%',''), $autoNum);
949
                        $mask = $mask[0];
950
                        $pos = strpos($autoNum, $mask) + 1;
951
                        $len = strlen($mask);
952
                        $like = str_replace('#', '_', $autoNum);
953

    
954
                        if ($global == 1){
955
                                $query = "";
956
                                $first = 1;
957
                                foreach($LINK_ID_TABLE as $t=>$table){
958
                                        if ($t == COMPUTER_TYPE || $t == MONITOR_TYPE  || $t == NETWORKING_TYPE || $t == PERIPHERAL_TYPE || $t == PRINTER_TYPE || $t == PHONE_TYPE){
959
                                                $query .= ($first ? "SELECT " : " UNION SELECT  ")." `$field` AS code
960
                                                        FROM `$table`
961
                                                        WHERE `$field` LIKE '$like'
962
                                                        AND deleted = '0' 
963
                                                        AND is_template = '0'";
964
                                                        if ($CFG_GLPI["autoname_entity"]&&$FK_entities>=0){
965
                                                                $query.=" AND FK_entities = '$FK_entities' ";
966
                                                        }
967
                                                $first = 0;
968
                                        }
969
                                }
970
                                $query = "SELECT CAST(SUBSTRING(code, $pos, $len) AS unsigned) AS no 
971
                                        FROM ($query) AS codes";
972
                        } else        {
973
                                $table = $LINK_ID_TABLE[$type];
974
                                $query = "SELECT CAST(SUBSTRING($field, $pos, $len) AS unsigned) AS no 
975
                                        FROM `$table`
976
                                        WHERE `$field` LIKE '$like' ";
977
                                if ($type != INFOCOM_TYPE){
978
                                        $query .= " AND deleted = '0' AND is_template = '0'";
979
                                        if ($CFG_GLPI["autoname_entity"]&&$FK_entities>=0){
980
                                                $query.=" AND FK_entities = '$FK_entities' ";
981
                                        }
982
                                }
983

    
984
                        }
985

    
986
                        $query = "SELECT MAX(Num.no) AS lastNo 
987
                                FROM (".$query.") AS Num";
988
                        $resultNo = $DB->query($query);
989

    
990
                        if ($DB->numrows($resultNo)>0) {
991
                                $data = $DB->fetch_array($resultNo);
992
                                $newNo = $data['lastNo'] + 1;
993
                        } else        $newNo = 0;
994
                        $objectName = str_replace(array($mask,'\\_','\\%'), array(str_pad($newNo, $len, '0', STR_PAD_LEFT),'_','%'), $autoNum);
995
                }
996
        }
997
        return $objectName;
998
}
999

    
1000
/**
1001
 * Close active DB connections
1002
 *
1003
 *@return nothing
1004
 *
1005
 **/
1006
function closeDBConnections(){
1007
        global $DB, $DBocs;
1008

    
1009
        // Case of not init $DB object
1010
        if (method_exists($DB,"close")){
1011
                $DB->close();
1012
                if (isset($DBocs)&&method_exists($DBocs,"close")){
1013
                        $DBocs->close();
1014
                }
1015
        }
1016
}
1017

    
1018
// Check if the user have an email 
1019
/* // NOT_USED
1020
function checkEmailForUser($ID){
1021
        global $DB;
1022
        $query="SELECT email FROM glpi_users WHERE ID='$ID'";
1023
        $result=$DB->query($query);
1024
        if ($DB->numrows($result)==1){
1025
                return isValidEmail($DB->result($result,0,0));
1026
        }
1027
        return false;
1028
}
1029
*/
1030

    
1031
/**
1032
 * Format a web link adding http:// if missing
1033
 *
1034
 *@param $link link to format
1035
 *
1036
 *@return formatted link.
1037
 *
1038
 **/
1039
function formatOutputWebLink($link){
1040
        if (!ereg("^https?",$link)){
1041
                return "http://".$link;
1042
        } 
1043
        return $link;
1044
}
1045

    
1046
?>
Redmine Appliance - Powered by TurnKey Linux