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