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