r1387 + fixed typo
[racktables] / inc / database.php
CommitLineData
b325120a 1<?php
e673ee24
DO
2/*
3*
4* This file is a library of database access functions for RackTables.
5*
6*/
7
8function escapeString ($value)
9{
10 global $dbxlink;
11 return substr ($dbxlink->quote (htmlentities ($value)), 1, -1);
12}
13
14// This function returns detailed information about either all or one
15// rack row depending on its argument.
16function getRackRowInfo ($rackrow_id = 0)
17{
18 global $dbxlink;
19 $query =
5332840f
DO
20 "select dict_key, dict_value, count(Rack.id) as count, " .
21 "if(isnull(sum(Rack.height)),0,sum(Rack.height)) as sum " .
22 "from Chapter natural join Dictionary left join Rack on Rack.row_id = dict_key " .
e673ee24
DO
23 "where chapter_name = 'RackRow' " .
24 ($rackrow_id > 0 ? "and dict_key = ${rackrow_id} " : '') .
25 "group by dict_key order by dict_value";
26 $result = $dbxlink->query ($query);
27 if ($result == NULL)
28 {
29 showError ('SQL query failed in getRackRowInfo()');
30 return NULL;
31 }
32 $ret = array();
33 $clist = array ('dict_key', 'dict_value', 'count', 'sum');
34 while ($row = $result->fetch (PDO::FETCH_ASSOC))
35 foreach ($clist as $dummy => $cname)
36 $ret[$row['dict_key']][$cname] = $row[$cname];
37 $result->closeCursor();
38 if ($rackrow_id > 0)
39 return current ($ret);
40 else
41 return $ret;
42}
43
44// This function returns id->name map for all object types. The map is used
45// to build <select> input for objects.
46function getObjectTypeList ()
47{
48 return readChapter ('RackObjectType');
49}
50
51function getObjectList ($type_id = 0)
52{
53 global $dbxlink;
54 $query =
55 "select distinct RackObject.id as id , RackObject.name as name, dict_value as objtype_name, " .
56 "RackObject.label as label, RackObject.barcode as barcode, " .
57 "dict_key as objtype_id, asset_no, rack_id, Rack.name as Rack_name from " .
58 "((RackObject inner join Dictionary on objtype_id=dict_key natural join Chapter) " .
59 "left join RackSpace on RackObject.id = object_id) " .
60 "left join Rack on rack_id = Rack.id " .
61 "where objtype_id = '${type_id}' and RackObject.deleted = 'no' " .
62 "and chapter_name = 'RackObjectType' order by name";
63 $result = $dbxlink->query ($query);
64 if ($result == NULL)
65 {
66 showError ('SQL query failed in getObjectList()');
67 return;
68 }
69 $ret = array();
70 $clist = array ('id', 'name', 'label', 'barcode', 'objtype_name', 'objtype_id', 'asset_no', 'rack_id', 'Rack_name');
71 while ($row = $result->fetch (PDO::FETCH_ASSOC))
72 {
73 foreach ($clist as $dummy => $cname)
74 $ret[$row['id']][$cname] = $row[$cname];
75 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
76 }
77 $result->closeCursor();
78 return $ret;
79}
80
81function getRacksForRow ($row_id = 0)
82{
83 global $dbxlink;
84 $query =
6a3a37b2 85 "select Rack.id, Rack.name, height, Rack.comment, row_id, dict_value as row_name " .
e673ee24
DO
86 "from Rack left join Dictionary on row_id = dict_key natural join Chapter " .
87 "where chapter_name = 'RackRow' and Rack.deleted = 'no' " .
88 (($row_id == 0) ? "" : "and row_id = ${row_id} ") .
89 "order by row_name, Rack.id";
90 $result = $dbxlink->query ($query);
91 if ($result == NULL)
92 {
93 showError ('SQL query failed in getRacksForRow()');
94 return;
95 }
96 $ret = array();
97 $clist = array ('id', 'name', 'height', 'comment', 'row_id', 'row_name');
98 while ($row = $result->fetch (PDO::FETCH_ASSOC))
99 foreach ($clist as $dummy => $cname)
100 $ret[$row['id']][$cname] = $row[$cname];
101 $result->closeCursor();
6a3a37b2 102 usort ($ret, 'sortRacks');
e673ee24
DO
103 $ret = restoreRackIDs ($ret);
104 return $ret;
105}
106
107// This is a popular helper for getting information about
108// a particular rack and its rackspace at once.
109function getRackData ($rack_id = 0, $silent = FALSE)
110{
111 if ($rack_id == 0)
112 {
113 if ($silent == FALSE)
114 showError ('Invalid rack_id in getRackData()');
115 return NULL;
116 }
117 global $dbxlink;
118 $query =
119 "select Rack.id, Rack.name, row_id, height, Rack.comment, dict_value as row_name from " .
120 "Rack left join Dictionary on Rack.row_id = dict_key natural join Chapter " .
121 "where chapter_name = 'RackRow' and Rack.id='${rack_id}' and Rack.deleted = 'no' limit 1";
122 $result1 = $dbxlink->query ($query);
123 if ($result1 == NULL)
124 {
125 if ($silent == FALSE)
126 showError ("SQL query #1 failed in getRackData()");
127 return NULL;
128 }
129 if (($row = $result1->fetch (PDO::FETCH_ASSOC)) == NULL)
130 {
131 if ($silent == FALSE)
132 showError ('Query #1 succeded, but returned no data in getRackData()');
133 return NULL;
134 }
135
136 // load metadata
137 $rack['id'] = $row['id'];
138 $rack['name'] = $row['name'];
139 $rack['height'] = $row['height'];
140 $rack['comment'] = $row['comment'];
141 $rack['row_id'] = $row['row_id'];
142 $rack['row_name'] = $row['row_name'];
143 $result1->closeCursor();
144
145 // start with default rackspace
146 for ($i = $rack['height']; $i > 0; $i--)
147 for ($locidx = 0; $locidx < 3; $locidx++)
148 $rack[$i][$locidx]['state'] = 'F';
149
150 // load difference
151 $query =
152 "select unit_no, atom, state, object_id " .
153 "from RackSpace where rack_id = ${rack_id} and " .
154 "unit_no between 1 and " . $rack['height'] . " order by unit_no";
155 $result2 = $dbxlink->query ($query);
156 if ($result2 == NULL)
157 {
158 if ($silent == FALSE)
159 showError ('SQL query failure #2 in getRackData()');
160 return NULL;
161 }
162 global $loclist;
163 while ($row = $result2->fetch (PDO::FETCH_ASSOC))
164 {
165 $rack[$row['unit_no']][$loclist[$row['atom']]]['state'] = $row['state'];
166 $rack[$row['unit_no']][$loclist[$row['atom']]]['object_id'] = $row['object_id'];
167 }
168 $result2->closeCursor();
169 return $rack;
170}
171
172// This is a popular helper.
173function getObjectInfo ($object_id = 0)
174{
175 if ($object_id == 0)
176 {
177 showError ('Invalid object_id in getObjectInfo()');
178 return;
179 }
180 global $dbxlink;
181 $query =
182 "select id, name, label, barcode, dict_value as objtype_name, asset_no, dict_key as objtype_id, has_problems, comment from " .
183 "RackObject inner join Dictionary on objtype_id = dict_key natural join Chapter " .
184 "where id = '${object_id}' and deleted = 'no' and chapter_name = 'RackObjectType' limit 1";
185 $result = $dbxlink->query ($query);
186 if ($result == NULL)
187 {
c461c579
DO
188 $ei = $dbxlink->errorInfo();
189 showError ("SQL query failed in getObjectInfo (${object_id}) with error ${ei[1]} (${ei[2]})");
e673ee24
DO
190 return NULL;
191 }
192 if (($row = $result->fetch (PDO::FETCH_ASSOC)) == NULL)
193 {
194 showError ('Query succeded, but returned no data in getObjectInfo()');
195 $ret = NULL;
196 }
197 else
198 {
199 $ret['id'] = $row['id'];
200 $ret['name'] = $row['name'];
201 $ret['label'] = $row['label'];
202 $ret['barcode'] = $row['barcode'];
203 $ret['objtype_name'] = $row['objtype_name'];
204 $ret['objtype_id'] = $row['objtype_id'];
205 $ret['has_problems'] = $row['has_problems'];
206 $ret['asset_no'] = $row['asset_no'];
207 $ret['dname'] = displayedName ($ret);
208 $ret['comment'] = $row['comment'];
209 }
210 $result->closeCursor();
211 return $ret;
212}
213
214function getPortTypes ()
215{
fe6e3bd7 216 return readChapter ('PortType');
e673ee24
DO
217}
218
219function getObjectPortsAndLinks ($object_id = 0)
220{
221 if ($object_id == 0)
222 {
223 showError ('Invalid object_id in getObjectPorts()');
224 return;
225 }
226 global $dbxlink;
227 $query =
228 "select Port.id as Port_id, ".
229 "Port.name as Port_name, ".
230 "Port.label as Port_label, ".
231 "Port.l2address as Port_l2address, ".
232 "Port.type as Port_type, ".
233 "Port.reservation_comment as Port_reservation_comment, " .
234 "dict_value as PortType_name, ".
235 "RemotePort.id as RemotePort_id, ".
236 "RemotePort.name as RemotePort_name, ".
237 "RemotePort.object_id as RemotePort_object_id, ".
238 "RackObject.name as RackObject_name ".
239 "from (".
240 "(".
241 "(".
242 "Port inner join Dictionary on Port.type = dict_key natural join Chapter".
243 ") ".
244 "left join Link on Port.id=Link.porta or Port.id=Link.portb ".
245 ") ".
246 "left join Port as RemotePort on Link.portb=RemotePort.id or Link.porta=RemotePort.id ".
247 ") ".
248 "left join RackObject on RemotePort.object_id=RackObject.id ".
249 "where chapter_name = 'PortType' and Port.object_id=${object_id} ".
250 "and (Port.id != RemotePort.id or RemotePort.id is null) ".
251 "order by Port_name";
252 $result = $dbxlink->query ($query);
253 if ($result == NULL)
254 {
255 return NULL;
256 }
257 else
258 {
259 $ret=array();
260 $count=0;
261 while ($row = $result->fetch (PDO::FETCH_ASSOC))
262 {
263 $ret[$count]['id'] = $row['Port_id'];
264 $ret[$count]['name'] = $row['Port_name'];
265 $ret[$count]['l2address'] = l2addressFromDatabase ($row['Port_l2address']);
266 $ret[$count]['label'] = $row['Port_label'];
267 $ret[$count]['type_id'] = $row['Port_type'];
268 $ret[$count]['type'] = $row['PortType_name'];
269 $ret[$count]['reservation_comment'] = $row['Port_reservation_comment'];
270 $ret[$count]['remote_id'] = $row['RemotePort_id'];
271 $ret[$count]['remote_name'] = htmlentities ($row['RemotePort_name'], ENT_QUOTES);
272 $ret[$count]['remote_object_id'] = $row['RemotePort_object_id'];
273 $ret[$count]['remote_object_name'] = $row['RackObject_name'];
db389b79
DO
274 // Save on displayedName() calls.
275 if (empty ($row['RackObject_name']) and !empty ($row['RemotePort_object_id']))
276 {
277 $oi = getObjectInfo ($row['RemotePort_object_id']);
278 $ret[$count]['remote_object_name'] = displayedName ($oi);
279 }
e673ee24
DO
280 $count++;
281 }
282 }
283 $result->closeCursor();
284 return $ret;
285}
286
287function commitAddRack ($name, $height, $row_id, $comment)
288{
289 global $dbxlink;
290 $query = "insert into Rack(row_id, name, height, comment) values('${row_id}', '${name}', '${height}', '${comment}')";
291 $result1 = $dbxlink->query ($query);
292 if ($result1 == NULL)
293 {
294 showError ('SQL query failed in commitAddRack()');
295 return FALSE;
296 }
297 // last_insert_id() is MySQL-specific
298 $query = 'select last_insert_id()';
299 $result2 = $dbxlink->query ($query);
300 if ($result2 == NULL)
301 {
302 showError ('Cannot get last ID in commitAddRack()');
303 return FALSE;
304 }
305 // we always have a row
306 $row = $result2->fetch (PDO::FETCH_NUM);
307 $last_insert_id = $row[0];
308 $result2->closeCursor();
309 return recordHistory ('Rack', "id = ${last_insert_id}");
310}
311
312function commitAddObject ($new_name, $new_label, $new_barcode, $new_type_id, $new_asset_no)
313{
314 global $dbxlink;
315 // Maintain UNIQUE INDEX for common names and asset tags.
316 $new_asset_no = empty ($new_asset_no) ? 'NULL' : "'${new_asset_no}'";
317 $new_barcode = empty ($new_barcode) ? 'NULL' : "'${new_barcode}'";
318 $new_name = empty ($new_name) ? 'NULL' : "'${new_name}'";
319 $query =
320 "insert into RackObject(name, label, barcode, objtype_id, asset_no) " .
321 "values(${new_name}, '${new_label}', ${new_barcode}, '${new_type_id}', ${new_asset_no})";
322 $result1 = $dbxlink->query ($query);
323 if ($result1 == NULL)
324 {
325 $errorInfo = $dbxlink->errorInfo();
326 showError ("SQL query '${query}' failed in commitAddObject(): " . $errorInfo[2]);
327 die;
328 }
329 if ($result1->rowCount() != 1)
330 {
331 showError ('Adding new object failed in commitAddObject()');
332 return FALSE;
333 }
334 $query = 'select last_insert_id()';
335 $result2 = $dbxlink->query ($query);
336 if ($result2 == NULL)
337 {
338 $errorInfo = $dbxlink->errorInfo();
339 showError ("SQL query '${query}' failed in commitAddObject(): " . $errorInfo[2]);
340 die;
341 }
342 // we always have a row
343 $row = $result2->fetch (PDO::FETCH_NUM);
344 $last_insert_id = $row[0];
345 $result2->closeCursor();
346 return recordHistory ('RackObject', "id = ${last_insert_id}");
347}
348
349function commitUpdateObject ($object_id = 0, $new_name = '', $new_label = '', $new_barcode = '', $new_type_id = 0, $new_has_problems = 'no', $new_asset_no = '', $new_comment = '')
350{
351 if ($object_id == 0 || $new_type_id == 0)
352 {
353 showError ('Not all required args to commitUpdateObject() are present.');
354 return FALSE;
355 }
356 global $dbxlink;
357 $new_asset_no = empty ($new_asset_no) ? 'NULL' : "'${new_asset_no}'";
358 $new_barcode = empty ($new_barcode) ? 'NULL' : "'${new_barcode}'";
359 $new_name = empty ($new_name) ? 'NULL' : "'${new_name}'";
360 $query = "update RackObject set name=${new_name}, label='${new_label}', barcode=${new_barcode}, objtype_id='${new_type_id}', " .
361 "has_problems='${new_has_problems}', asset_no=${new_asset_no}, comment='${new_comment}' " .
362 "where id='${object_id}' limit 1";
363 $result = $dbxlink->query ($query);
364 if ($result == NULL)
365 {
366 showError ("SQL query '${query}' failed in commitUpdateObject");
367 return FALSE;
368 }
369 if ($result->rowCount() != 1)
370 {
371 showError ('Error updating object information in commitUpdateObject()');
372 return FALSE;
373 }
374 $result->closeCursor();
375 return recordHistory ('RackObject', "id = ${object_id}");
376}
377
378function commitUpdateRack ($rack_id, $new_name, $new_height, $new_row_id, $new_comment)
379{
380 if (empty ($rack_id) || empty ($new_name) || empty ($new_height))
381 {
382 showError ('Not all required args to commitUpdateRack() are present.');
383 return FALSE;
384 }
385 global $dbxlink;
386 $query = "update Rack set name='${new_name}', height='${new_height}', comment='${new_comment}', row_id=${new_row_id} " .
387 "where id='${rack_id}' limit 1";
388 $result1 = $dbxlink->query ($query);
389 if ($result1->rowCount() != 1)
390 {
391 showError ('Error updating rack information in commitUpdateRack()');
392 return FALSE;
393 }
394 return recordHistory ('Rack', "id = ${rack_id}");
395}
396
397// This function accepts rack data returned by getRackData(), validates and applies changes
398// supplied in $_REQUEST and returns resulting array. Only those changes are examined, which
399// correspond to current rack ID.
400// 1st arg is rackdata, 2nd arg is unchecked state, 3rd arg is checked state.
401// If 4th arg is present, object_id fields will be updated accordingly to the new state.
402// The function returns the modified rack upon success.
403function processGridForm (&$rackData, $unchecked_state, $checked_state, $object_id = 0)
404{
405 global $loclist, $dbxlink;
406 $rack_id = $rackData['id'];
407 $rack_name = $rackData['name'];
408 $rackchanged = FALSE;
409 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
410 {
411 for ($locidx = 0; $locidx < 3; $locidx++)
412 {
413 if ($rackData[$unit_no][$locidx]['enabled'] != TRUE)
414 continue;
415 // detect a change
416 $state = $rackData[$unit_no][$locidx]['state'];
417 if (isset ($_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"]) and $_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"] == 'on')
418 $newstate = $checked_state;
419 else
420 $newstate = $unchecked_state;
421 if ($state == $newstate)
422 continue;
423 $rackchanged = TRUE;
424 // and validate
425 $atom = $loclist[$locidx];
426 // The only changes allowed are those introduced by checkbox grid.
427 if
428 (
429 !($state == $checked_state && $newstate == $unchecked_state) &&
430 !($state == $unchecked_state && $newstate == $checked_state)
431 )
432 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, 'atom ${atom}', cannot change state from '${state}' to '${newstate}'");
433 // Here we avoid using ON DUPLICATE KEY UPDATE by first performing DELETE
434 // anyway and then looking for probable need of INSERT.
435 $query =
436 "delete from RackSpace where rack_id = ${rack_id} and " .
437 "unit_no = ${unit_no} and atom = '${atom}' limit 1";
438 $r = $dbxlink->query ($query);
439 if ($r == NULL)
440 return array ('code' => 500, 'message' => "${rack_name}: SQL DELETE query failed in processGridForm()");
441 if ($newstate != 'F')
442 {
443 $query =
444 "insert into RackSpace(rack_id, unit_no, atom, state) " .
445 "values(${rack_id}, ${unit_no}, '${atom}', '${newstate}') ";
446 $r = $dbxlink->query ($query);
447 if ($r == NULL)
448 return array ('code' => 500, 'message' => "${rack_name}: SQL INSERT query failed in processGridForm()");
449 }
450 if ($newstate == 'T' and $object_id != 0)
451 {
452 // At this point we already have a record in RackSpace.
453 $query =
454 "update RackSpace set object_id=${object_id} " .
455 "where rack_id=${rack_id} and unit_no=${unit_no} and atom='${atom}' limit 1";
456 $r = $dbxlink->query ($query);
457 if ($r->rowCount() == 1)
458 $rackData[$unit_no][$locidx]['object_id'] = $object_id;
459 else
460 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, atom '${atom}' failed to set object_id to '${object_id}'");
461 }
462 }
463 }
464 if ($rackchanged)
465 return array ('code' => 200, 'message' => "${rack_name}: All changes were successfully saved.");
466 else
467 return array ('code' => 300, 'message' => "${rack_name}: No changes.");
468}
469
470// This function builds a list of rack-unit-atom records, which are assigned to
471// the requested object.
472function getMoleculeForObject ($object_id = 0)
473{
474 if ($object_id == 0)
475 {
476 showError ("object_id == 0 in getMoleculeForObject()");
477 return NULL;
478 }
479 global $dbxlink;
480 $query =
481 "select rack_id, unit_no, atom from RackSpace " .
482 "where state = 'T' and object_id = ${object_id} order by rack_id, unit_no, atom";
483 $result = $dbxlink->query ($query);
484 if ($result == NULL)
485 {
486 showError ("SQL query failed in getMoleculeForObject()");
487 return NULL;
488 }
489 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
490 $result->closeCursor();
491 return $ret;
492}
493
494// This function builds a list of rack-unit-atom records for requested molecule.
495function getMolecule ($mid = 0)
496{
497 if ($mid == 0)
498 {
499 showError ("mid == 0 in getMolecule()");
500 return NULL;
501 }
502 global $dbxlink;
503 $query =
504 "select rack_id, unit_no, atom from Atom " .
505 "where molecule_id=${mid}";
506 $result = $dbxlink->query ($query);
507 if ($result == NULL)
508 {
509 showError ("SQL query failed in getMolecule()");
510 return NULL;
511 }
512 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
513 $result->closeCursor();
514 return $ret;
515}
516
517// This function creates a new record in Molecule and number of linked
518// R-U-A records in Atom.
519function createMolecule ($molData)
520{
521 global $dbxlink;
522 $query = "insert into Molecule values()";
523 $result1 = $dbxlink->query ($query);
524 if ($result1->rowCount() != 1)
525 {
526 showError ('Error inserting into Molecule in createMolecule()');
527 return NULL;
528 }
529 $query = 'select last_insert_id()';
530 $result2 = $dbxlink->query ($query);
531 if ($result2 == NULL)
532 {
533 showError ('Cannot get last ID in createMolecule().');
534 return NULL;
535 }
536 $row = $result2->fetch (PDO::FETCH_NUM);
537 $molecule_id = $row[0];
538 $result2->closeCursor();
539 foreach ($molData as $dummy => $rua)
540 {
541 $rack_id = $rua['rack_id'];
542 $unit_no = $rua['unit_no'];
543 $atom = $rua['atom'];
544 $query =
545 "insert into Atom(molecule_id, rack_id, unit_no, atom) " .
546 "values (${molecule_id}, ${rack_id}, ${unit_no}, '${atom}')";
547 $result3 = $dbxlink->query ($query);
548 if ($result3 == NULL or $result3->rowCount() != 1)
549 {
550 showError ('Error inserting into Atom in createMolecule()');
551 return NULL;
552 }
553 }
554 return $molecule_id;
555}
556
557// History logger. This function assumes certain table naming convention and
558// column design:
559// 1. History table name equals to dictionary table name plus 'History'.
560// 2. History table must have the same row set (w/o keys) plus one row named
561// 'ctime' of type 'timestamp'.
562function recordHistory ($tableName, $whereClause)
563{
564 global $dbxlink, $remote_username;
565 $query = "insert into ${tableName}History select *, current_timestamp(), '${remote_username}' from ${tableName} where ${whereClause}";
566 $result = $dbxlink->query ($query);
567 if ($result == NULL or $result->rowCount() != 1)
568 {
569 showError ("SQL query failed in recordHistory() for table ${tableName}");
570 return FALSE;
571 }
572 return TRUE;
573}
574
575function getRackspaceHistory ()
576{
577 global $dbxlink;
578 $query =
579 "select mo.id as mo_id, ro.id as ro_id, ro.name, mo.ctime, mo.comment, dict_value as objtype_name, user_name from " .
580 "MountOperation as mo inner join RackObject as ro on mo.object_id = ro.id " .
581 "inner join Dictionary on objtype_id = dict_key natural join Chapter " .
582 "where chapter_name = 'RackObjectType' order by ctime desc";
583 $result = $dbxlink->query ($query);
584 if ($result == NULL)
585 {
586 showError ('SQL query failed in getRackspaceHistory()');
587 return;
588 }
589 $ret = $result->fetchAll(PDO::FETCH_ASSOC);
590 $result->closeCursor();
591 return $ret;
592}
593
594// This function is used in renderRackspaceHistory()
595function getOperationMolecules ($op_id = 0)
596{
597 if ($op_id <= 0)
598 {
599 showError ("Missing argument to getOperationMolecules()");
600 return;
601 }
602 global $dbxlink;
603 $query = "select old_molecule_id, new_molecule_id from MountOperation where id = ${op_id}";
604 $result = $dbxlink->query ($query);
605 if ($result == NULL)
606 {
607 showError ("SQL query failed in getOperationMolecules()");
608 return;
609 }
610 // We expect one row.
611 $row = $result->fetch (PDO::FETCH_ASSOC);
612 if ($row == NULL)
613 {
614 showError ("SQL query succeded, but returned no results in getOperationMolecules().");
615 return;
616 }
617 $omid = $row['old_molecule_id'];
618 $nmid = $row['new_molecule_id'];
619 $result->closeCursor();
620 return array ($omid, $nmid);
621}
622
623function getResidentRacksData ($object_id = 0)
624{
625 if ($object_id <= 0)
626 {
627 showError ('Invalid object_id in getResidentRacksData()');
628 return;
629 }
630 $query = "select distinct rack_id from RackSpace where object_id = ${object_id} order by rack_id";
631 global $dbxlink;
632 $result = $dbxlink->query ($query);
633 if ($result == NULL)
634 {
635 showError ("SQL query failed in getResidentRacksData()");
636 return;
637 }
638 $rows = $result->fetchAll (PDO::FETCH_NUM);
639 $result->closeCursor();
640 $ret = array();
641 foreach ($rows as $row)
642 {
643 $rackData = getRackData ($row[0]);
644 if ($rackData == NULL)
645 {
646 showError ('getRackData() failed in getResidentRacksData()');
647 return NULL;
648 }
649 $ret[$row[0]] = $rackData;
650 }
651 $result->closeCursor();
652 return $ret;
653}
654
655function getObjectGroupInfo ($group_id = 0)
656{
657 $query =
658 'select dict_key as id, dict_value as name, count(id) as count from ' .
659 'Dictionary natural join Chapter left join RackObject on dict_key = objtype_id ' .
660 'where chapter_name = "RackObjectType" ' .
661 (($group_id > 0) ? "and dict_key = ${group_id} " : '') .
662 'group by dict_key';
663 global $dbxlink;
664 $result = $dbxlink->query ($query);
665 if ($result == NULL)
666 {
667 showError ('SQL query failed in getObjectGroupSummary');
668 return NULL;
669 }
670 $ret = array();
671 $clist = array ('id', 'name', 'count');
672 while ($row = $result->fetch (PDO::FETCH_ASSOC))
673 foreach ($clist as $dummy => $cname)
674 $ret[$row['id']][$cname] = $row[$cname];
675 $result->closeCursor();
676 if ($group_id > 0)
677 return current ($ret);
678 else
679 return $ret;
680}
681
682// This function returns objects, which have no rackspace assigned to them.
683// Additionally it keeps rack_id parameter, so we can silently pre-select
684// the rack required.
685function getUnmountedObjects ()
686{
687 global $dbxlink;
688 $query =
689 'select dict_value as objtype_name, dict_key as objtype_id, name, label, barcode, id, asset_no from ' .
690 'RackObject inner join Dictionary on objtype_id = dict_key natural join Chapter ' .
691 'left join RackSpace on id = object_id '.
068ffc0c 692 'where rack_id is null and chapter_name = "RackObjectType" order by dict_value, name, label, asset_no, barcode';
e673ee24
DO
693 $result = $dbxlink->query ($query);
694 if ($result == NULL)
695 {
696 showError ('SQL query failure in getUnmountedObjects()');
697 return NULL;
698 }
699 $ret = array();
700 $clist = array ('id', 'name', 'label', 'barcode', 'objtype_name', 'objtype_id', 'asset_no');
701 while ($row = $result->fetch (PDO::FETCH_ASSOC))
702 {
703 foreach ($clist as $dummy => $cname)
704 $ret[$row['id']][$cname] = $row[$cname];
705 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
706 }
707 $result->closeCursor();
708 return $ret;
709}
710
711function getProblematicObjects ()
712{
713 global $dbxlink;
714 $query =
715 'select dict_value as objtype_name, dict_key as objtype_id, name, id, asset_no from ' .
716 'RackObject inner join Dictionary on objtype_id = dict_key natural join Chapter '.
717 'where has_problems = "yes" and chapter_name = "RackObjectType" order by objtype_name, name';
718 $result = $dbxlink->query ($query);
719 if ($result == NULL)
720 {
721 showError ('SQL query failure in getProblematicObjects()');
722 return NULL;
723 }
724 $ret = array();
725 $clist = array ('id', 'name', 'objtype_name', 'objtype_id', 'asset_no');
726 while ($row = $result->fetch (PDO::FETCH_ASSOC))
727 {
728 foreach ($clist as $dummy => $cname)
729 $ret[$row['id']][$cname] = $row[$cname];
730 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
731 }
732 $result->closeCursor();
733 return $ret;
734}
735
736function commitAddPort ($object_id = 0, $port_name, $port_type_id, $port_label, $port_l2address)
737{
738 if ($object_id <= 0)
739 {
740 showError ('Invalid object_id in commitAddPort()');
741 return;
742 }
743 $port_l2address = l2addressForDatabase ($port_l2address);
744 $result = useInsertBlade
745 (
746 'Port',
747 array
748 (
749 'name' => "'${port_name}'",
750 'object_id' => "'${object_id}'",
751 'label' => "'${port_label}'",
752 'type' => "'${port_type_id}'",
753 'l2address' => "${port_l2address}"
754 )
755 );
756 if ($result)
757 return '';
758 else
759 return 'SQL query failed';
760}
761
762function commitUpdatePort ($port_id, $port_name, $port_label, $port_l2address, $port_reservation_comment)
763{
764 global $dbxlink;
765 $port_l2address = l2addressForDatabase ($port_l2address);
766 $query =
767 "update Port set name='$port_name', label='$port_label', " .
768 "reservation_comment = ${port_reservation_comment}, l2address=${port_l2address} " .
769 "where id='$port_id'";
770 $result = $dbxlink->exec ($query);
771 if ($result == 1)
772 return '';
773 $errorInfo = $dbxlink->errorInfo();
774 // We could update nothing.
775 if ($errorInfo[0] == '00000')
776 return '';
777 return $errorInfo[2];
778}
779
780function delObjectPort ($port_id)
781{
782 if (unlinkPort ($port_id) != '')
783 return 'unlinkPort() failed in delObjectPort()';
784 if (useDeleteBlade ('Port', 'id', $port_id) != TRUE)
785 return 'useDeleteBlade() failed in delObjectPort()';
786 return '';
787}
788
789function getObjectAddressesAndNames ()
790{
791 global $dbxlink;
792 $query =
793 "select object_id as object_id, ".
794 "RackObject.name as object_name, ".
795 "IPBonds.name as name, ".
796 "INET_NTOA(ip) as ip ".
797 "from IPBonds join RackObject on id=object_id ";
798 $result = $dbxlink->query ($query);
799 if ($result == NULL)
800 {
07d88c67 801 showError ("SQL query failure in getObjectAddressesAndNames()");
e673ee24
DO
802 return NULL;
803 }
804 $ret = array();
805 $count=0;
806 while ($row = $result->fetch (PDO::FETCH_ASSOC))
807 {
808 $ret[$count]['object_id']=$row['object_id'];
809 $ret[$count]['object_name']=$row['object_name'];
810 $ret[$count]['name']=$row['name'];
811 $ret[$count]['ip']=$row['ip'];
812 $count++;
813 }
814 $result->closeCursor();
815 return $ret;
816}
817
818
819function getEmptyPortsOfType ($type_id)
820{
821 global $dbxlink;
822 $query =
823 "select distinct Port.id as Port_id, ".
824 "Port.object_id as Port_object_id, ".
825 "RackObject.name as Object_name, ".
826 "Port.name as Port_name, ".
827 "Port.type as Port_type_id, ".
828 "dict_value as Port_type_name ".
829 "from ( ".
830 " ( ".
831 " Port inner join Dictionary on Port.type = dict_key natural join Chapter ".
832 " ) ".
833 " join RackObject on Port.object_id = RackObject.id ".
834 ") ".
835 "left join Link on Port.id=Link.porta or Port.id=Link.portb ".
836 "inner join PortCompat on Port.type = PortCompat.type2 ".
837 "where chapter_name = 'PortType' and PortCompat.type1 = '$type_id' and Link.porta is NULL ".
838 "and Port.reservation_comment is null order by Object_name, Port_name";
839 $result = $dbxlink->query ($query);
840 if ($result == NULL)
841 {
842 showError ("SQL query failure in getEmptyPortsOfType($type_id)");
843 return NULL;
844 }
845 $ret = array();
846 $count=0;
847 while ($row = $result->fetch (PDO::FETCH_ASSOC))
848 {
849 $ret[$count]['Port_id']=$row['Port_id'];
850 $ret[$count]['Port_object_id']=$row['Port_object_id'];
851 $ret[$count]['Object_name']=$row['Object_name'];
852 $ret[$count]['Port_name']=$row['Port_name'];
853 $ret[$count]['Port_type_id']=$row['Port_type_id'];
854 $ret[$count]['Port_type_name']=$row['Port_type_name'];
855 $count++;
856 }
857 $result->closeCursor();
858 return $ret;
859}
860
861function linkPorts ($porta, $portb)
862{
863 if ($porta == $portb)
864 return "Ports can't be the same";
865 if ($porta > $portb)
866 {
867 $tmp = $porta;
868 $porta = $portb;
869 $portb = $tmp;
870 }
871 global $dbxlink;
872 $query1 = "insert into Link set porta='${porta}', portb='{$portb}'";
873 $query2 = "update Port set reservation_comment = NULL where id = ${porta} or id = ${portb} limit 2";
874 // FIXME: who cares about the return value?
875 $result = $dbxlink->exec ($query1);
876 $result = $dbxlink->exec ($query2);
877 return '';
878
879}
880
881function unlinkPort ($port)
882{
883 global $dbxlink;
884 $query =
885 "delete from Link where porta='$port' or portb='$port'";
886 $result = $dbxlink->exec ($query);
887 return '';
888
889}
890
4b2bf583
DO
891// FIXME: after falling back to using existing getObjectInfo we don't
892// need that large query. Shrink it some later.
e673ee24
DO
893function getObjectAddresses ($object_id = 0)
894{
895 if ($object_id == 0)
896 {
897 showError ('Invalid object_id in getObjectAddresses()');
898 return;
899 }
900 global $dbxlink;
901 $query =
902 "select ".
903 "IPAddress.name as IPAddress_name, ".
904 "IPAddress.reserved as IPAddress_reserved, ".
905 "IPBonds.name as IPBonds_name, ".
906 "INET_NTOA(IPBonds.ip) as IPBonds_ip, ".
907 "IPBonds.type as IPBonds_type, ".
908 "RemoteBonds.name as RemoteBonds_name, ".
909 "RemoteBonds.type as RemoteBonds_type, ".
910 "RemoteBonds.object_id as RemoteBonds_object_id, ".
911 "RemoteObject.name as RemoteObject_name from IPBonds " .
912 "left join IPBonds as RemoteBonds on IPBonds.ip=RemoteBonds.ip " .
913 "and IPBonds.object_id!=RemoteBonds.object_id " .
914 "left join IPAddress on IPBonds.ip=IPAddress.ip " .
915 "left join RackObject as RemoteObject on RemoteBonds.object_id=RemoteObject.id ".
916 "where ".
917 "IPBonds.object_id = ${object_id} ".
918 "order by IPBonds.ip, RemoteObject.name";
919 $result = $dbxlink->query ($query);
920 if ($result == NULL)
921 {
922 showError ("SQL query failed in getObjectAddresses()");
923 return NULL;
924 }
925 else
926 {
927 $ret=array();
928 $count=0;
929 $refcount=0;
930 $prev_ip = 0;
c461c579
DO
931 // We are going to call getObjectInfo() for some rows,
932 // hence the connector must be unloaded from the
933 // current data.
934 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
935 $result->closeCursor();
936 foreach ($rows as $row)
e673ee24
DO
937 {
938 if ($prev_ip != $row['IPBonds_ip'])
939 {
940 $count++;
941 $refcount=0;
942 $prev_ip = $row['IPBonds_ip'];
943 $ret[$count]['address_name'] = $row['IPAddress_name'];
944 $ret[$count]['address_reserved'] = $row['IPAddress_reserved'];
945 $ret[$count]['ip'] = $row['IPBonds_ip'];
946 $ret[$count]['name'] = $row['IPBonds_name'];
947 $ret[$count]['type'] = $row['IPBonds_type'];
948 $ret[$count]['references'] = array();
949 }
950
951 if ($row['RemoteBonds_type'])
952 {
953 $ret[$count]['references'][$refcount]['type'] = $row['RemoteBonds_type'];
954 $ret[$count]['references'][$refcount]['name'] = $row['RemoteBonds_name'];
955 $ret[$count]['references'][$refcount]['object_id'] = $row['RemoteBonds_object_id'];
c461c579
DO
956 if (empty ($row['RemoteBonds_object_id']))
957 $ret[$count]['references'][$refcount]['object_name'] = $row['RemoteObject_name'];
958 else
959 {
960 $oi = getObjectInfo ($row['RemoteBonds_object_id']);
961 $ret[$count]['references'][$refcount]['object_name'] = displayedName ($oi);
962 }
e673ee24
DO
963 $refcount++;
964 }
965 }
966 }
e673ee24
DO
967 return $ret;
968}
969
970function getAddressspaceList ()
971{
972 global $dbxlink;
973 $query =
974 "select ".
975 "id as IPRanges_id, ".
976 "INET_NTOA(ip) as IPRanges_ip, ".
977 "mask as IPRanges_mask, ".
978 "name as IPRanges_name ".
979 "from IPRanges ".
980 "order by ip";
981 $result = $dbxlink->query ($query);
982 if ($result == NULL)
983 {
984 return NULL;
985 }
986 else
987 {
988 $ret=array();
989 $count=0;
990 while ($row = $result->fetch (PDO::FETCH_ASSOC))
991 {
992 $ret[$count]['id'] = $row['IPRanges_id'];
993 $ret[$count]['ip'] = $row['IPRanges_ip'];
994 $ret[$count]['ip_bin'] = ip2long($row['IPRanges_ip']);
995 $ret[$count]['name'] = $row['IPRanges_name'];
996 $ret[$count]['mask'] = $row['IPRanges_mask'];
997 $ret[$count]['mask_bin'] = binMaskFromDec($row['IPRanges_mask']);
998 $ret[$count]['mask_bin_inv'] = binInvMaskFromDec($row['IPRanges_mask']);
999 $count++;
1000 }
1001 }
1002 $result->closeCursor();
1003 return $ret;
1004
1005}
1006
1007function getRangeByIp ($ip = '', $id = 0)
1008{
1009 global $dbxlink;
1010 if ($id == 0)
1011 $query =
1012 "select ".
1013 "id, INET_NTOA(ip) as ip, mask, name ".
1014 "from IPRanges ";
1015 else
1016 $query =
1017 "select ".
1018 "id, INET_NTOA(ip) as ip, mask, name ".
1019 "from IPRanges where id='$id'";
1020
1021 $result = $dbxlink->query ($query);
1022 if ($result == NULL)
1023 {
1024 return NULL;
1025 }
1026 else
1027 {
1028 $ret=array();
1029 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1030 {
1031 $binmask=binMaskFromDec($row['mask']);
1032 if ((ip2long($ip) & $binmask) == ip2long($row['ip']))
1033 {
1034 $ret['id'] = $row['id'];
1035 $ret['ip'] = $row['ip'];
1036 $ret['ip_bin'] = ip2long($row['ip']);
1037 $ret['name'] = $row['name'];
1038 $ret['mask'] = $row['mask'];
1039 $result->closeCursor();
1040 return $ret;
1041 }
1042 }
1043 }
1044 $result->closeCursor();
1045 return NULL;
1046}
1047
1048function updateRange ($id=0, $name='')
1049{
1050 global $dbxlink;
1051 $query =
1052 "update IPRanges set name='$name' where id='$id'";
1053 $result = $dbxlink->exec ($query);
1054 return '';
1055
1056}
1057
1058// This function is actually used not only to update, but also to create records,
1059// that's why ON DUPLICATE KEY UPDATE was replaced by DELETE-INSERT pair
1060// (MySQL 4.0 workaround).
1061function updateAddress ($ip=0, $name='', $reserved='no')
1062{
1063 // DELETE may safely fail.
1064 $r = useDeleteBlade ('IPAddress', 'ip', "INET_ATON('${ip}')", FALSE);
1065 // INSERT may appear not necessary.
1066 if ($name == '' and $reserved == 'no')
1067 return '';
1068 if (useInsertBlade ('IPAddress', array ('name' => "'${name}'", 'reserved' => "'${reserved}'", 'ip' => "INET_ATON('${ip}')")))
1069 return '';
1070 else
1071 return 'useInsertBlade() failed in updateAddress()';
1072}
1073
399214af 1074// FIXME: This function doesn't wipe relevant records from IPAddress table.
e673ee24
DO
1075function commitDeleteRange ($id = 0)
1076{
1077 if ($id <= 0)
1078 return 'Invalid range ID in commitDeleteRange()';
1079 if (useDeleteBlade ('IPRanges', 'id', $id))
1080 return '';
1081 else
1082 return 'SQL query failed in commitDeleteRange';
1083}
1084
1085function updateBond ($ip='', $object_id=0, $name='', $type='')
1086{
1087 global $dbxlink;
1088
1089 $query =
1090 "update IPBonds set name='$name', type='$type' where ip=INET_ATON('$ip') and object_id='$object_id'";
1091 $result = $dbxlink->exec ($query);
1092 return '';
1093}
1094
1095function unbindIpFromObject ($ip='', $object_id=0)
1096{
1097 global $dbxlink;
1098
1099 $query =
1100 "delete from IPBonds where ip=INET_ATON('$ip') and object_id='$object_id'";
1101 $result = $dbxlink->exec ($query);
1102 return '';
1103}
1104
1105// This function returns either all or one user account. Array key is user name.
1106function getUserAccounts ()
1107{
1108 global $dbxlink;
1109 $query =
1110 'select user_id, user_name, user_password_hash, user_realname, user_enabled ' .
4e9ea83c 1111 'from UserAccount order by user_name';
e673ee24
DO
1112 $result = $dbxlink->query ($query);
1113 if ($result == NULL)
1114 {
1115 showError ('SQL query failed in getUserAccounts()');
1116 return NULL;
1117 }
1118 $ret = array();
1119 $clist = array ('user_id', 'user_name', 'user_realname', 'user_password_hash', 'user_enabled');
1120 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1121 foreach ($clist as $dummy => $cname)
1122 $ret[$row['user_name']][$cname] = $row[$cname];
1123 $result->closeCursor();
1124 return $ret;
1125}
1126
1127// This function returns permission array for all user accounts. Array key is user name.
1128function getUserPermissions ()
1129{
1130 global $dbxlink;
1131 $query =
1132 "select UserPermission.user_id, user_name, page, tab, access from " .
1133 "UserPermission natural left join UserAccount where (user_name is not null) or " .
7bf342fd 1134 "(user_name is null and UserPermission.user_id = 0) order by user_name, page, tab";
e673ee24
DO
1135 $result = $dbxlink->query ($query);
1136 if ($result == NULL)
1137 {
1138 showError ('SQL query failed in getUserPermissions()');
1139 return NULL;
1140 }
1141 $ret = array();
1142 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1143 {
1144 if ($row['user_id'] == 0)
1145 $row['user_name'] = '%';
1146 $ret[$row['user_name']][$row['page']][$row['tab']] = $row['access'];
1147 }
1148 $result->closeCursor();
1149 return $ret;
1150}
1151
1152function searchByl2address ($l2addr)
1153{
1154 global $dbxlink;
1155 $l2addr = l2addressForDatabase ($l2addr);
1156 $query = "select object_id, Port.id as port_id from RackObject as ro inner join Port on ro.id = Port.object_id " .
1157 "where l2address = ${l2addr}";
1158 $result = $dbxlink->query ($query);
1159 if ($result == NULL)
1160 {
1161 showError ('SQL query failed in objectIDbyl2address()');
1162 return NULL;
1163 }
1164 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
1165 $result->closeCursor();
1166 if (count ($rows) == 0) // No results.
1167 return NULL;
1168 if (count ($rows) == 1) // Target found.
1169 return $rows[0];
1170 showError ('More than one results found in objectIDbyl2address(). This is probably a broken unique key.');
1171 return NULL;
1172}
1173
1174// This function returns either port ID or NULL for specified arguments.
1175function getPortID ($object_id, $port_name)
1176{
1177 global $dbxlink;
1178 $query = "select id from Port where object_id=${object_id} and name='${port_name}' limit 2";
1179 $result = $dbxlink->query ($query);
1180 if ($result == NULL)
1181 {
1182 showError ('SQL query failed in getPortID()');
1183 return NULL;
1184 }
1185 $rows = $result->fetchAll (PDO::FETCH_NUM);
1186 if (count ($rows) != 1)
1187 return NULL;
1188 $ret = $rows[0][0];
1189 $result->closeCursor();
1190 return $ret;
1191}
1192
1193function commitCreateUserAccount ($username, $realname, $password)
1194{
1195 return useInsertBlade
1196 (
1197 'UserAccount',
1198 array
1199 (
1200 'user_name' => "'${username}'",
1201 'user_realname' => "'${realname}'",
1202 'user_password_hash' => "'${password}'"
1203 )
1204 );
1205}
1206
1207function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
1208{
1209 global $dbxlink;
1210 $query =
1211 "update UserAccount set user_name = '${new_username}', user_realname = '${new_realname}', " .
1212 "user_password_hash = '${new_password}' where user_id = ${id} limit 1";
1213 $result = $dbxlink->query ($query);
1214 if ($result == NULL)
1215 {
1216 showError ('SQL query failed in commitUpdateUserAccount()');
1217 die;
1218 }
1219 return TRUE;
1220}
1221
1222function commitEnableUserAccount ($id, $new_enabled_value)
1223{
1224 global $dbxlink;
1225 $query =
1226 "update UserAccount set user_enabled = '${new_enabled_value}' " .
1227 "where user_id = ${id} limit 1";
1228 $result = $dbxlink->query ($query);
1229 if ($result == NULL)
1230 {
1231 showError ('SQL query failed in commitEnableUserAccount()');
1232 die;
1233 }
1234 return TRUE;
1235}
1236
1237function commitGrantPermission ($userid, $page, $tab, $value)
1238{
1239 return useInsertBlade
1240 (
1241 'UserPermission',
1242 array
1243 (
1244 'user_id' => $userid,
1245 'page' => "'${page}'",
1246 'tab' => "'${tab}'",
1247 'access' => "'${value}'"
1248 )
1249 );
1250}
1251
1252function commitRevokePermission ($userid, $page, $tab)
1253{
1254 global $dbxlink;
1255 $query =
1256 "delete from UserPermission where user_id = '${userid}' and page = '${page}' " .
1257 "and tab = '$tab' limit 1";
1258 $result = $dbxlink->query ($query);
1259 if ($result == NULL)
1260 {
1261 showError ('SQL query failed in commitRevokePermission()');
1262 die;
1263 }
1264 return TRUE;
1265}
1266
1267// This function returns an array of all port type pairs from PortCompat table.
1268function getPortCompat ()
1269{
1270 global $dbxlink;
1271 $query =
1272 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
1273 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
1274 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
1275 "inner join Chapter as c1 on d1.chapter_no = c1.chapter_no " .
1276 "inner join Chapter as c2 on d2.chapter_no = c2.chapter_no " .
1277 "where c1.chapter_name = 'PortType' and c2.chapter_name = 'PortType'";
1278 $result = $dbxlink->query ($query);
1279 if ($result == NULL)
1280 {
1281 showError ('SQL query failed in getPortCompat()');
1282 return NULL;
1283 }
1284 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
1285 $result->closeCursor();
1286 return $ret;
1287}
1288
1289function removePortCompat ($type1 = 0, $type2 = 0)
1290{
1291 global $dbxlink;
1292 if ($type1 == 0 or $type2 == 0)
1293 {
1294 showError ('Invalid arguments to removePortCompat');
1295 die;
1296 }
1297 $query = "delete from PortCompat where type1 = ${type1} and type2 = ${type2} limit 1";
1298 $result = $dbxlink->query ($query);
1299 if ($result == NULL)
1300 {
1301 showError ('SQL query failed in removePortCompat()');
1302 die;
1303 }
1304 return TRUE;
1305}
1306
1307function addPortCompat ($type1 = 0, $type2 = 0)
1308{
1309 if ($type1 <= 0 or $type2 <= 0)
1310 {
1311 showError ('Invalid arguments to addPortCompat');
1312 die;
1313 }
1314 return useInsertBlade
1315 (
1316 'PortCompat',
1317 array ('type1' => $type1, 'type2' => $type2)
1318 );
1319}
1320
1321// This function returns the dictionary as an array of trees, each tree
1322// representing a single chapter. Each element has 'id', 'name', 'sticky'
1323// and 'word' keys with the latter holding all the words within the chapter.
1324function getDict ()
1325{
1326 global $dbxlink;
1327 $query =
1328 "select chapter_name, Chapter.chapter_no, dict_key, dict_value, sticky from " .
1329 "Chapter natural left join Dictionary order by chapter_name, dict_value";
1330 $result = $dbxlink->query ($query);
1331 if ($result == NULL)
1332 {
1333 showError ('SQL query failed in getDict()');
1334 return NULL;
1335 }
1336 $dict = array();
1337 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1338 {
1339 $chapter_no = $row['chapter_no'];
1340 if (!isset ($dict[$chapter_no]))
1341 {
1342 $dict[$chapter_no]['no'] = $chapter_no;
1343 $dict[$chapter_no]['name'] = $row['chapter_name'];
1344 $dict[$chapter_no]['sticky'] = $row['sticky'] == 'yes' ? TRUE : FALSE;
1345 $dict[$chapter_no]['word'] = array();
1346 }
1347 if ($row['dict_key'] != NULL)
1348 $dict[$chapter_no]['word'][$row['dict_key']] = $row['dict_value'];
1349 }
1350 $result->closeCursor();
1351 return $dict;
1352}
1353
da95280e
DO
1354function getDictStats ()
1355{
1356 $stock_chapters = array (1, 2, 3, 11, 12, 13, 14, 16, 17, 18, 19, 20);
1357 global $dbxlink;
1358 $query =
5aa28abb
DO
1359 "select Chapter.chapter_no, chapter_name, count(dict_key) as wc from " .
1360 "Chapter natural left join Dictionary group by Chapter.chapter_no";
08b4cb24
DO
1361 $result1 = $dbxlink->query ($query);
1362 if ($result1 == NULL)
da95280e 1363 {
08b4cb24 1364 showError ('SQL query #1 failed in getDictStats()');
da95280e
DO
1365 return NULL;
1366 }
1367 $tc = $tw = $uc = $uw = 0;
08b4cb24 1368 while ($row = $result1->fetch (PDO::FETCH_ASSOC))
da95280e
DO
1369 {
1370 $tc++;
1371 $tw += $row['wc'];;
1372 if (in_array ($row['chapter_no'], $stock_chapters))
1373 continue;
1374 $uc++;
1375 $uw += $row['wc'];;
1376 }
08b4cb24
DO
1377 $result1->closeCursor();
1378 $query = "select count(attr_id) as attrc from RackObject as ro left join " .
1379 "AttributeValue as av on ro.id = av.object_id group by ro.id";
1380 $result2 = $dbxlink->query ($query);
1381 if ($result2 == NULL)
1382 {
1383 showError ('SQL query #2 failed in getDictStats()');
1384 return NULL;
1385 }
1386 $to = $ta = $so = 0;
1387 while ($row = $result2->fetch (PDO::FETCH_ASSOC))
1388 {
1389 $to++;
1390 if ($row['attrc'] != 0)
1391 {
1392 $so++;
1393 $ta += $row['attrc'];
1394 }
1395 }
1396 $result2->closeCursor();
da95280e
DO
1397 $ret = array();
1398 $ret['Total chapters in dictionary'] = $tc;
1399 $ret['Total words in dictionary'] = $tw;
1400 $ret['User chapters'] = $uc;
1401 $ret['Words in user chapters'] = $uw;
08b4cb24
DO
1402 $ret['Total objects'] = $to;
1403 $ret['Objects with stickers'] = $so;
1404 $ret['Total stickers attached'] = $ta;
da95280e
DO
1405 return $ret;
1406}
1407
e673ee24
DO
1408function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1409{
1410 if ($chapter_no <= 0 or $dict_key <= 0 or empty ($dict_value))
1411 {
1412 showError ('Invalid args to commitUpdateDictionary()');
1413 die;
1414 }
1415 global $dbxlink;
1416 $query =
1417 "update Dictionary set dict_value = '${dict_value}' where chapter_no=${chapter_no} " .
1418 "and dict_key=${dict_key} limit 1";
1419 $result = $dbxlink->query ($query);
1420 if ($result == NULL)
1421 {
1422 showError ('SQL query failed in commitUpdateDictionary()');
1423 die;
1424 }
1425 return TRUE;
1426}
1427
1428function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1429{
1430 if ($chapter_no <= 0 or empty ($dict_value))
1431 {
1432 showError ('Invalid args to commitSupplementDictionary()');
1433 die;
1434 }
1435 return useInsertBlade
1436 (
1437 'Dictionary',
1438 array ('chapter_no' => $chapter_no, 'dict_value' => "'${dict_value}'")
1439 );
1440}
1441
1442function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1443{
1444 if ($chapter_no <= 0 or $dict_key <= 0)
1445 {
1446 showError ('Invalid args to commitReduceDictionary()');
1447 die;
1448 }
1449 global $dbxlink;
1450 $query =
1451 "delete from Dictionary where chapter_no=${chapter_no} " .
1452 "and dict_key=${dict_key} limit 1";
1453 $result = $dbxlink->query ($query);
1454 if ($result == NULL)
1455 {
1456 showError ('SQL query failed in commitReduceDictionary()');
1457 die;
1458 }
1459 return TRUE;
1460}
1461
1462function commitAddChapter ($chapter_name = '')
1463{
1464 if (empty ($chapter_name))
1465 {
1466 showError ('Invalid args to commitAddChapter()');
1467 die;
1468 }
1469 return useInsertBlade
1470 (
1471 'Chapter',
1472 array ('chapter_name' => "'${chapter_name}'")
1473 );
1474}
1475
1476function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
1477{
1478 if ($chapter_no <= 0 or empty ($chapter_name))
1479 {
1480 showError ('Invalid args to commitUpdateChapter()');
1481 die;
1482 }
1483 global $dbxlink;
1484 $query =
1485 "update Chapter set chapter_name = '${chapter_name}' where chapter_no = ${chapter_no} " .
1486 "and sticky = 'no' limit 1";
1487 $result = $dbxlink->query ($query);
1488 if ($result == NULL)
1489 {
1490 showError ('SQL query failed in commitUpdateChapter()');
1491 die;
1492 }
1493 return TRUE;
1494}
1495
1496function commitDeleteChapter ($chapter_no = 0)
1497{
1498 if ($chapter_no <= 0)
1499 {
1500 showError ('Invalid args to commitDeleteChapter()');
1501 die;
1502 }
1503 global $dbxlink;
1504 $query =
1505 "delete from Chapter where chapter_no = ${chapter_no} and sticky = 'no' limit 1";
1506 $result = $dbxlink->query ($query);
1507 if ($result == NULL)
1508 {
1509 showError ('SQL query failed in commitDeleteChapter()');
1510 die;
1511 }
1512 return TRUE;
1513}
1514
4c330a14
DO
1515// This is a dictionary accessor. We perform link rendering, so the user sees
1516// nice <select> drop-downs.
e673ee24
DO
1517function readChapter ($chapter_name = '')
1518{
1519 if (empty ($chapter_name))
1520 {
1521 showError ('invalid argument to readChapter()');
1522 return NULL;
1523 }
1524 global $dbxlink;
1525 $query =
1526 "select dict_key, dict_value from Dictionary natural join Chapter " .
4aa8609b 1527 "where chapter_name = '${chapter_name}'";
e673ee24
DO
1528 $result = $dbxlink->query ($query);
1529 if ($result == NULL)
1530 {
1531 $errorInfo = $dbxlink->errorInfo();
1532 showError ("SQL query '${query}'\nwith message '${errorInfo[2]}'\nfailed in readChapter('${chapter_name}')");
1533 return NULL;
1534 }
1535 $chapter = array();
1536 while ($row = $result->fetch (PDO::FETCH_ASSOC))
4c330a14 1537 $chapter[$row['dict_key']] = parseWikiLink ($row['dict_value'], 'o');
e673ee24 1538 $result->closeCursor();
4aa8609b
DO
1539 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
1540 asort ($chapter);
e673ee24
DO
1541 return $chapter;
1542}
1543
1544function getAttrMap ()
1545{
1546 global $dbxlink;
1547 $query =
1548 "select a.attr_id, a.attr_type, a.attr_name, am.objtype_id, " .
1549 "d.dict_value as objtype_name, am.chapter_no, c2.chapter_name from " .
1550 "Attribute as a natural left join AttributeMap as am " .
1551 "left join Dictionary as d on am.objtype_id = d.dict_key " .
1552 "left join Chapter as c1 on d.chapter_no = c1.chapter_no " .
1553 "left join Chapter as c2 on am.chapter_no = c2.chapter_no " .
1554 "where c1.chapter_name = 'RackObjectType' or c1.chapter_name is null " .
1555 "order by attr_name";
1556 $result = $dbxlink->query ($query);
1557 if ($result == NULL)
1558 {
1559 $errorInfo = $dbxlink->errorInfo();
1560 showError ("SQL query '${query}'\nwith message '${errorInfo[2]}'\nfailed in getAttrMap()");
1561 return NULL;
1562 }
1563 $ret = array();
1564 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1565 {
1566 $attr_id = $row['attr_id'];
1567 if (!isset ($ret[$attr_id]))
1568 {
1569 $ret[$attr_id]['id'] = $attr_id;
1570 $ret[$attr_id]['type'] = $row['attr_type'];
1571 $ret[$attr_id]['name'] = $row['attr_name'];
1572 $ret[$attr_id]['application'] = array();
1573 }
1574 if ($row['objtype_id'] == '')
1575 continue;
1576 $application['objtype_id'] = $row['objtype_id'];
1577 $application['objtype_name'] = $row['objtype_name'];
1578 if ($row['attr_type'] == 'dict')
1579 {
1580 $application['chapter_no'] = $row['chapter_no'];
1581 $application['chapter_name'] = $row['chapter_name'];
1582 }
1583 $ret[$attr_id]['application'][] = $application;
1584 }
1585 $result->closeCursor();
1586 return $ret;
1587}
1588
1589function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
1590{
1591 if ($attr_id <= 0 or empty ($attr_name))
1592 {
1593 showError ('Invalid args to commitUpdateAttribute()');
1594 die;
1595 }
1596 global $dbxlink;
1597 $query =
1598 "update Attribute set attr_name = '${attr_name}' " .
1599 "where attr_id = ${attr_id} limit 1";
1600 $result = $dbxlink->query ($query);
1601 if ($result == NULL)
1602 {
1603 showError ("SQL query '${query}' failed in commitUpdateAttribute()");
1604 die;
1605 }
1606 return TRUE;
1607}
1608
1609function commitAddAttribute ($attr_name = '', $attr_type = '')
1610{
1611 if (empty ($attr_name))
1612 {
1613 showError ('Invalid args to commitAddAttribute()');
1614 die;
1615 }
1616 switch ($attr_type)
1617 {
1618 case 'uint':
1619 case 'float':
1620 case 'string':
1621 case 'dict':
1622 break;
1623 default:
1624 showError ('Invalid args to commitAddAttribute()');
1625 die;
1626 }
1627 return useInsertBlade
1628 (
1629 'Attribute',
1630 array ('attr_name' => "'${attr_name}'", 'attr_type' => "'${attr_type}'")
1631 );
1632}
1633
1634function commitDeleteAttribute ($attr_id = 0)
1635{
1636 if ($attr_id <= 0)
1637 {
1638 showError ('Invalid args to commitDeleteAttribute()');
1639 die;
1640 }
1641 return useDeleteBlade ('Attribute', 'attr_id', $attr_id);
1642}
1643
1644// FIXME: don't store garbage in chapter_no for non-dictionary types.
1645function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
1646{
1647 if ($attr_id <= 0 or $objtype_id <= 0 or $chapter_no <= 0)
1648 {
1649 showError ('Invalid args to commitSupplementAttrMap()');
1650 die;
1651 }
1652 return useInsertBlade
1653 (
1654 'AttributeMap',
1655 array
1656 (
1657 'attr_id' => $attr_id,
1658 'objtype_id' => $objtype_id,
1659 'chapter_no' => $chapter_no
1660 )
1661 );
1662}
1663
1664function commitReduceAttrMap ($attr_id = 0, $objtype_id)
1665{
1666 if ($attr_id <= 0 or $objtype_id <= 0)
1667 {
1668 showError ('Invalid args to commitReduceAttrMap()');
1669 die;
1670 }
1671 global $dbxlink;
1672 $query =
1673 "delete from AttributeMap where attr_id=${attr_id} " .
1674 "and objtype_id=${objtype_id} limit 1";
1675 $result = $dbxlink->query ($query);
1676 if ($result == NULL)
1677 {
1678 showError ('SQL query failed in commitReduceAttrMap()');
1679 die;
1680 }
1681 return TRUE;
1682}
1683
1684// This function returns all optional attributes for requested object
1685// as an array of records. NULL is returned on error and empty array
1686// is returned, if there are no attributes found.
1687function getAttrValues ($object_id)
1688{
1689 if ($object_id <= 0)
1690 {
1691 showError ('Invalid argument to getAttrValues()');
1692 return NULL;
1693 }
1694 global $dbxlink;
1695 $ret = array();
1696 $query =
1697 "select A.attr_id, A.attr_name, A.attr_type, C.chapter_name, " .
1698 "AV.uint_value, AV.float_value, AV.string_value, D.dict_value from " .
1699 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
1700 "inner join Attribute as A using (attr_id) " .
1701 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
1702 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_no = D.chapter_no " .
1703 "left join Chapter as C on AM.chapter_no = C.chapter_no " .
1704 "where RO.id = ${object_id} order by A.attr_type";
1705 $result = $dbxlink->query ($query);
1706 if ($result == NULL)
1707 {
1708 $errorInfo = $dbxlink->errorInfo();
1709 showError ("SQL query '${query}'\nwith message '${errorInfo[2]}'\nfailed in getAttrValues()");
1710 return NULL;
1711 }
1712 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1713 {
1714 $record = array();
1715 $record['id'] = $row['attr_id'];
1716 $record['name'] = $row['attr_name'];
1717 $record['type'] = $row['attr_type'];
1718 switch ($row['attr_type'])
1719 {
1720 case 'uint':
1721 case 'float':
1722 case 'string':
1723 case 'dict':
50a954f6
DO
1724 $record['value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'o');
1725 $record['a_value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'a');
e673ee24
DO
1726 $record['chapter_name'] = $row['chapter_name'];
1727 $record['key'] = $row['uint_value'];
1728 break;
1729 default:
1730 $record['value'] = NULL;
1731 break;
1732 }
1733 $ret[$row['attr_id']] = $record;
1734 }
1735 $result->closeCursor();
1736 return $ret;
1737}
1738
1739function commitResetAttrValue ($object_id = 0, $attr_id = 0)
1740{
1741 if ($object_id <= 0 or $attr_id <= 0)
1742 {
1743 showError ('Invalid arguments to commitResetAttrValue()');
1744 die;
1745 }
1746 global $dbxlink;
1747 $query = "delete from AttributeValue where object_id = ${object_id} and attr_id = ${attr_id} limit 1";
1748 $result = $dbxlink->query ($query);
1749 if ($result == NULL)
1750 {
1751 showError ('SQL query failed in commitResetAttrValue()');
1752 die;
1753 }
1754 return TRUE;
1755}
1756
1757// FIXME: don't share common code with use commitResetAttrValue()
1758function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
1759{
1760 if ($object_id <= 0 or $attr_id <= 0)
1761 {
1762 showError ('Invalid arguments to commitUpdateAttrValue()');
1763 die;
1764 }
1765 if (empty ($value))
1766 return commitResetAttrValue ($object_id, $attr_id);
1767 global $dbxlink;
1768 $query1 = "select attr_type from Attribute where attr_id = ${attr_id}";
1769 $result = $dbxlink->query ($query1);
1770 if ($result == NULL)
1771 {
1772 showError ('SQL query #1 failed in commitUpdateAttrValue()');
1773 die;
1774 }
1775 $row = $result->fetch (PDO::FETCH_NUM);
1776 if ($row == NULL)
1777 {
1778 showError ('SQL query #1 returned no results in commitUpdateAttrValue()');
1779 die;
1780 }
1781 $attr_type = $row[0];
1782 $result->closeCursor();
1783 switch ($attr_type)
1784 {
1785 case 'uint':
1786 case 'float':
1787 case 'string':
1788 $column = $attr_type . '_value';
1789 break;
1790 case 'dict':
1791 $column = 'uint_value';
1792 break;
1793 default:
1794 showError ("Unknown attribute type '${attr_type}' met in commitUpdateAttrValue()");
1795 die;
1796 }
1797 $query2 =
1798 "delete from AttributeValue where " .
1799 "object_id = ${object_id} and attr_id = ${attr_id} limit 1";
1800 $result = $dbxlink->query ($query2);
1801 if ($result == NULL)
1802 {
1803 showError ('SQL query #2 failed in commitUpdateAttrValue()');
1804 die;
1805 }
1806 // We know $value isn't empty here.
1807 $query3 =
1808 "insert into AttributeValue set ${column} = '${value}', " .
1809 "object_id = ${object_id}, attr_id = ${attr_id} ";
1810 $result = $dbxlink->query ($query3);
1811 if ($result == NULL)
1812 {
1813 showError ('SQL query #3 failed in commitUpdateAttrValue()');
1814 die;
1815 }
1816 return TRUE;
1817}
1818
1819function commitUseupPort ($port_id = 0)
1820{
1821 if ($port_id <= 0)
1822 {
1823 showError ("Invalid argument to commitUseupPort()");
1824 die;
1825 }
1826 global $dbxlink;
1827 $query = "update Port set reservation_comment = NULL where id = ${port_id} limit 1";
1828 $result = $dbxlink->exec ($query);
1829 if ($result == NULL)
1830 {
1831 showError ("SQL query failed in commitUseupPort()");
1832 die;
1833 }
1834 return TRUE;
1835
1836}
1837
1838// This is a swiss-knife blade to insert a record into a table.
1839// The first argument is table name.
1840// The second argument is an array of "name" => "value" pairs.
1841// The function returns either TRUE or FALSE (we expect one row
1842// to be inserted).
1843function useInsertBlade ($tablename, $values)
1844{
1845 global $dbxlink;
1846 $namelist = $valuelist = '';
1847 foreach ($values as $name => $value)
1848 {
1849 $namelist = $namelist . ($namelist == '' ? "(${name}" : ", ${name}");
1850 $valuelist = $valuelist . ($valuelist == '' ? "(${value}" : ", ${value}");
1851 }
1852 $query = "insert into ${tablename} ${namelist}) values ${valuelist})";
1853 $result = $dbxlink->exec ($query);
1854 if ($result != 1)
1855 return FALSE;
1856 return TRUE;
1857}
1858
1859// This swiss-knife blade deletes one record from the specified table
1860// using the specified key name and value.
1861function useDeleteBlade ($tablename, $keyname, $keyvalue, $quotekey = TRUE)
1862{
1863 global $dbxlink;
1864 if ($quotekey == TRUE)
1865 $query = "delete from ${tablename} where ${keyname}='$keyvalue' limit 1";
1866 else
1867 $query = "delete from ${tablename} where ${keyname}=$keyvalue limit 1";
1868 $result = $dbxlink->exec ($query);
1869 if ($result === NULL)
1870 return FALSE;
1871 elseif ($result != 1)
1872 return FALSE;
1873 else
1874 return TRUE;
1875}
1876
9c0b0016
DO
1877function loadConfigCache ()
1878{
1879 global $dbxlink;
4fe32e78 1880 $query = 'SELECT varname, varvalue, vartype, is_hidden, emptyok, description FROM Config ORDER BY varname';
9c0b0016
DO
1881 $result = $dbxlink->query ($query);
1882 if ($result == NULL)
1883 {
1884 $errorInfo = $dbxlink->errorInfo();
4785bafa 1885 showError ("SQL query '${query}'\nwith message '${errorInfo[2]}'\nfailed in loadConfigCache()");
9c0b0016
DO
1886 return NULL;
1887 }
1888 $cache = array();
1889 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1890 $cache[$row['varname']] = $row;
1891 $result->closeCursor();
1892 return $cache;
1893}
1894
1895// setConfigVar() is expected to perform all necessary filtering
1896function storeConfigVar ($varname = NULL, $varvalue = NULL)
1897{
c461c579 1898 global $dbxlink;
bb6b9880 1899 if (empty ($varname) || $varvalue === NULL)
9c0b0016
DO
1900 {
1901 showError ('Invalid arguments to storeConfigVar()');
1902 return FALSE;
1903 }
1904 $query = "update Config set varvalue='${varvalue}' where varname='${varname}' limit 1";
1905 $result = $dbxlink->query ($query);
1906 if ($result == NULL)
1907 {
1908 showError ("SQL query '${query}' failed in storeConfigVar()");
1909 return FALSE;
1910 }
1911 $rc = $result->rowCount();
1912 $result->closeCursor();
f7ee57a1 1913 if ($rc == 0 or $rc == 1)
9c0b0016 1914 return TRUE;
f7ee57a1 1915 showError ("Something went wrong in storeConfigVar('${varname}', '${varvalue}')");
9c0b0016
DO
1916 return FALSE;
1917}
1918
fbbb74fb
DO
1919// Database version detector. Should behave corretly on any
1920// working dataset a user might have.
1921function getDatabaseVersion ()
1922{
1923 global $dbxlink;
1924 $query = "select varvalue from Config where varname = 'DB_VERSION' and vartype = 'string'";
1925 $result = $dbxlink->query ($query);
1926 if ($result == NULL)
1927 {
1928 $errorInfo = $dbxlink->errorInfo();
1929 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
1930 return '0.14.4';
1931 die ('SQL query #1 failed in getDatabaseVersion() with error ' . $errorInfo[2]);
1932 }
1933 $rows = $result->fetchAll (PDO::FETCH_NUM);
1934 if (count ($rows) != 1 || empty ($rows[0][0]))
1935 {
1936 $result->closeCursor();
1937 die ('Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
1938 }
1939 $ret = $rows[0][0];
1940 $result->closeCursor();
1941 return $ret;
1942}
1943
e673ee24 1944?>