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