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