r1271 + completely rewrote getIPRange() to avoid nested joins and be more MySQL-4...
[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 {
798 showError ("SQL query failure in getObjectAddressesAndNames($type_id)");
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
888function getObjectAddresses ($object_id = 0)
889{
890 if ($object_id == 0)
891 {
892 showError ('Invalid object_id in getObjectAddresses()');
893 return;
894 }
895 global $dbxlink;
896 $query =
897 "select ".
898 "IPAddress.name as IPAddress_name, ".
899 "IPAddress.reserved as IPAddress_reserved, ".
900 "IPBonds.name as IPBonds_name, ".
901 "INET_NTOA(IPBonds.ip) as IPBonds_ip, ".
902 "IPBonds.type as IPBonds_type, ".
903 "RemoteBonds.name as RemoteBonds_name, ".
904 "RemoteBonds.type as RemoteBonds_type, ".
905 "RemoteBonds.object_id as RemoteBonds_object_id, ".
906 "RemoteObject.name as RemoteObject_name from IPBonds " .
907 "left join IPBonds as RemoteBonds on IPBonds.ip=RemoteBonds.ip " .
908 "and IPBonds.object_id!=RemoteBonds.object_id " .
909 "left join IPAddress on IPBonds.ip=IPAddress.ip " .
910 "left join RackObject as RemoteObject on RemoteBonds.object_id=RemoteObject.id ".
911 "where ".
912 "IPBonds.object_id = ${object_id} ".
913 "order by IPBonds.ip, RemoteObject.name";
914 $result = $dbxlink->query ($query);
915 if ($result == NULL)
916 {
917 showError ("SQL query failed in getObjectAddresses()");
918 return NULL;
919 }
920 else
921 {
922 $ret=array();
923 $count=0;
924 $refcount=0;
925 $prev_ip = 0;
926 while ($row = $result->fetch (PDO::FETCH_ASSOC))
927 {
928 if ($prev_ip != $row['IPBonds_ip'])
929 {
930 $count++;
931 $refcount=0;
932 $prev_ip = $row['IPBonds_ip'];
933 $ret[$count]['address_name'] = $row['IPAddress_name'];
934 $ret[$count]['address_reserved'] = $row['IPAddress_reserved'];
935 $ret[$count]['ip'] = $row['IPBonds_ip'];
936 $ret[$count]['name'] = $row['IPBonds_name'];
937 $ret[$count]['type'] = $row['IPBonds_type'];
938 $ret[$count]['references'] = array();
939 }
940
941 if ($row['RemoteBonds_type'])
942 {
943 $ret[$count]['references'][$refcount]['type'] = $row['RemoteBonds_type'];
944 $ret[$count]['references'][$refcount]['name'] = $row['RemoteBonds_name'];
945 $ret[$count]['references'][$refcount]['object_id'] = $row['RemoteBonds_object_id'];
946 $ret[$count]['references'][$refcount]['object_name'] = $row['RemoteObject_name'];
947 $refcount++;
948 }
949 }
950 }
951 $result->closeCursor();
952 return $ret;
953}
954
955function getAddressspaceList ()
956{
957 global $dbxlink;
958 $query =
959 "select ".
960 "id as IPRanges_id, ".
961 "INET_NTOA(ip) as IPRanges_ip, ".
962 "mask as IPRanges_mask, ".
963 "name as IPRanges_name ".
964 "from IPRanges ".
965 "order by ip";
966 $result = $dbxlink->query ($query);
967 if ($result == NULL)
968 {
969 return NULL;
970 }
971 else
972 {
973 $ret=array();
974 $count=0;
975 while ($row = $result->fetch (PDO::FETCH_ASSOC))
976 {
977 $ret[$count]['id'] = $row['IPRanges_id'];
978 $ret[$count]['ip'] = $row['IPRanges_ip'];
979 $ret[$count]['ip_bin'] = ip2long($row['IPRanges_ip']);
980 $ret[$count]['name'] = $row['IPRanges_name'];
981 $ret[$count]['mask'] = $row['IPRanges_mask'];
982 $ret[$count]['mask_bin'] = binMaskFromDec($row['IPRanges_mask']);
983 $ret[$count]['mask_bin_inv'] = binInvMaskFromDec($row['IPRanges_mask']);
984 $count++;
985 }
986 }
987 $result->closeCursor();
988 return $ret;
989
990}
991
992function getRangeByIp ($ip = '', $id = 0)
993{
994 global $dbxlink;
995 if ($id == 0)
996 $query =
997 "select ".
998 "id, INET_NTOA(ip) as ip, mask, name ".
999 "from IPRanges ";
1000 else
1001 $query =
1002 "select ".
1003 "id, INET_NTOA(ip) as ip, mask, name ".
1004 "from IPRanges where id='$id'";
1005
1006 $result = $dbxlink->query ($query);
1007 if ($result == NULL)
1008 {
1009 return NULL;
1010 }
1011 else
1012 {
1013 $ret=array();
1014 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1015 {
1016 $binmask=binMaskFromDec($row['mask']);
1017 if ((ip2long($ip) & $binmask) == ip2long($row['ip']))
1018 {
1019 $ret['id'] = $row['id'];
1020 $ret['ip'] = $row['ip'];
1021 $ret['ip_bin'] = ip2long($row['ip']);
1022 $ret['name'] = $row['name'];
1023 $ret['mask'] = $row['mask'];
1024 $result->closeCursor();
1025 return $ret;
1026 }
1027 }
1028 }
1029 $result->closeCursor();
1030 return NULL;
1031}
1032
1033function updateRange ($id=0, $name='')
1034{
1035 global $dbxlink;
1036 $query =
1037 "update IPRanges set name='$name' where id='$id'";
1038 $result = $dbxlink->exec ($query);
1039 return '';
1040
1041}
1042
1043// This function is actually used not only to update, but also to create records,
1044// that's why ON DUPLICATE KEY UPDATE was replaced by DELETE-INSERT pair
1045// (MySQL 4.0 workaround).
1046function updateAddress ($ip=0, $name='', $reserved='no')
1047{
1048 // DELETE may safely fail.
1049 $r = useDeleteBlade ('IPAddress', 'ip', "INET_ATON('${ip}')", FALSE);
1050 // INSERT may appear not necessary.
1051 if ($name == '' and $reserved == 'no')
1052 return '';
1053 if (useInsertBlade ('IPAddress', array ('name' => "'${name}'", 'reserved' => "'${reserved}'", 'ip' => "INET_ATON('${ip}')")))
1054 return '';
1055 else
1056 return 'useInsertBlade() failed in updateAddress()';
1057}
1058
1059function commitDeleteRange ($id = 0)
1060{
1061 if ($id <= 0)
1062 return 'Invalid range ID in commitDeleteRange()';
1063 if (useDeleteBlade ('IPRanges', 'id', $id))
1064 return '';
1065 else
1066 return 'SQL query failed in commitDeleteRange';
1067}
1068
1069function updateBond ($ip='', $object_id=0, $name='', $type='')
1070{
1071 global $dbxlink;
1072
1073 $query =
1074 "update IPBonds set name='$name', type='$type' where ip=INET_ATON('$ip') and object_id='$object_id'";
1075 $result = $dbxlink->exec ($query);
1076 return '';
1077}
1078
1079function unbindIpFromObject ($ip='', $object_id=0)
1080{
1081 global $dbxlink;
1082
1083 $query =
1084 "delete from IPBonds where ip=INET_ATON('$ip') and object_id='$object_id'";
1085 $result = $dbxlink->exec ($query);
1086 return '';
1087}
1088
1089// This function returns either all or one user account. Array key is user name.
1090function getUserAccounts ()
1091{
1092 global $dbxlink;
1093 $query =
1094 'select user_id, user_name, user_password_hash, user_realname, user_enabled ' .
1095 'from UserAccount order by user_id';
1096 $result = $dbxlink->query ($query);
1097 if ($result == NULL)
1098 {
1099 showError ('SQL query failed in getUserAccounts()');
1100 return NULL;
1101 }
1102 $ret = array();
1103 $clist = array ('user_id', 'user_name', 'user_realname', 'user_password_hash', 'user_enabled');
1104 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1105 foreach ($clist as $dummy => $cname)
1106 $ret[$row['user_name']][$cname] = $row[$cname];
1107 $result->closeCursor();
1108 return $ret;
1109}
1110
1111// This function returns permission array for all user accounts. Array key is user name.
1112function getUserPermissions ()
1113{
1114 global $dbxlink;
1115 $query =
1116 "select UserPermission.user_id, user_name, page, tab, access from " .
1117 "UserPermission natural left join UserAccount where (user_name is not null) or " .
1118 "(user_name is null and UserPermission.user_id = 0) order by user_id, page, tab";
1119 $result = $dbxlink->query ($query);
1120 if ($result == NULL)
1121 {
1122 showError ('SQL query failed in getUserPermissions()');
1123 return NULL;
1124 }
1125 $ret = array();
1126 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1127 {
1128 if ($row['user_id'] == 0)
1129 $row['user_name'] = '%';
1130 $ret[$row['user_name']][$row['page']][$row['tab']] = $row['access'];
1131 }
1132 $result->closeCursor();
1133 return $ret;
1134}
1135
1136function searchByl2address ($l2addr)
1137{
1138 global $dbxlink;
1139 $l2addr = l2addressForDatabase ($l2addr);
1140 $query = "select object_id, Port.id as port_id from RackObject as ro inner join Port on ro.id = Port.object_id " .
1141 "where l2address = ${l2addr}";
1142 $result = $dbxlink->query ($query);
1143 if ($result == NULL)
1144 {
1145 showError ('SQL query failed in objectIDbyl2address()');
1146 return NULL;
1147 }
1148 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
1149 $result->closeCursor();
1150 if (count ($rows) == 0) // No results.
1151 return NULL;
1152 if (count ($rows) == 1) // Target found.
1153 return $rows[0];
1154 showError ('More than one results found in objectIDbyl2address(). This is probably a broken unique key.');
1155 return NULL;
1156}
1157
1158// This function returns either port ID or NULL for specified arguments.
1159function getPortID ($object_id, $port_name)
1160{
1161 global $dbxlink;
1162 $query = "select id from Port where object_id=${object_id} and name='${port_name}' limit 2";
1163 $result = $dbxlink->query ($query);
1164 if ($result == NULL)
1165 {
1166 showError ('SQL query failed in getPortID()');
1167 return NULL;
1168 }
1169 $rows = $result->fetchAll (PDO::FETCH_NUM);
1170 if (count ($rows) != 1)
1171 return NULL;
1172 $ret = $rows[0][0];
1173 $result->closeCursor();
1174 return $ret;
1175}
1176
1177function commitCreateUserAccount ($username, $realname, $password)
1178{
1179 return useInsertBlade
1180 (
1181 'UserAccount',
1182 array
1183 (
1184 'user_name' => "'${username}'",
1185 'user_realname' => "'${realname}'",
1186 'user_password_hash' => "'${password}'"
1187 )
1188 );
1189}
1190
1191function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
1192{
1193 global $dbxlink;
1194 $query =
1195 "update UserAccount set user_name = '${new_username}', user_realname = '${new_realname}', " .
1196 "user_password_hash = '${new_password}' where user_id = ${id} limit 1";
1197 $result = $dbxlink->query ($query);
1198 if ($result == NULL)
1199 {
1200 showError ('SQL query failed in commitUpdateUserAccount()');
1201 die;
1202 }
1203 return TRUE;
1204}
1205
1206function commitEnableUserAccount ($id, $new_enabled_value)
1207{
1208 global $dbxlink;
1209 $query =
1210 "update UserAccount set user_enabled = '${new_enabled_value}' " .
1211 "where user_id = ${id} limit 1";
1212 $result = $dbxlink->query ($query);
1213 if ($result == NULL)
1214 {
1215 showError ('SQL query failed in commitEnableUserAccount()');
1216 die;
1217 }
1218 return TRUE;
1219}
1220
1221function commitGrantPermission ($userid, $page, $tab, $value)
1222{
1223 return useInsertBlade
1224 (
1225 'UserPermission',
1226 array
1227 (
1228 'user_id' => $userid,
1229 'page' => "'${page}'",
1230 'tab' => "'${tab}'",
1231 'access' => "'${value}'"
1232 )
1233 );
1234}
1235
1236function commitRevokePermission ($userid, $page, $tab)
1237{
1238 global $dbxlink;
1239 $query =
1240 "delete from UserPermission where user_id = '${userid}' and page = '${page}' " .
1241 "and tab = '$tab' limit 1";
1242 $result = $dbxlink->query ($query);
1243 if ($result == NULL)
1244 {
1245 showError ('SQL query failed in commitRevokePermission()');
1246 die;
1247 }
1248 return TRUE;
1249}
1250
1251// This function returns an array of all port type pairs from PortCompat table.
1252function getPortCompat ()
1253{
1254 global $dbxlink;
1255 $query =
1256 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
1257 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
1258 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
1259 "inner join Chapter as c1 on d1.chapter_no = c1.chapter_no " .
1260 "inner join Chapter as c2 on d2.chapter_no = c2.chapter_no " .
1261 "where c1.chapter_name = 'PortType' and c2.chapter_name = 'PortType'";
1262 $result = $dbxlink->query ($query);
1263 if ($result == NULL)
1264 {
1265 showError ('SQL query failed in getPortCompat()');
1266 return NULL;
1267 }
1268 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
1269 $result->closeCursor();
1270 return $ret;
1271}
1272
1273function removePortCompat ($type1 = 0, $type2 = 0)
1274{
1275 global $dbxlink;
1276 if ($type1 == 0 or $type2 == 0)
1277 {
1278 showError ('Invalid arguments to removePortCompat');
1279 die;
1280 }
1281 $query = "delete from PortCompat where type1 = ${type1} and type2 = ${type2} limit 1";
1282 $result = $dbxlink->query ($query);
1283 if ($result == NULL)
1284 {
1285 showError ('SQL query failed in removePortCompat()');
1286 die;
1287 }
1288 return TRUE;
1289}
1290
1291function addPortCompat ($type1 = 0, $type2 = 0)
1292{
1293 if ($type1 <= 0 or $type2 <= 0)
1294 {
1295 showError ('Invalid arguments to addPortCompat');
1296 die;
1297 }
1298 return useInsertBlade
1299 (
1300 'PortCompat',
1301 array ('type1' => $type1, 'type2' => $type2)
1302 );
1303}
1304
1305// This function returns the dictionary as an array of trees, each tree
1306// representing a single chapter. Each element has 'id', 'name', 'sticky'
1307// and 'word' keys with the latter holding all the words within the chapter.
1308function getDict ()
1309{
1310 global $dbxlink;
1311 $query =
1312 "select chapter_name, Chapter.chapter_no, dict_key, dict_value, sticky from " .
1313 "Chapter natural left join Dictionary order by chapter_name, dict_value";
1314 $result = $dbxlink->query ($query);
1315 if ($result == NULL)
1316 {
1317 showError ('SQL query failed in getDict()');
1318 return NULL;
1319 }
1320 $dict = array();
1321 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1322 {
1323 $chapter_no = $row['chapter_no'];
1324 if (!isset ($dict[$chapter_no]))
1325 {
1326 $dict[$chapter_no]['no'] = $chapter_no;
1327 $dict[$chapter_no]['name'] = $row['chapter_name'];
1328 $dict[$chapter_no]['sticky'] = $row['sticky'] == 'yes' ? TRUE : FALSE;
1329 $dict[$chapter_no]['word'] = array();
1330 }
1331 if ($row['dict_key'] != NULL)
1332 $dict[$chapter_no]['word'][$row['dict_key']] = $row['dict_value'];
1333 }
1334 $result->closeCursor();
1335 return $dict;
1336}
1337
1338function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1339{
1340 if ($chapter_no <= 0 or $dict_key <= 0 or empty ($dict_value))
1341 {
1342 showError ('Invalid args to commitUpdateDictionary()');
1343 die;
1344 }
1345 global $dbxlink;
1346 $query =
1347 "update Dictionary set dict_value = '${dict_value}' where chapter_no=${chapter_no} " .
1348 "and dict_key=${dict_key} limit 1";
1349 $result = $dbxlink->query ($query);
1350 if ($result == NULL)
1351 {
1352 showError ('SQL query failed in commitUpdateDictionary()');
1353 die;
1354 }
1355 return TRUE;
1356}
1357
1358function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1359{
1360 if ($chapter_no <= 0 or empty ($dict_value))
1361 {
1362 showError ('Invalid args to commitSupplementDictionary()');
1363 die;
1364 }
1365 return useInsertBlade
1366 (
1367 'Dictionary',
1368 array ('chapter_no' => $chapter_no, 'dict_value' => "'${dict_value}'")
1369 );
1370}
1371
1372function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1373{
1374 if ($chapter_no <= 0 or $dict_key <= 0)
1375 {
1376 showError ('Invalid args to commitReduceDictionary()');
1377 die;
1378 }
1379 global $dbxlink;
1380 $query =
1381 "delete from Dictionary where chapter_no=${chapter_no} " .
1382 "and dict_key=${dict_key} limit 1";
1383 $result = $dbxlink->query ($query);
1384 if ($result == NULL)
1385 {
1386 showError ('SQL query failed in commitReduceDictionary()');
1387 die;
1388 }
1389 return TRUE;
1390}
1391
1392function commitAddChapter ($chapter_name = '')
1393{
1394 if (empty ($chapter_name))
1395 {
1396 showError ('Invalid args to commitAddChapter()');
1397 die;
1398 }
1399 return useInsertBlade
1400 (
1401 'Chapter',
1402 array ('chapter_name' => "'${chapter_name}'")
1403 );
1404}
1405
1406function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
1407{
1408 if ($chapter_no <= 0 or empty ($chapter_name))
1409 {
1410 showError ('Invalid args to commitUpdateChapter()');
1411 die;
1412 }
1413 global $dbxlink;
1414 $query =
1415 "update Chapter set chapter_name = '${chapter_name}' where chapter_no = ${chapter_no} " .
1416 "and sticky = 'no' limit 1";
1417 $result = $dbxlink->query ($query);
1418 if ($result == NULL)
1419 {
1420 showError ('SQL query failed in commitUpdateChapter()');
1421 die;
1422 }
1423 return TRUE;
1424}
1425
1426function commitDeleteChapter ($chapter_no = 0)
1427{
1428 if ($chapter_no <= 0)
1429 {
1430 showError ('Invalid args to commitDeleteChapter()');
1431 die;
1432 }
1433 global $dbxlink;
1434 $query =
1435 "delete from Chapter where chapter_no = ${chapter_no} and sticky = 'no' limit 1";
1436 $result = $dbxlink->query ($query);
1437 if ($result == NULL)
1438 {
1439 showError ('SQL query failed in commitDeleteChapter()');
1440 die;
1441 }
1442 return TRUE;
1443}
1444
1445// This is a dictionary accessor.
1446function readChapter ($chapter_name = '')
1447{
1448 if (empty ($chapter_name))
1449 {
1450 showError ('invalid argument to readChapter()');
1451 return NULL;
1452 }
1453 global $dbxlink;
1454 $query =
1455 "select dict_key, dict_value from Dictionary natural join Chapter " .
1456 "where chapter_name = '${chapter_name}' order by dict_value";
1457 $result = $dbxlink->query ($query);
1458 if ($result == NULL)
1459 {
1460 $errorInfo = $dbxlink->errorInfo();
1461 showError ("SQL query '${query}'\nwith message '${errorInfo[2]}'\nfailed in readChapter('${chapter_name}')");
1462 return NULL;
1463 }
1464 $chapter = array();
1465 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1466 $chapter[] = $row;
1467 $result->closeCursor();
1468 return $chapter;
1469}
1470
1471function getAttrMap ()
1472{
1473 global $dbxlink;
1474 $query =
1475 "select a.attr_id, a.attr_type, a.attr_name, am.objtype_id, " .
1476 "d.dict_value as objtype_name, am.chapter_no, c2.chapter_name from " .
1477 "Attribute as a natural left join AttributeMap as am " .
1478 "left join Dictionary as d on am.objtype_id = d.dict_key " .
1479 "left join Chapter as c1 on d.chapter_no = c1.chapter_no " .
1480 "left join Chapter as c2 on am.chapter_no = c2.chapter_no " .
1481 "where c1.chapter_name = 'RackObjectType' or c1.chapter_name is null " .
1482 "order by attr_name";
1483 $result = $dbxlink->query ($query);
1484 if ($result == NULL)
1485 {
1486 $errorInfo = $dbxlink->errorInfo();
1487 showError ("SQL query '${query}'\nwith message '${errorInfo[2]}'\nfailed in getAttrMap()");
1488 return NULL;
1489 }
1490 $ret = array();
1491 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1492 {
1493 $attr_id = $row['attr_id'];
1494 if (!isset ($ret[$attr_id]))
1495 {
1496 $ret[$attr_id]['id'] = $attr_id;
1497 $ret[$attr_id]['type'] = $row['attr_type'];
1498 $ret[$attr_id]['name'] = $row['attr_name'];
1499 $ret[$attr_id]['application'] = array();
1500 }
1501 if ($row['objtype_id'] == '')
1502 continue;
1503 $application['objtype_id'] = $row['objtype_id'];
1504 $application['objtype_name'] = $row['objtype_name'];
1505 if ($row['attr_type'] == 'dict')
1506 {
1507 $application['chapter_no'] = $row['chapter_no'];
1508 $application['chapter_name'] = $row['chapter_name'];
1509 }
1510 $ret[$attr_id]['application'][] = $application;
1511 }
1512 $result->closeCursor();
1513 return $ret;
1514}
1515
1516function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
1517{
1518 if ($attr_id <= 0 or empty ($attr_name))
1519 {
1520 showError ('Invalid args to commitUpdateAttribute()');
1521 die;
1522 }
1523 global $dbxlink;
1524 $query =
1525 "update Attribute set attr_name = '${attr_name}' " .
1526 "where attr_id = ${attr_id} limit 1";
1527 $result = $dbxlink->query ($query);
1528 if ($result == NULL)
1529 {
1530 showError ("SQL query '${query}' failed in commitUpdateAttribute()");
1531 die;
1532 }
1533 return TRUE;
1534}
1535
1536function commitAddAttribute ($attr_name = '', $attr_type = '')
1537{
1538 if (empty ($attr_name))
1539 {
1540 showError ('Invalid args to commitAddAttribute()');
1541 die;
1542 }
1543 switch ($attr_type)
1544 {
1545 case 'uint':
1546 case 'float':
1547 case 'string':
1548 case 'dict':
1549 break;
1550 default:
1551 showError ('Invalid args to commitAddAttribute()');
1552 die;
1553 }
1554 return useInsertBlade
1555 (
1556 'Attribute',
1557 array ('attr_name' => "'${attr_name}'", 'attr_type' => "'${attr_type}'")
1558 );
1559}
1560
1561function commitDeleteAttribute ($attr_id = 0)
1562{
1563 if ($attr_id <= 0)
1564 {
1565 showError ('Invalid args to commitDeleteAttribute()');
1566 die;
1567 }
1568 return useDeleteBlade ('Attribute', 'attr_id', $attr_id);
1569}
1570
1571// FIXME: don't store garbage in chapter_no for non-dictionary types.
1572function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
1573{
1574 if ($attr_id <= 0 or $objtype_id <= 0 or $chapter_no <= 0)
1575 {
1576 showError ('Invalid args to commitSupplementAttrMap()');
1577 die;
1578 }
1579 return useInsertBlade
1580 (
1581 'AttributeMap',
1582 array
1583 (
1584 'attr_id' => $attr_id,
1585 'objtype_id' => $objtype_id,
1586 'chapter_no' => $chapter_no
1587 )
1588 );
1589}
1590
1591function commitReduceAttrMap ($attr_id = 0, $objtype_id)
1592{
1593 if ($attr_id <= 0 or $objtype_id <= 0)
1594 {
1595 showError ('Invalid args to commitReduceAttrMap()');
1596 die;
1597 }
1598 global $dbxlink;
1599 $query =
1600 "delete from AttributeMap where attr_id=${attr_id} " .
1601 "and objtype_id=${objtype_id} limit 1";
1602 $result = $dbxlink->query ($query);
1603 if ($result == NULL)
1604 {
1605 showError ('SQL query failed in commitReduceAttrMap()');
1606 die;
1607 }
1608 return TRUE;
1609}
1610
1611// This function returns all optional attributes for requested object
1612// as an array of records. NULL is returned on error and empty array
1613// is returned, if there are no attributes found.
1614function getAttrValues ($object_id)
1615{
1616 if ($object_id <= 0)
1617 {
1618 showError ('Invalid argument to getAttrValues()');
1619 return NULL;
1620 }
1621 global $dbxlink;
1622 $ret = array();
1623 $query =
1624 "select A.attr_id, A.attr_name, A.attr_type, C.chapter_name, " .
1625 "AV.uint_value, AV.float_value, AV.string_value, D.dict_value from " .
1626 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
1627 "inner join Attribute as A using (attr_id) " .
1628 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
1629 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_no = D.chapter_no " .
1630 "left join Chapter as C on AM.chapter_no = C.chapter_no " .
1631 "where RO.id = ${object_id} order by A.attr_type";
1632 $result = $dbxlink->query ($query);
1633 if ($result == NULL)
1634 {
1635 $errorInfo = $dbxlink->errorInfo();
1636 showError ("SQL query '${query}'\nwith message '${errorInfo[2]}'\nfailed in getAttrValues()");
1637 return NULL;
1638 }
1639 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1640 {
1641 $record = array();
1642 $record['id'] = $row['attr_id'];
1643 $record['name'] = $row['attr_name'];
1644 $record['type'] = $row['attr_type'];
1645 switch ($row['attr_type'])
1646 {
1647 case 'uint':
1648 case 'float':
1649 case 'string':
1650 case 'dict':
1651 $record['value'] = $row[$row['attr_type'] . '_value'];
1652 $record['chapter_name'] = $row['chapter_name'];
1653 $record['key'] = $row['uint_value'];
1654 break;
1655 default:
1656 $record['value'] = NULL;
1657 break;
1658 }
1659 $ret[$row['attr_id']] = $record;
1660 }
1661 $result->closeCursor();
1662 return $ret;
1663}
1664
1665function commitResetAttrValue ($object_id = 0, $attr_id = 0)
1666{
1667 if ($object_id <= 0 or $attr_id <= 0)
1668 {
1669 showError ('Invalid arguments to commitResetAttrValue()');
1670 die;
1671 }
1672 global $dbxlink;
1673 $query = "delete from AttributeValue where object_id = ${object_id} and attr_id = ${attr_id} limit 1";
1674 $result = $dbxlink->query ($query);
1675 if ($result == NULL)
1676 {
1677 showError ('SQL query failed in commitResetAttrValue()');
1678 die;
1679 }
1680 return TRUE;
1681}
1682
1683// FIXME: don't share common code with use commitResetAttrValue()
1684function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
1685{
1686 if ($object_id <= 0 or $attr_id <= 0)
1687 {
1688 showError ('Invalid arguments to commitUpdateAttrValue()');
1689 die;
1690 }
1691 if (empty ($value))
1692 return commitResetAttrValue ($object_id, $attr_id);
1693 global $dbxlink;
1694 $query1 = "select attr_type from Attribute where attr_id = ${attr_id}";
1695 $result = $dbxlink->query ($query1);
1696 if ($result == NULL)
1697 {
1698 showError ('SQL query #1 failed in commitUpdateAttrValue()');
1699 die;
1700 }
1701 $row = $result->fetch (PDO::FETCH_NUM);
1702 if ($row == NULL)
1703 {
1704 showError ('SQL query #1 returned no results in commitUpdateAttrValue()');
1705 die;
1706 }
1707 $attr_type = $row[0];
1708 $result->closeCursor();
1709 switch ($attr_type)
1710 {
1711 case 'uint':
1712 case 'float':
1713 case 'string':
1714 $column = $attr_type . '_value';
1715 break;
1716 case 'dict':
1717 $column = 'uint_value';
1718 break;
1719 default:
1720 showError ("Unknown attribute type '${attr_type}' met in commitUpdateAttrValue()");
1721 die;
1722 }
1723 $query2 =
1724 "delete from AttributeValue where " .
1725 "object_id = ${object_id} and attr_id = ${attr_id} limit 1";
1726 $result = $dbxlink->query ($query2);
1727 if ($result == NULL)
1728 {
1729 showError ('SQL query #2 failed in commitUpdateAttrValue()');
1730 die;
1731 }
1732 // We know $value isn't empty here.
1733 $query3 =
1734 "insert into AttributeValue set ${column} = '${value}', " .
1735 "object_id = ${object_id}, attr_id = ${attr_id} ";
1736 $result = $dbxlink->query ($query3);
1737 if ($result == NULL)
1738 {
1739 showError ('SQL query #3 failed in commitUpdateAttrValue()');
1740 die;
1741 }
1742 return TRUE;
1743}
1744
1745function commitUseupPort ($port_id = 0)
1746{
1747 if ($port_id <= 0)
1748 {
1749 showError ("Invalid argument to commitUseupPort()");
1750 die;
1751 }
1752 global $dbxlink;
1753 $query = "update Port set reservation_comment = NULL where id = ${port_id} limit 1";
1754 $result = $dbxlink->exec ($query);
1755 if ($result == NULL)
1756 {
1757 showError ("SQL query failed in commitUseupPort()");
1758 die;
1759 }
1760 return TRUE;
1761
1762}
1763
4fe32e78
DY
1764function commitUpdateUI ($varname, $vartype, $emptyok, $varvalue, $description)
1765{
1766 if (empty ($varname) || empty ($vartype) || empty ($emptyok) || empty ($varvalue)|| empty ($description))
1767 {
1768 showError ('Not all required args to commitUpdateUI() are present.');
1769 return FALSE;
1770 }
1771 global $dbxlink;
1772 $query = "UPDATE Config SET vartype='${vartype}', emptyok='${emptyok}', varvalue='${varvalue}', description='${description}' " .
1773 "WHERE varname='${varname}'";
1774 $result = $dbxlink->query ($query);
1775 if ($result->rowCount() != 1)
1776 {
1777 showError ('Error updating config in commitUpdateUI()');
1778 return FALSE;
1779 }
1780 return TRUE;
1781}
1782
e673ee24
DO
1783// This is a swiss-knife blade to insert a record into a table.
1784// The first argument is table name.
1785// The second argument is an array of "name" => "value" pairs.
1786// The function returns either TRUE or FALSE (we expect one row
1787// to be inserted).
1788function useInsertBlade ($tablename, $values)
1789{
1790 global $dbxlink;
1791 $namelist = $valuelist = '';
1792 foreach ($values as $name => $value)
1793 {
1794 $namelist = $namelist . ($namelist == '' ? "(${name}" : ", ${name}");
1795 $valuelist = $valuelist . ($valuelist == '' ? "(${value}" : ", ${value}");
1796 }
1797 $query = "insert into ${tablename} ${namelist}) values ${valuelist})";
1798 $result = $dbxlink->exec ($query);
1799 if ($result != 1)
1800 return FALSE;
1801 return TRUE;
1802}
1803
1804// This swiss-knife blade deletes one record from the specified table
1805// using the specified key name and value.
1806function useDeleteBlade ($tablename, $keyname, $keyvalue, $quotekey = TRUE)
1807{
1808 global $dbxlink;
1809 if ($quotekey == TRUE)
1810 $query = "delete from ${tablename} where ${keyname}='$keyvalue' limit 1";
1811 else
1812 $query = "delete from ${tablename} where ${keyname}=$keyvalue limit 1";
1813 $result = $dbxlink->exec ($query);
1814 if ($result === NULL)
1815 return FALSE;
1816 elseif ($result != 1)
1817 return FALSE;
1818 else
1819 return TRUE;
1820}
1821
9c0b0016
DO
1822function loadConfigCache ()
1823{
1824 global $dbxlink;
4fe32e78 1825 $query = 'SELECT varname, varvalue, vartype, is_hidden, emptyok, description FROM Config ORDER BY varname';
9c0b0016
DO
1826 $result = $dbxlink->query ($query);
1827 if ($result == NULL)
1828 {
1829 $errorInfo = $dbxlink->errorInfo();
4785bafa 1830 showError ("SQL query '${query}'\nwith message '${errorInfo[2]}'\nfailed in loadConfigCache()");
9c0b0016
DO
1831 return NULL;
1832 }
1833 $cache = array();
1834 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1835 $cache[$row['varname']] = $row;
1836 $result->closeCursor();
1837 return $cache;
1838}
1839
1840// setConfigVar() is expected to perform all necessary filtering
1841function storeConfigVar ($varname = NULL, $varvalue = NULL)
1842{
1843 if ($varname == NULL || $varvalue == NULL)
1844 {
1845 showError ('Invalid arguments to storeConfigVar()');
1846 return FALSE;
1847 }
1848 $query = "update Config set varvalue='${varvalue}' where varname='${varname}' limit 1";
1849 $result = $dbxlink->query ($query);
1850 if ($result == NULL)
1851 {
1852 showError ("SQL query '${query}' failed in storeConfigVar()");
1853 return FALSE;
1854 }
1855 $rc = $result->rowCount();
1856 $result->closeCursor();
1857 if ($rc == 1)
1858 return TRUE;
1859 showError ("Something went wrong in storeConfigVar() when updatating '${varname}'");
1860 return FALSE;
1861}
1862
fbbb74fb
DO
1863// Database version detector. Should behave corretly on any
1864// working dataset a user might have.
1865function getDatabaseVersion ()
1866{
1867 global $dbxlink;
1868 $query = "select varvalue from Config where varname = 'DB_VERSION' and vartype = 'string'";
1869 $result = $dbxlink->query ($query);
1870 if ($result == NULL)
1871 {
1872 $errorInfo = $dbxlink->errorInfo();
1873 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
1874 return '0.14.4';
1875 die ('SQL query #1 failed in getDatabaseVersion() with error ' . $errorInfo[2]);
1876 }
1877 $rows = $result->fetchAll (PDO::FETCH_NUM);
1878 if (count ($rows) != 1 || empty ($rows[0][0]))
1879 {
1880 $result->closeCursor();
1881 die ('Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
1882 }
1883 $ret = $rows[0][0];
1884 $result->closeCursor();
1885 return $ret;
1886}
1887
e673ee24 1888?>