r1934 + treat tag list to pre-assign to newly added rack(s)
[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, $do_db_escape = TRUE)
9 {
10 $ret = htmlentities ($value, ENT_QUOTES, 'UTF-8');
11 if ($do_db_escape)
12 {
13 global $dbxlink;
14 $ret = substr ($dbxlink->quote ($ret), 1, -1);
15 }
16 return $ret;
17 }
18
19 function getRackspace ($tagfilter = array())
20 {
21 $whereclause = getWhereClause ($tagfilter);
22 $query =
23 "select dict_key as row_id, dict_value as row_name " .
24 "from Chapter natural join Dictionary left join Rack on Rack.row_id = dict_key " .
25 "left join TagStorage on Rack.id = TagStorage.target_id and target_realm = 'rack' " .
26 "where chapter_name = 'RackRow' " .
27 $whereclause .
28 " order by dict_value";
29 $result = useSelectBlade ($query);
30 $ret = array();
31 $clist = array ('row_id', 'row_name');
32 while ($row = $result->fetch (PDO::FETCH_ASSOC))
33 foreach ($clist as $cname)
34 $ret[$row['row_id']][$cname] = $row[$cname];
35 $result->closeCursor();
36 return $ret;
37 }
38
39 // This function returns detailed information about either all or one
40 // rack row depending on its argument.
41 function getRackRowInfo ($rackrow_id = 0)
42 {
43 $query =
44 "select dict_key, dict_value, count(Rack.id) as count, " .
45 "if(isnull(sum(Rack.height)),0,sum(Rack.height)) as sum " .
46 "from Chapter natural join Dictionary left join Rack on Rack.row_id = dict_key " .
47 "where chapter_name = 'RackRow' " .
48 ($rackrow_id > 0 ? "and dict_key = ${rackrow_id} " : '') .
49 "group by dict_key order by dict_value";
50 $result = useSelectBlade ($query);
51 $ret = array();
52 $clist = array ('dict_key', 'dict_value', 'count', 'sum');
53 while ($row = $result->fetch (PDO::FETCH_ASSOC))
54 foreach ($clist as $cname)
55 $ret[$row['dict_key']][$cname] = $row[$cname];
56 $result->closeCursor();
57 if ($rackrow_id > 0)
58 return current ($ret);
59 else
60 return $ret;
61 }
62
63 // This function returns id->name map for all object types. The map is used
64 // to build <select> input for objects.
65 function getObjectTypeList ()
66 {
67 return readChapter ('RackObjectType');
68 }
69
70 // Return a part of SQL query suitable for embeding into a bigger text.
71 // The returned result should list all tag IDs shown in the tag filter.
72 function getWhereClause ($tagfilter = array())
73 {
74 $whereclause = '';
75 if (count ($tagfilter))
76 {
77 $whereclause .= ' and (';
78 $orclause = '';
79 foreach ($tagfilter as $tag_id)
80 {
81 $whereclause .= $orclause . 'tag_id = ' . $tag_id;
82 $orclause = ' or ';
83 }
84 $whereclause .= ') ';
85 }
86 return $whereclause;
87 }
88
89 function getObjectList ($type_id = 0, $tagfilter = array())
90 {
91 $whereclause = getWhereClause ($tagfilter);
92 if ($type_id != 0)
93 $whereclause .= " and objtype_id = '${type_id}' ";
94 $query =
95 "select distinct RackObject.id as id , RackObject.name as name, dict_value as objtype_name, " .
96 "RackObject.label as label, RackObject.barcode as barcode, " .
97 "dict_key as objtype_id, asset_no, rack_id, Rack.name as Rack_name from " .
98 "((RackObject inner join Dictionary on objtype_id=dict_key natural join Chapter) " .
99 "left join RackSpace on RackObject.id = object_id) " .
100 "left join Rack on rack_id = Rack.id " .
101 "left join TagStorage on RackObject.id = TagStorage.target_id and target_realm = 'object' " .
102 "where RackObject.deleted = 'no' and chapter_name = 'RackObjectType' " .
103 $whereclause .
104 "order by name";
105 $result = useSelectBlade ($query);
106 $ret = array();
107 while ($row = $result->fetch (PDO::FETCH_ASSOC))
108 {
109 foreach (array (
110 'id',
111 'name',
112 'label',
113 'barcode',
114 'objtype_name',
115 'objtype_id',
116 'asset_no',
117 'rack_id',
118 'Rack_name'
119 ) as $cname)
120 $ret[$row['id']][$cname] = $row[$cname];
121 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
122 }
123 $result->closeCursor();
124 return $ret;
125 }
126
127 function getRacksForRow ($row_id = 0, $tagfilter = array())
128 {
129 $query =
130 "select Rack.id, Rack.name, height, Rack.comment, row_id, " .
131 "'yes' as left_is_front, 'yes' as bottom_is_unit1, dict_value as row_name " .
132 "from Rack left join Dictionary on row_id = dict_key natural join Chapter " .
133 "left join TagStorage on Rack.id = TagStorage.target_id and target_realm = 'rack' " .
134 "where chapter_name = 'RackRow' and Rack.deleted = 'no' " .
135 (($row_id == 0) ? "" : "and row_id = ${row_id} ") .
136 getWhereClause ($tagfilter) .
137 " order by row_name, Rack.id";
138 $result = useSelectBlade ($query);
139 $ret = array();
140 $clist = array
141 (
142 'id',
143 'name',
144 'height',
145 'comment',
146 'row_id',
147 'left_is_front',
148 'bottom_is_unit1',
149 'row_name'
150 );
151 while ($row = $result->fetch (PDO::FETCH_ASSOC))
152 foreach ($clist as $cname)
153 $ret[$row['id']][$cname] = $row[$cname];
154 $result->closeCursor();
155 usort ($ret, 'sortRacks');
156 $ret = restoreRackIDs ($ret);
157 return $ret;
158 }
159
160 // This is a popular helper for getting information about
161 // a particular rack and its rackspace at once.
162 function getRackData ($rack_id = 0, $silent = FALSE)
163 {
164 if ($rack_id == 0)
165 {
166 if ($silent == FALSE)
167 showError ('Invalid rack_id', __FUNCTION__);
168 return NULL;
169 }
170 $query =
171 "select Rack.id, Rack.name, row_id, height, Rack.comment, " .
172 "'yes' as left_is_front, 'yes' as bottom_is_unit1, dict_value as row_name from " .
173 "Rack left join Dictionary on Rack.row_id = dict_key natural join Chapter " .
174 "where chapter_name = 'RackRow' and Rack.id='${rack_id}' and Rack.deleted = 'no' limit 1";
175 $result = useSelectBlade ($query);
176 if (($row = $result->fetch (PDO::FETCH_ASSOC)) == NULL)
177 {
178 if ($silent == FALSE)
179 showError ('Query #1 succeded, but returned no data', __FUNCTION__);
180 return NULL;
181 }
182
183 // load metadata
184 $clist = array
185 (
186 'id',
187 'name',
188 'height',
189 'comment',
190 'row_id',
191 'left_is_front',
192 'bottom_is_unit1',
193 'row_name'
194 );
195 foreach ($clist as $cname)
196 $rack[$cname] = $row[$cname];
197 $result->closeCursor();
198 unset ($result);
199
200 // start with default rackspace
201 for ($i = $rack['height']; $i > 0; $i--)
202 for ($locidx = 0; $locidx < 3; $locidx++)
203 $rack[$i][$locidx]['state'] = 'F';
204
205 // load difference
206 $query =
207 "select unit_no, atom, state, object_id " .
208 "from RackSpace where rack_id = ${rack_id} and " .
209 "unit_no between 1 and " . $rack['height'] . " order by unit_no";
210 $result = useSelectBlade ($query);
211 global $loclist;
212 while ($row = $result->fetch (PDO::FETCH_ASSOC))
213 {
214 $rack[$row['unit_no']][$loclist[$row['atom']]]['state'] = $row['state'];
215 $rack[$row['unit_no']][$loclist[$row['atom']]]['object_id'] = $row['object_id'];
216 }
217 $result->closeCursor();
218 return $rack;
219 }
220
221 // This is a popular helper.
222 function getObjectInfo ($object_id = 0)
223 {
224 if ($object_id == 0)
225 {
226 showError ('Invalid object_id', __FUNCTION__);
227 return;
228 }
229 $query =
230 "select id, name, label, barcode, dict_value as objtype_name, asset_no, dict_key as objtype_id, has_problems, comment from " .
231 "RackObject inner join Dictionary on objtype_id = dict_key natural join Chapter " .
232 "where id = '${object_id}' and deleted = 'no' and chapter_name = 'RackObjectType' limit 1";
233 $result = useSelectBlade ($query);
234 if (($row = $result->fetch (PDO::FETCH_ASSOC)) == NULL)
235 {
236 showError ('Query succeded, but returned no data', __FUNCTION__);
237 $ret = NULL;
238 }
239 else
240 {
241 $ret['id'] = $row['id'];
242 $ret['name'] = $row['name'];
243 $ret['label'] = $row['label'];
244 $ret['barcode'] = $row['barcode'];
245 $ret['objtype_name'] = $row['objtype_name'];
246 $ret['objtype_id'] = $row['objtype_id'];
247 $ret['has_problems'] = $row['has_problems'];
248 $ret['asset_no'] = $row['asset_no'];
249 $ret['dname'] = displayedName ($ret);
250 $ret['comment'] = $row['comment'];
251 }
252 $result->closeCursor();
253 return $ret;
254 }
255
256 function getPortTypes ()
257 {
258 return readChapter ('PortType');
259 }
260
261 function getObjectPortsAndLinks ($object_id = 0)
262 {
263 if ($object_id == 0)
264 {
265 showError ('Invalid object_id', __FUNCTION__);
266 return;
267 }
268 $query =
269 "select Port.id as Port_id, ".
270 "Port.name as Port_name, ".
271 "Port.label as Port_label, ".
272 "Port.l2address as Port_l2address, ".
273 "Port.type as Port_type, ".
274 "Port.reservation_comment as Port_reservation_comment, " .
275 "dict_value as PortType_name, ".
276 "RemotePort.id as RemotePort_id, ".
277 "RemotePort.name as RemotePort_name, ".
278 "RemotePort.object_id as RemotePort_object_id, ".
279 "RackObject.name as RackObject_name ".
280 "from (".
281 "(".
282 "(".
283 "Port inner join Dictionary on Port.type = dict_key natural join Chapter".
284 ") ".
285 "left join Link on Port.id=Link.porta or Port.id=Link.portb ".
286 ") ".
287 "left join Port as RemotePort on Link.portb=RemotePort.id or Link.porta=RemotePort.id ".
288 ") ".
289 "left join RackObject on RemotePort.object_id=RackObject.id ".
290 "where chapter_name = 'PortType' and Port.object_id=${object_id} ".
291 "and (Port.id != RemotePort.id or RemotePort.id is null) ".
292 "order by Port_name";
293 $result = useSelectBlade ($query);
294 $ret=array();
295 $count=0;
296 while ($row = $result->fetch (PDO::FETCH_ASSOC))
297 {
298 $ret[$count]['id'] = $row['Port_id'];
299 $ret[$count]['name'] = $row['Port_name'];
300 $ret[$count]['l2address'] = l2addressFromDatabase ($row['Port_l2address']);
301 $ret[$count]['label'] = $row['Port_label'];
302 $ret[$count]['type_id'] = $row['Port_type'];
303 $ret[$count]['type'] = $row['PortType_name'];
304 $ret[$count]['reservation_comment'] = $row['Port_reservation_comment'];
305 $ret[$count]['remote_id'] = $row['RemotePort_id'];
306 $ret[$count]['remote_name'] = htmlentities ($row['RemotePort_name'], ENT_QUOTES);
307 $ret[$count]['remote_object_id'] = $row['RemotePort_object_id'];
308 $ret[$count]['remote_object_name'] = $row['RackObject_name'];
309 // Save on displayedName() calls.
310 if (empty ($row['RackObject_name']) and !empty ($row['RemotePort_object_id']))
311 {
312 $oi = getObjectInfo ($row['RemotePort_object_id']);
313 $ret[$count]['remote_object_name'] = displayedName ($oi);
314 }
315 $count++;
316 }
317 $result->closeCursor();
318 return $ret;
319 }
320
321 function commitAddRack ($name, $height, $row_id, $comment, $taglist)
322 {
323 $result = useInsertBlade
324 (
325 'Rack',
326 array
327 (
328 'row_id' => $row_id,
329 'name' => "'${name}'",
330 'height' => $height,
331 'comment' => "'${comment}'"
332 )
333 );
334 if ($result == NULL)
335 {
336 showError ('useInsertBlade() failed', __FUNCTION__);
337 return FALSE;
338 }
339
340 if (($result = useSelectBlade ('select last_insert_id()')) == NULL)
341 {
342 showError ('Query #2 failed', __FUNCTION__);
343 return FALSE;
344 }
345 // we always have a row
346 $row = $result->fetch (PDO::FETCH_NUM);
347 $last_insert_id = $row[0];
348 $result->closeCursor();
349 foreach ($taglist as $tag_id)
350 if (useInsertBlade
351 (
352 'TagStorage',
353 array
354 (
355 'target_realm' => "'rack'",
356 'target_id' => $last_insert_id,
357 'tag_id' => $tag_id
358 )
359 ) == FALSE)
360 $errcount++;
361 if ($errcount)
362 showError ("Experienced ${errcount} errors adding tags for the rack");
363 return recordHistory ('Rack', "id = ${last_insert_id}");
364 }
365
366 function commitAddObject ($new_name, $new_label, $new_barcode, $new_type_id, $new_asset_no)
367 {
368 global $dbxlink;
369 // Maintain UNIQUE INDEX for common names and asset tags.
370 $new_asset_no = empty ($new_asset_no) ? 'NULL' : "'${new_asset_no}'";
371 $new_barcode = empty ($new_barcode) ? 'NULL' : "'${new_barcode}'";
372 $new_name = empty ($new_name) ? 'NULL' : "'${new_name}'";
373 $query =
374 "insert into RackObject(name, label, barcode, objtype_id, asset_no) " .
375 "values(${new_name}, '${new_label}', ${new_barcode}, '${new_type_id}', ${new_asset_no})";
376 $result1 = $dbxlink->query ($query);
377 if ($result1 == NULL)
378 {
379 $errorInfo = $dbxlink->errorInfo();
380 showError ("SQL query '${query}' failed: ${errorInfo[2]}", __FUNCTION__);
381 die;
382 }
383 if ($result1->rowCount() != 1)
384 {
385 showError ('Adding new object failed', __FUNCTION__);
386 return FALSE;
387 }
388 $query = 'select last_insert_id()';
389 $result2 = $dbxlink->query ($query);
390 if ($result2 == NULL)
391 {
392 $errorInfo = $dbxlink->errorInfo();
393 showError ("SQL query '${query}' failed: ${errorInfo[2]}", __FUNCTION__);
394 die;
395 }
396 // we always have a row
397 $row = $result2->fetch (PDO::FETCH_NUM);
398 $last_insert_id = $row[0];
399 $result2->closeCursor();
400 // Do AutoPorts magic
401 executeAutoPorts ($last_insert_id, $new_type_id);
402 return recordHistory ('RackObject', "id = ${last_insert_id}");
403 }
404
405 function commitUpdateObject ($object_id = 0, $new_name = '', $new_label = '', $new_barcode = '', $new_type_id = 0, $new_has_problems = 'no', $new_asset_no = '', $new_comment = '')
406 {
407 if ($object_id == 0 || $new_type_id == 0)
408 {
409 showError ('Not all required args are present.', __FUNCTION__);
410 return FALSE;
411 }
412 global $dbxlink;
413 $new_asset_no = empty ($new_asset_no) ? 'NULL' : "'${new_asset_no}'";
414 $new_barcode = empty ($new_barcode) ? 'NULL' : "'${new_barcode}'";
415 $new_name = empty ($new_name) ? 'NULL' : "'${new_name}'";
416 $query = "update RackObject set name=${new_name}, label='${new_label}', barcode=${new_barcode}, objtype_id='${new_type_id}', " .
417 "has_problems='${new_has_problems}', asset_no=${new_asset_no}, comment='${new_comment}' " .
418 "where id='${object_id}' limit 1";
419 $result = $dbxlink->query ($query);
420 if ($result == NULL)
421 {
422 showError ("SQL query '${query}' failed", __FUNCTION__);
423 return FALSE;
424 }
425 $result->closeCursor();
426 return recordHistory ('RackObject', "id = ${object_id}");
427 }
428
429 function commitUpdateRack ($rack_id, $new_name, $new_height, $new_row_id, $new_comment)
430 {
431 if (empty ($rack_id) || empty ($new_name) || empty ($new_height))
432 {
433 showError ('Not all required args are present.', __FUNCTION__);
434 return FALSE;
435 }
436 global $dbxlink;
437 $query = "update Rack set name='${new_name}', height='${new_height}', comment='${new_comment}', row_id=${new_row_id} " .
438 "where id='${rack_id}' limit 1";
439 $result1 = $dbxlink->query ($query);
440 if ($result1->rowCount() != 1)
441 {
442 showError ('Error updating rack information', __FUNCTION__);
443 return FALSE;
444 }
445 return recordHistory ('Rack', "id = ${rack_id}");
446 }
447
448 // This function accepts rack data returned by getRackData(), validates and applies changes
449 // supplied in $_REQUEST and returns resulting array. Only those changes are examined, which
450 // correspond to current rack ID.
451 // 1st arg is rackdata, 2nd arg is unchecked state, 3rd arg is checked state.
452 // If 4th arg is present, object_id fields will be updated accordingly to the new state.
453 // The function returns the modified rack upon success.
454 function processGridForm (&$rackData, $unchecked_state, $checked_state, $object_id = 0)
455 {
456 global $loclist, $dbxlink;
457 $rack_id = $rackData['id'];
458 $rack_name = $rackData['name'];
459 $rackchanged = FALSE;
460 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
461 {
462 for ($locidx = 0; $locidx < 3; $locidx++)
463 {
464 if ($rackData[$unit_no][$locidx]['enabled'] != TRUE)
465 continue;
466 // detect a change
467 $state = $rackData[$unit_no][$locidx]['state'];
468 if (isset ($_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"]) and $_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"] == 'on')
469 $newstate = $checked_state;
470 else
471 $newstate = $unchecked_state;
472 if ($state == $newstate)
473 continue;
474 $rackchanged = TRUE;
475 // and validate
476 $atom = $loclist[$locidx];
477 // The only changes allowed are those introduced by checkbox grid.
478 if
479 (
480 !($state == $checked_state && $newstate == $unchecked_state) &&
481 !($state == $unchecked_state && $newstate == $checked_state)
482 )
483 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, 'atom ${atom}', cannot change state from '${state}' to '${newstate}'");
484 // Here we avoid using ON DUPLICATE KEY UPDATE by first performing DELETE
485 // anyway and then looking for probable need of INSERT.
486 $query =
487 "delete from RackSpace where rack_id = ${rack_id} and " .
488 "unit_no = ${unit_no} and atom = '${atom}' limit 1";
489 $r = $dbxlink->query ($query);
490 if ($r == NULL)
491 return array ('code' => 500, 'message' => __FUNCTION__ . ": ${rack_name}: SQL DELETE query failed");
492 if ($newstate != 'F')
493 {
494 $query =
495 "insert into RackSpace(rack_id, unit_no, atom, state) " .
496 "values(${rack_id}, ${unit_no}, '${atom}', '${newstate}') ";
497 $r = $dbxlink->query ($query);
498 if ($r == NULL)
499 return array ('code' => 500, 'message' => __FUNCTION__ . ": ${rack_name}: SQL INSERT query failed");
500 }
501 if ($newstate == 'T' and $object_id != 0)
502 {
503 // At this point we already have a record in RackSpace.
504 $query =
505 "update RackSpace set object_id=${object_id} " .
506 "where rack_id=${rack_id} and unit_no=${unit_no} and atom='${atom}' limit 1";
507 $r = $dbxlink->query ($query);
508 if ($r->rowCount() == 1)
509 $rackData[$unit_no][$locidx]['object_id'] = $object_id;
510 else
511 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, atom '${atom}' failed to set object_id to '${object_id}'");
512 }
513 }
514 }
515 if ($rackchanged)
516 {
517 resetThumbCache ($rack_id);
518 return array ('code' => 200, 'message' => "${rack_name}: All changes were successfully saved.");
519 }
520 else
521 return array ('code' => 300, 'message' => "${rack_name}: No changes.");
522 }
523
524 // This function builds a list of rack-unit-atom records, which are assigned to
525 // the requested object.
526 function getMoleculeForObject ($object_id = 0)
527 {
528 if ($object_id == 0)
529 {
530 showError ("object_id == 0", __FUNCTION__);
531 return NULL;
532 }
533 $query =
534 "select rack_id, unit_no, atom from RackSpace " .
535 "where state = 'T' and object_id = ${object_id} order by rack_id, unit_no, atom";
536 $result = useSelectBlade ($query);
537 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
538 $result->closeCursor();
539 return $ret;
540 }
541
542 // This function builds a list of rack-unit-atom records for requested molecule.
543 function getMolecule ($mid = 0)
544 {
545 if ($mid == 0)
546 {
547 showError ("mid == 0", __FUNCTION__);
548 return NULL;
549 }
550 $query =
551 "select rack_id, unit_no, atom from Atom " .
552 "where molecule_id=${mid}";
553 $result = useSelectBlade ($query);
554 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
555 $result->closeCursor();
556 return $ret;
557 }
558
559 // This function creates a new record in Molecule and number of linked
560 // R-U-A records in Atom.
561 function createMolecule ($molData)
562 {
563 global $dbxlink;
564 $query = "insert into Molecule values()";
565 $result1 = $dbxlink->query ($query);
566 if ($result1->rowCount() != 1)
567 {
568 showError ('Error inserting into Molecule', __FUNCTION__);
569 return NULL;
570 }
571 $query = 'select last_insert_id()';
572 $result2 = $dbxlink->query ($query);
573 if ($result2 == NULL)
574 {
575 showError ('Cannot get last ID.', __FUNCTION__);
576 return NULL;
577 }
578 $row = $result2->fetch (PDO::FETCH_NUM);
579 $molecule_id = $row[0];
580 $result2->closeCursor();
581 foreach ($molData as $rua)
582 {
583 $rack_id = $rua['rack_id'];
584 $unit_no = $rua['unit_no'];
585 $atom = $rua['atom'];
586 $query =
587 "insert into Atom(molecule_id, rack_id, unit_no, atom) " .
588 "values (${molecule_id}, ${rack_id}, ${unit_no}, '${atom}')";
589 $result3 = $dbxlink->query ($query);
590 if ($result3 == NULL or $result3->rowCount() != 1)
591 {
592 showError ('Error inserting into Atom', __FUNCTION__);
593 return NULL;
594 }
595 }
596 return $molecule_id;
597 }
598
599 // History logger. This function assumes certain table naming convention and
600 // column design:
601 // 1. History table name equals to dictionary table name plus 'History'.
602 // 2. History table must have the same row set (w/o keys) plus one row named
603 // 'ctime' of type 'timestamp'.
604 function recordHistory ($tableName, $whereClause)
605 {
606 global $dbxlink, $remote_username;
607 $query = "insert into ${tableName}History select *, current_timestamp(), '${remote_username}' from ${tableName} where ${whereClause}";
608 $result = $dbxlink->query ($query);
609 if ($result == NULL or $result->rowCount() != 1)
610 {
611 showError ("SQL query '${query}' failed for table ${tableName}", __FUNCTION__);
612 return FALSE;
613 }
614 return TRUE;
615 }
616
617 function getRackspaceHistory ()
618 {
619 $query =
620 "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 " .
621 "MountOperation as mo inner join RackObject as ro on mo.object_id = ro.id " .
622 "inner join Dictionary on objtype_id = dict_key natural join Chapter " .
623 "where chapter_name = 'RackObjectType' order by ctime desc";
624 $result = useSelectBlade ($query);
625 $ret = $result->fetchAll(PDO::FETCH_ASSOC);
626 $result->closeCursor();
627 return $ret;
628 }
629
630 // This function is used in renderRackspaceHistory()
631 function getOperationMolecules ($op_id = 0)
632 {
633 if ($op_id <= 0)
634 {
635 showError ("Missing argument", __FUNCTION__);
636 return;
637 }
638 $query = "select old_molecule_id, new_molecule_id from MountOperation where id = ${op_id}";
639 $result = useSelectBlade ($query);
640 // We expect one row.
641 $row = $result->fetch (PDO::FETCH_ASSOC);
642 if ($row == NULL)
643 {
644 showError ("SQL query succeded, but returned no results.", __FUNCTION__);
645 return;
646 }
647 $omid = $row['old_molecule_id'];
648 $nmid = $row['new_molecule_id'];
649 $result->closeCursor();
650 return array ($omid, $nmid);
651 }
652
653 function getResidentRacksData ($object_id = 0, $fetch_rackdata = TRUE)
654 {
655 if ($object_id <= 0)
656 {
657 showError ('Invalid object_id', __FUNCTION__);
658 return;
659 }
660 $query = "select distinct rack_id from RackSpace where object_id = ${object_id} order by rack_id";
661 $result = useSelectBlade ($query);
662 $rows = $result->fetchAll (PDO::FETCH_NUM);
663 $result->closeCursor();
664 $ret = array();
665 foreach ($rows as $row)
666 {
667 if (!$fetch_rackdata)
668 {
669 $ret[$row[0]] = $row[0];
670 continue;
671 }
672 $rackData = getRackData ($row[0]);
673 if ($rackData == NULL)
674 {
675 showError ('getRackData() failed', __FUNCTION__);
676 return NULL;
677 }
678 $ret[$row[0]] = $rackData;
679 }
680 $result->closeCursor();
681 return $ret;
682 }
683
684 function getObjectGroupInfo ()
685 {
686 $query =
687 'select dict_key as id, dict_value as name, count(id) as count from ' .
688 'Dictionary natural join Chapter left join RackObject on dict_key = objtype_id ' .
689 'where chapter_name = "RackObjectType" ' .
690 'group by dict_key order by dict_value';
691 $result = useSelectBlade ($query);
692 $ret = array();
693 $ret[0] = array ('id' => 0, 'name' => 'ALL types');
694 $clist = array ('id', 'name', 'count');
695 $total = 0;
696 while ($row = $result->fetch (PDO::FETCH_ASSOC))
697 if ($row['count'] > 0)
698 {
699 $total += $row['count'];
700 foreach ($clist as $cname)
701 $ret[$row['id']][$cname] = $row[$cname];
702 }
703 $result->closeCursor();
704 $ret[0]['count'] = $total;
705 return $ret;
706 }
707
708 // This function returns objects, which have no rackspace assigned to them.
709 // Additionally it keeps rack_id parameter, so we can silently pre-select
710 // the rack required.
711 function getUnmountedObjects ()
712 {
713 $query =
714 'select dict_value as objtype_name, dict_key as objtype_id, name, label, barcode, id, asset_no from ' .
715 'RackObject inner join Dictionary on objtype_id = dict_key natural join Chapter ' .
716 'left join RackSpace on id = object_id '.
717 'where rack_id is null and chapter_name = "RackObjectType" order by dict_value, name, label, asset_no, barcode';
718 $result = useSelectBlade ($query);
719 $ret = array();
720 $clist = array ('id', 'name', 'label', 'barcode', 'objtype_name', 'objtype_id', 'asset_no');
721 while ($row = $result->fetch (PDO::FETCH_ASSOC))
722 {
723 foreach ($clist as $cname)
724 $ret[$row['id']][$cname] = $row[$cname];
725 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
726 }
727 $result->closeCursor();
728 return $ret;
729 }
730
731 function getProblematicObjects ()
732 {
733 $query =
734 'select dict_value as objtype_name, dict_key as objtype_id, name, id, asset_no from ' .
735 'RackObject inner join Dictionary on objtype_id = dict_key natural join Chapter '.
736 'where has_problems = "yes" and chapter_name = "RackObjectType" order by objtype_name, name';
737 $result = useSelectBlade ($query);
738 $ret = array();
739 $clist = array ('id', 'name', 'objtype_name', 'objtype_id', 'asset_no');
740 while ($row = $result->fetch (PDO::FETCH_ASSOC))
741 {
742 foreach ($clist as $cname)
743 $ret[$row['id']][$cname] = $row[$cname];
744 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
745 }
746 $result->closeCursor();
747 return $ret;
748 }
749
750 function commitAddPort ($object_id = 0, $port_name, $port_type_id, $port_label, $port_l2address)
751 {
752 if ($object_id <= 0)
753 {
754 showError ('Invalid object_id', __FUNCTION__);
755 return;
756 }
757 $port_l2address = l2addressForDatabase ($port_l2address);
758 $result = useInsertBlade
759 (
760 'Port',
761 array
762 (
763 'name' => "'${port_name}'",
764 'object_id' => "'${object_id}'",
765 'label' => "'${port_label}'",
766 'type' => "'${port_type_id}'",
767 'l2address' => "${port_l2address}"
768 )
769 );
770 if ($result)
771 return '';
772 else
773 return 'SQL query failed';
774 }
775
776 function commitUpdatePort ($port_id, $port_name, $port_label, $port_l2address, $port_reservation_comment)
777 {
778 global $dbxlink;
779 $port_l2address = l2addressForDatabase ($port_l2address);
780 $query =
781 "update Port set name='$port_name', label='$port_label', " .
782 "reservation_comment = ${port_reservation_comment}, l2address=${port_l2address} " .
783 "where id='$port_id'";
784 $result = $dbxlink->exec ($query);
785 if ($result == 1)
786 return '';
787 $errorInfo = $dbxlink->errorInfo();
788 // We could update nothing.
789 if ($errorInfo[0] == '00000')
790 return '';
791 return $errorInfo[2];
792 }
793
794 function delObjectPort ($port_id)
795 {
796 if (unlinkPort ($port_id) != '')
797 return __FUNCTION__ . ': unlinkPort() failed';
798 if (useDeleteBlade ('Port', 'id', $port_id) != TRUE)
799 return __FUNCTION__ . ': useDeleteBlade() failed';
800 return '';
801 }
802
803 function getObjectAddressesAndNames ()
804 {
805 $query =
806 "select object_id as object_id, ".
807 "RackObject.name as object_name, ".
808 "IPBonds.name as name, ".
809 "INET_NTOA(ip) as ip ".
810 "from IPBonds join RackObject on id=object_id ";
811 $result = useSelectBlade ($query);
812 $ret = array();
813 $count=0;
814 while ($row = $result->fetch (PDO::FETCH_ASSOC))
815 {
816 $ret[$count]['object_id']=$row['object_id'];
817 $ret[$count]['object_name']=$row['object_name'];
818 $ret[$count]['name']=$row['name'];
819 $ret[$count]['ip']=$row['ip'];
820 $count++;
821 }
822 $result->closeCursor();
823 return $ret;
824 }
825
826
827 function getEmptyPortsOfType ($type_id)
828 {
829 $query =
830 "select distinct Port.id as Port_id, ".
831 "Port.object_id as Port_object_id, ".
832 "RackObject.name as Object_name, ".
833 "Port.name as Port_name, ".
834 "Port.type as Port_type_id, ".
835 "dict_value as Port_type_name ".
836 "from ( ".
837 " ( ".
838 " Port inner join Dictionary on Port.type = dict_key natural join Chapter ".
839 " ) ".
840 " join RackObject on Port.object_id = RackObject.id ".
841 ") ".
842 "left join Link on Port.id=Link.porta or Port.id=Link.portb ".
843 "inner join PortCompat on Port.type = PortCompat.type2 ".
844 "where chapter_name = 'PortType' and PortCompat.type1 = '$type_id' and Link.porta is NULL ".
845 "and Port.reservation_comment is null order by Object_name, Port_name";
846 $result = useSelectBlade ($query);
847 $ret = array();
848 $count=0;
849 while ($row = $result->fetch (PDO::FETCH_ASSOC))
850 {
851 $ret[$count]['Port_id']=$row['Port_id'];
852 $ret[$count]['Port_object_id']=$row['Port_object_id'];
853 $ret[$count]['Object_name']=$row['Object_name'];
854 $ret[$count]['Port_name']=$row['Port_name'];
855 $ret[$count]['Port_type_id']=$row['Port_type_id'];
856 $ret[$count]['Port_type_name']=$row['Port_type_name'];
857 $count++;
858 }
859 $result->closeCursor();
860 return $ret;
861 }
862
863 function linkPorts ($porta, $portb)
864 {
865 if ($porta == $portb)
866 return "Ports can't be the same";
867 if ($porta > $portb)
868 {
869 $tmp = $porta;
870 $porta = $portb;
871 $portb = $tmp;
872 }
873 global $dbxlink;
874 $query1 = "insert into Link set porta='${porta}', portb='{$portb}'";
875 $query2 = "update Port set reservation_comment = NULL where id = ${porta} or id = ${portb} limit 2";
876 // FIXME: who cares about the return value?
877 $result = $dbxlink->exec ($query1);
878 $result = $dbxlink->exec ($query2);
879 return '';
880
881 }
882
883 function unlinkPort ($port)
884 {
885 global $dbxlink;
886 $query =
887 "delete from Link where porta='$port' or portb='$port'";
888 $result = $dbxlink->exec ($query);
889 return '';
890
891 }
892
893 // FIXME: after falling back to using existing getObjectInfo we don't
894 // need that large query. Shrink it some later.
895 function getObjectAddresses ($object_id = 0)
896 {
897 if ($object_id == 0)
898 {
899 showError ('Invalid object_id', __FUNCTION__);
900 return;
901 }
902 $query =
903 "select ".
904 "IPAddress.name as IPAddress_name, ".
905 "IPAddress.reserved as IPAddress_reserved, ".
906 "IPBonds.name as IPBonds_name, ".
907 "INET_NTOA(IPBonds.ip) as IPBonds_ip, ".
908 "IPBonds.type as IPBonds_type, ".
909 "RemoteBonds.name as RemoteBonds_name, ".
910 "RemoteBonds.type as RemoteBonds_type, ".
911 "RemoteBonds.object_id as RemoteBonds_object_id, ".
912 "RemoteObject.name as RemoteObject_name from IPBonds " .
913 "left join IPBonds as RemoteBonds on IPBonds.ip=RemoteBonds.ip " .
914 "and IPBonds.object_id!=RemoteBonds.object_id " .
915 "left join IPAddress on IPBonds.ip=IPAddress.ip " .
916 "left join RackObject as RemoteObject on RemoteBonds.object_id=RemoteObject.id ".
917 "where ".
918 "IPBonds.object_id = ${object_id} ".
919 "order by IPBonds.ip, RemoteObject.name";
920 $result = useSelectBlade ($query);
921 $ret=array();
922 $count=0;
923 $refcount=0;
924 $prev_ip = 0;
925 // We are going to call getObjectInfo() for some rows,
926 // hence the connector must be unloaded from the
927 // current data.
928 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
929 $result->closeCursor();
930 foreach ($rows as $row)
931 {
932 if ($prev_ip != $row['IPBonds_ip'])
933 {
934 $count++;
935 $refcount=0;
936 $prev_ip = $row['IPBonds_ip'];
937 $ret[$count]['address_name'] = $row['IPAddress_name'];
938 $ret[$count]['address_reserved'] = $row['IPAddress_reserved'];
939 $ret[$count]['ip'] = $row['IPBonds_ip'];
940 $ret[$count]['name'] = $row['IPBonds_name'];
941 $ret[$count]['type'] = $row['IPBonds_type'];
942 $ret[$count]['references'] = array();
943 }
944
945 if ($row['RemoteBonds_type'])
946 {
947 $ret[$count]['references'][$refcount]['type'] = $row['RemoteBonds_type'];
948 $ret[$count]['references'][$refcount]['name'] = $row['RemoteBonds_name'];
949 $ret[$count]['references'][$refcount]['object_id'] = $row['RemoteBonds_object_id'];
950 if (empty ($row['RemoteBonds_object_id']))
951 $ret[$count]['references'][$refcount]['object_name'] = $row['RemoteObject_name'];
952 else
953 {
954 $oi = getObjectInfo ($row['RemoteBonds_object_id']);
955 $ret[$count]['references'][$refcount]['object_name'] = displayedName ($oi);
956 }
957 $refcount++;
958 }
959 }
960 return $ret;
961 }
962
963 function getAddressspaceList ($tagfilter = array())
964 {
965 $whereclause = getWhereClause ($tagfilter);
966 $query =
967 "select distinct ".
968 "id as IPRanges_id, ".
969 "INET_NTOA(ip) as IPRanges_ip, ".
970 "mask as IPRanges_mask, ".
971 "name as IPRanges_name ".
972 "from IPRanges left join TagStorage on IPRanges.id = TagStorage.target_id and target_realm = 'ipv4net' " .
973 "where true ${whereclause} " .
974 " order by ip";
975 $result = useSelectBlade ($query);
976 $ret=array();
977 $count=0;
978 while ($row = $result->fetch (PDO::FETCH_ASSOC))
979 {
980 $ret[$count]['id'] = $row['IPRanges_id'];
981 $ret[$count]['ip'] = $row['IPRanges_ip'];
982 $ret[$count]['ip_bin'] = ip2long($row['IPRanges_ip']);
983 $ret[$count]['name'] = $row['IPRanges_name'];
984 $ret[$count]['mask'] = $row['IPRanges_mask'];
985 $ret[$count]['mask_bin'] = binMaskFromDec($row['IPRanges_mask']);
986 $ret[$count]['mask_bin_inv'] = binInvMaskFromDec($row['IPRanges_mask']);
987 $count++;
988 }
989 $result->closeCursor();
990 return $ret;
991
992 }
993
994 function getRangeByIp ($ip = '', $id = 0)
995 {
996 if ($id == 0)
997 $query =
998 "select ".
999 "id, INET_NTOA(ip) as ip, mask, name ".
1000 "from IPRanges ";
1001 else
1002 $query =
1003 "select ".
1004 "id, INET_NTOA(ip) as ip, mask, name ".
1005 "from IPRanges where id='$id'";
1006
1007 $result = useSelectBlade ($query);
1008 $ret=array();
1009 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1010 {
1011 $binmask=binMaskFromDec($row['mask']);
1012 if ((ip2long($ip) & $binmask) == ip2long($row['ip']))
1013 {
1014 $ret['id'] = $row['id'];
1015 $ret['ip'] = $row['ip'];
1016 $ret['ip_bin'] = ip2long($row['ip']);
1017 $ret['name'] = $row['name'];
1018 $ret['mask'] = $row['mask'];
1019 $result->closeCursor();
1020 return $ret;
1021 }
1022 }
1023 $result->closeCursor();
1024 return NULL;
1025 }
1026
1027 function updateRange ($id=0, $name='')
1028 {
1029 global $dbxlink;
1030 $query =
1031 "update IPRanges set name='$name' where id='$id'";
1032 $result = $dbxlink->exec ($query);
1033 return '';
1034
1035 }
1036
1037 // This function is actually used not only to update, but also to create records,
1038 // that's why ON DUPLICATE KEY UPDATE was replaced by DELETE-INSERT pair
1039 // (MySQL 4.0 workaround).
1040 function updateAddress ($ip=0, $name='', $reserved='no')
1041 {
1042 // DELETE may safely fail.
1043 $r = useDeleteBlade ('IPAddress', 'ip', "INET_ATON('${ip}')", FALSE);
1044 // INSERT may appear not necessary.
1045 if ($name == '' and $reserved == 'no')
1046 return '';
1047 if (useInsertBlade ('IPAddress', array ('name' => "'${name}'", 'reserved' => "'${reserved}'", 'ip' => "INET_ATON('${ip}')")))
1048 return '';
1049 else
1050 return 'useInsertBlade() failed in updateAddress()';
1051 }
1052
1053 // FIXME: This function doesn't wipe relevant records from IPAddress table.
1054 function commitDeleteRange ($id = 0)
1055 {
1056 if ($id <= 0)
1057 return __FUNCTION__ . ': Invalid range ID';
1058 if (!useDeleteBlade ('IPRanges', 'id', $id, FALSE))
1059 return __FUNCTION__ . ': SQL query #1 failed';
1060 if (!deleteTagsForEntity ('ipv4net', $id))
1061 return __FUNCTION__ . ': SQL query #2 failed';
1062 return '';
1063 }
1064
1065 function updateBond ($ip='', $object_id=0, $name='', $type='')
1066 {
1067 global $dbxlink;
1068
1069 $query =
1070 "update IPBonds set name='$name', type='$type' where ip=INET_ATON('$ip') and object_id='$object_id'";
1071 $result = $dbxlink->exec ($query);
1072 return '';
1073 }
1074
1075 function unbindIpFromObject ($ip='', $object_id=0)
1076 {
1077 global $dbxlink;
1078
1079 $query =
1080 "delete from IPBonds where ip=INET_ATON('$ip') and object_id='$object_id'";
1081 $result = $dbxlink->exec ($query);
1082 return '';
1083 }
1084
1085 // This function returns either all or one user account. Array key is user name.
1086 function getUserAccounts ()
1087 {
1088 $query =
1089 'select user_id, user_name, user_password_hash, user_realname, user_enabled ' .
1090 'from UserAccount order by user_name';
1091 $result = useSelectBlade ($query);
1092 $ret = array();
1093 $clist = array ('user_id', 'user_name', 'user_realname', 'user_password_hash', 'user_enabled');
1094 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1095 foreach ($clist as $cname)
1096 $ret[$row['user_name']][$cname] = $row[$cname];
1097 $result->closeCursor();
1098 return $ret;
1099 }
1100
1101 // This function returns permission array for all user accounts. Array key is user name.
1102 function getUserPermissions ()
1103 {
1104 $query =
1105 "select UserPermission.user_id, user_name, page, tab, access from " .
1106 "UserPermission natural left join UserAccount where (user_name is not null) or " .
1107 "(user_name is null and UserPermission.user_id = 0) order by user_name, page, tab";
1108 $result = useSelectBlade ($query);
1109 $ret = array();
1110 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1111 {
1112 if ($row['user_id'] == 0)
1113 $row['user_name'] = '%';
1114 $ret[$row['user_name']][$row['page']][$row['tab']] = $row['access'];
1115 }
1116 $result->closeCursor();
1117 return $ret;
1118 }
1119
1120 function searchByl2address ($l2addr)
1121 {
1122 $l2addr = l2addressForDatabase ($l2addr);
1123 $query = "select object_id, Port.id as port_id from RackObject as ro inner join Port on ro.id = Port.object_id " .
1124 "where l2address = ${l2addr}";
1125 $result = useSelectBlade ($query);
1126 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
1127 $result->closeCursor();
1128 if (count ($rows) == 0) // No results.
1129 return NULL;
1130 if (count ($rows) == 1) // Target found.
1131 return $rows[0];
1132 showError ('More than one results was found. This is probably a broken unique key.', __FUNCTION__);
1133 return NULL;
1134 }
1135
1136 function getIPv4PrefixSearchResult ($terms)
1137 {
1138 $query = "select id, inet_ntoa(ip) as ip, mask, name from IPRanges where ";
1139 $or = '';
1140 foreach (explode (' ', $terms) as $term)
1141 {
1142 $query .= $or . "name like '%${term}%'";
1143 $or = ' or ';
1144 }
1145 $result = useSelectBlade ($query);
1146 $ret = array();
1147 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1148 $ret[] = $row;
1149 return $ret;
1150 }
1151
1152 function getIPv4AddressSearchResult ($terms)
1153 {
1154 $query = "select inet_ntoa(ip) as ip, name from IPAddress where ";
1155 $or = '';
1156 foreach (explode (' ', $terms) as $term)
1157 {
1158 $query .= $or . "name like '%${term}%'";
1159 $or = ' or ';
1160 }
1161 $result = useSelectBlade ($query);
1162 $ret = array();
1163 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1164 $ret[] = $row;
1165 return $ret;
1166 }
1167
1168 function getIPv4RSPoolSearchResult ($terms)
1169 {
1170 $query = "select id as pool_id, name from IPRSPool where ";
1171 $or = '';
1172 foreach (explode (' ', $terms) as $term)
1173 {
1174 $query .= $or . "name like '%${term}%'";
1175 $or = ' or ';
1176 }
1177 $result = useSelectBlade ($query);
1178 $ret = array();
1179 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1180 $ret[] = $row;
1181 return $ret;
1182 }
1183
1184 function getIPv4VServiceSearchResult ($terms)
1185 {
1186 $query = "select id, inet_ntoa(vip) as vip, vport, proto, name from IPVirtualService where ";
1187 $or = '';
1188 foreach (explode (' ', $terms) as $term)
1189 {
1190 $query .= $or . "name like '%${term}%'";
1191 $or = ' or ';
1192 }
1193 $result = useSelectBlade ($query);
1194 $ret = array();
1195 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1196 $ret[] = $row;
1197 return $ret;
1198 }
1199
1200 // This function returns either port ID or NULL for specified arguments.
1201 function getPortID ($object_id, $port_name)
1202 {
1203 $query = "select id from Port where object_id=${object_id} and name='${port_name}' limit 2";
1204 $result = useSelectBlade ($query);
1205 $rows = $result->fetchAll (PDO::FETCH_NUM);
1206 if (count ($rows) != 1)
1207 return NULL;
1208 $ret = $rows[0][0];
1209 $result->closeCursor();
1210 return $ret;
1211 }
1212
1213 function commitCreateUserAccount ($username, $realname, $password)
1214 {
1215 return useInsertBlade
1216 (
1217 'UserAccount',
1218 array
1219 (
1220 'user_name' => "'${username}'",
1221 'user_realname' => "'${realname}'",
1222 'user_password_hash' => "'${password}'"
1223 )
1224 );
1225 }
1226
1227 function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
1228 {
1229 global $dbxlink;
1230 $query =
1231 "update UserAccount set user_name = '${new_username}', user_realname = '${new_realname}', " .
1232 "user_password_hash = '${new_password}' where user_id = ${id} limit 1";
1233 $result = $dbxlink->query ($query);
1234 if ($result == NULL)
1235 {
1236 showError ('SQL query failed', __FUNCTION__);
1237 die;
1238 }
1239 return TRUE;
1240 }
1241
1242 function commitEnableUserAccount ($id, $new_enabled_value)
1243 {
1244 global $dbxlink;
1245 $query =
1246 "update UserAccount set user_enabled = '${new_enabled_value}' " .
1247 "where user_id = ${id} limit 1";
1248 $result = $dbxlink->query ($query);
1249 if ($result == NULL)
1250 {
1251 showError ('SQL query failed', __FUNCTION__);
1252 die;
1253 }
1254 return TRUE;
1255 }
1256
1257 function commitGrantPermission ($userid, $page, $tab, $value)
1258 {
1259 return useInsertBlade
1260 (
1261 'UserPermission',
1262 array
1263 (
1264 'user_id' => $userid,
1265 'page' => "'${page}'",
1266 'tab' => "'${tab}'",
1267 'access' => "'${value}'"
1268 )
1269 );
1270 }
1271
1272 function commitRevokePermission ($userid, $page, $tab)
1273 {
1274 global $dbxlink;
1275 $query =
1276 "delete from UserPermission where user_id = '${userid}' and page = '${page}' " .
1277 "and tab = '$tab' limit 1";
1278 $result = $dbxlink->query ($query);
1279 if ($result == NULL)
1280 {
1281 showError ('SQL query failed', __FUNCTION__);
1282 die;
1283 }
1284 return TRUE;
1285 }
1286
1287 // This function returns an array of all port type pairs from PortCompat table.
1288 function getPortCompat ()
1289 {
1290 $query =
1291 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
1292 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
1293 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
1294 "inner join Chapter as c1 on d1.chapter_no = c1.chapter_no " .
1295 "inner join Chapter as c2 on d2.chapter_no = c2.chapter_no " .
1296 "where c1.chapter_name = 'PortType' and c2.chapter_name = 'PortType'";
1297 $result = useSelectBlade ($query);
1298 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
1299 $result->closeCursor();
1300 return $ret;
1301 }
1302
1303 function removePortCompat ($type1 = 0, $type2 = 0)
1304 {
1305 global $dbxlink;
1306 if ($type1 == 0 or $type2 == 0)
1307 {
1308 showError ('Invalid arguments', __FUNCTION__);
1309 die;
1310 }
1311 $query = "delete from PortCompat where type1 = ${type1} and type2 = ${type2} limit 1";
1312 $result = $dbxlink->query ($query);
1313 if ($result == NULL)
1314 {
1315 showError ('SQL query failed', __FUNCTION__);
1316 die;
1317 }
1318 return TRUE;
1319 }
1320
1321 function addPortCompat ($type1 = 0, $type2 = 0)
1322 {
1323 if ($type1 <= 0 or $type2 <= 0)
1324 {
1325 showError ('Invalid arguments', __FUNCTION__);
1326 die;
1327 }
1328 return useInsertBlade
1329 (
1330 'PortCompat',
1331 array ('type1' => $type1, 'type2' => $type2)
1332 );
1333 }
1334
1335 // This function returns the dictionary as an array of trees, each tree
1336 // representing a single chapter. Each element has 'id', 'name', 'sticky'
1337 // and 'word' keys with the latter holding all the words within the chapter.
1338 function getDict ($parse_links = FALSE)
1339 {
1340 $query1 =
1341 "select chapter_name, Chapter.chapter_no, dict_key, dict_value, sticky from " .
1342 "Chapter natural left join Dictionary order by chapter_name, dict_value";
1343 $result = useSelectBlade ($query1);
1344 $dict = array();
1345 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1346 {
1347 $chapter_no = $row['chapter_no'];
1348 if (!isset ($dict[$chapter_no]))
1349 {
1350 $dict[$chapter_no]['no'] = $chapter_no;
1351 $dict[$chapter_no]['name'] = $row['chapter_name'];
1352 $dict[$chapter_no]['sticky'] = $row['sticky'] == 'yes' ? TRUE : FALSE;
1353 $dict[$chapter_no]['word'] = array();
1354 }
1355 if ($row['dict_key'] != NULL)
1356 {
1357 $dict[$chapter_no]['word'][$row['dict_key']] = $parse_links ?
1358 parseWikiLink ($row['dict_value'], 'a') : $row['dict_value'];
1359 $dict[$chapter_no]['refcnt'][$row['dict_key']] = 0;
1360 }
1361 }
1362 $result->closeCursor();
1363 unset ($result);
1364 // Find the list of all assigned values of dictionary-addressed attributes, each with
1365 // chapter/word keyed reference counters. Use the structure to adjust reference counters
1366 // of the returned disctionary words.
1367 $query2 = "select a.attr_id, am.chapter_no, uint_value, count(object_id) as refcnt " .
1368 "from Attribute as a inner join AttributeMap as am on a.attr_id = am.attr_id " .
1369 "inner join AttributeValue as av on a.attr_id = av.attr_id " .
1370 "inner join Dictionary as d on am.chapter_no = d.chapter_no and av.uint_value = d.dict_key " .
1371 "where attr_type = 'dict' group by a.attr_id, am.chapter_no, uint_value " .
1372 "order by a.attr_id, am.chapter_no, uint_value";
1373 $result = useSelectBlade ($query2);
1374 $refcnt = array();
1375 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1376 $dict[$row['chapter_no']]['refcnt'][$row['uint_value']] = $row['refcnt'];
1377 $result->closeCursor();
1378 return $dict;
1379 }
1380
1381 function getDictStats ()
1382 {
1383 $stock_chapters = array (1, 2, 3, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23);
1384 $query =
1385 "select Chapter.chapter_no, chapter_name, count(dict_key) as wc from " .
1386 "Chapter natural left join Dictionary group by Chapter.chapter_no";
1387 $result = useSelectBlade ($query);
1388 $tc = $tw = $uc = $uw = 0;
1389 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1390 {
1391 $tc++;
1392 $tw += $row['wc'];;
1393 if (in_array ($row['chapter_no'], $stock_chapters))
1394 continue;
1395 $uc++;
1396 $uw += $row['wc'];;
1397 }
1398 $result->closeCursor();
1399 unset ($result);
1400 $query = "select count(attr_id) as attrc from RackObject as ro left join " .
1401 "AttributeValue as av on ro.id = av.object_id group by ro.id";
1402 $result = useSelectBlade ($query);
1403 $to = $ta = $so = 0;
1404 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1405 {
1406 $to++;
1407 if ($row['attrc'] != 0)
1408 {
1409 $so++;
1410 $ta += $row['attrc'];
1411 }
1412 }
1413 $result->closeCursor();
1414 $ret = array();
1415 $ret['Total chapters in dictionary'] = $tc;
1416 $ret['Total words in dictionary'] = $tw;
1417 $ret['User chapters'] = $uc;
1418 $ret['Words in user chapters'] = $uw;
1419 $ret['Total objects'] = $to;
1420 $ret['Objects with stickers'] = $so;
1421 $ret['Total stickers attached'] = $ta;
1422 return $ret;
1423 }
1424
1425 function getIPv4Stats()
1426 {
1427 $ret = array();
1428 $subject = array();
1429 $subject[] = array ('q' => 'select count(id) from IPRanges', 'txt' => 'Networks');
1430 $subject[] = array ('q' => 'select count(ip) from IPAddress', 'txt' => 'Addresses commented/reserved');
1431 $subject[] = array ('q' => 'select count(ip) from IPBonds', 'txt' => 'Addresses allocated');
1432 $subject[] = array ('q' => 'select count(*) from PortForwarding', 'txt' => 'NAT rules');
1433 $subject[] = array ('q' => 'select count(id) from IPVirtualService', 'txt' => 'Virtual services');
1434 $subject[] = array ('q' => 'select count(id) from IPRSPool', 'txt' => 'Real server pools');
1435 $subject[] = array ('q' => 'select count(id) from IPRealServer', 'txt' => 'Real servers');
1436 $subject[] = array ('q' => 'select count(distinct object_id) from IPLoadBalancer', 'txt' => 'Load balancers');
1437
1438 foreach ($subject as $item)
1439 {
1440 $result = useSelectBlade ($item['q']);
1441 $row = $result->fetch (PDO::FETCH_NUM);
1442 $ret[$item['txt']] = $row[0];
1443 $result->closeCursor();
1444 unset ($result);
1445 }
1446 return $ret;
1447 }
1448
1449 function getRackspaceStats()
1450 {
1451 $ret = array();
1452 $subject = array();
1453 $subject[] = array ('q' => 'select count(*) from Dictionary where chapter_no = 3', 'txt' => 'Rack rows');
1454 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
1455 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
1456 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
1457
1458 foreach ($subject as $item)
1459 {
1460 $result = useSelectBlade ($item['q']);
1461 $row = $result->fetch (PDO::FETCH_NUM);
1462 $ret[$item['txt']] = empty ($row[0]) ? 0 : $row[0];
1463 $result->closeCursor();
1464 unset ($result);
1465 }
1466 return $ret;
1467 }
1468
1469 function getTagStats ()
1470 {
1471 $ret = array();
1472 $query = "select tag, count(tag_id) as refcnt from " .
1473 "TagTree inner join TagStorage on TagTree.id = TagStorage.tag_id " .
1474 "group by tag_id order by refcnt desc";
1475 $result = useSelectBlade ($query);
1476 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1477 $ret[$row['tag']] = $row['refcnt'];
1478 $result->closeCursor();
1479 return $ret;
1480 }
1481
1482 function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1483 {
1484 if ($chapter_no <= 0 or $dict_key <= 0 or empty ($dict_value))
1485 {
1486 showError ('Invalid args', __FUNCTION__);
1487 die;
1488 }
1489 global $dbxlink;
1490 $query =
1491 "update Dictionary set dict_value = '${dict_value}' where chapter_no=${chapter_no} " .
1492 "and dict_key=${dict_key} limit 1";
1493 $result = $dbxlink->query ($query);
1494 if ($result == NULL)
1495 {
1496 showError ('SQL query failed', __FUNCTION__);
1497 die;
1498 }
1499 return TRUE;
1500 }
1501
1502 function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1503 {
1504 if ($chapter_no <= 0 or empty ($dict_value))
1505 {
1506 showError ('Invalid args', __FUNCTION__);
1507 die;
1508 }
1509 return useInsertBlade
1510 (
1511 'Dictionary',
1512 array ('chapter_no' => $chapter_no, 'dict_value' => "'${dict_value}'")
1513 );
1514 }
1515
1516 function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1517 {
1518 if ($chapter_no <= 0 or $dict_key <= 0)
1519 {
1520 showError ('Invalid args', __FUNCTION__);
1521 die;
1522 }
1523 global $dbxlink;
1524 $query =
1525 "delete from Dictionary where chapter_no=${chapter_no} " .
1526 "and dict_key=${dict_key} limit 1";
1527 $result = $dbxlink->query ($query);
1528 if ($result == NULL)
1529 {
1530 showError ('SQL query failed', __FUNCTION__);
1531 die;
1532 }
1533 return TRUE;
1534 }
1535
1536 function commitAddChapter ($chapter_name = '')
1537 {
1538 if (empty ($chapter_name))
1539 {
1540 showError ('Invalid args', __FUNCTION__);
1541 die;
1542 }
1543 return useInsertBlade
1544 (
1545 'Chapter',
1546 array ('chapter_name' => "'${chapter_name}'")
1547 );
1548 }
1549
1550 function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
1551 {
1552 if ($chapter_no <= 0 or empty ($chapter_name))
1553 {
1554 showError ('Invalid args', __FUNCTION__);
1555 die;
1556 }
1557 global $dbxlink;
1558 $query =
1559 "update Chapter set chapter_name = '${chapter_name}' where chapter_no = ${chapter_no} " .
1560 "and sticky = 'no' limit 1";
1561 $result = $dbxlink->query ($query);
1562 if ($result == NULL)
1563 {
1564 showError ('SQL query failed', __FUNCTION__);
1565 die;
1566 }
1567 return TRUE;
1568 }
1569
1570 function commitDeleteChapter ($chapter_no = 0)
1571 {
1572 if ($chapter_no <= 0)
1573 {
1574 showError ('Invalid args', __FUNCTION__);
1575 die;
1576 }
1577 global $dbxlink;
1578 $query =
1579 "delete from Chapter where chapter_no = ${chapter_no} and sticky = 'no' limit 1";
1580 $result = $dbxlink->query ($query);
1581 if ($result == NULL)
1582 {
1583 showError ('SQL query failed', __FUNCTION__);
1584 die;
1585 }
1586 return TRUE;
1587 }
1588
1589 // This is a dictionary accessor. We perform link rendering, so the user sees
1590 // nice <select> drop-downs.
1591 function readChapter ($chapter_name = '')
1592 {
1593 if (empty ($chapter_name))
1594 {
1595 showError ('invalid argument', __FUNCTION__);
1596 return NULL;
1597 }
1598 $query =
1599 "select dict_key, dict_value from Dictionary natural join Chapter " .
1600 "where chapter_name = '${chapter_name}'";
1601 $result = useSelectBlade ($query);
1602 $chapter = array();
1603 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1604 $chapter[$row['dict_key']] = parseWikiLink ($row['dict_value'], 'o');
1605 $result->closeCursor();
1606 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
1607 asort ($chapter);
1608 return $chapter;
1609 }
1610
1611 function getAttrMap ()
1612 {
1613 $query =
1614 "select a.attr_id, a.attr_type, a.attr_name, am.objtype_id, " .
1615 "d.dict_value as objtype_name, am.chapter_no, c2.chapter_name from " .
1616 "Attribute as a natural left join AttributeMap as am " .
1617 "left join Dictionary as d on am.objtype_id = d.dict_key " .
1618 "left join Chapter as c1 on d.chapter_no = c1.chapter_no " .
1619 "left join Chapter as c2 on am.chapter_no = c2.chapter_no " .
1620 "where c1.chapter_name = 'RackObjectType' or c1.chapter_name is null " .
1621 "order by attr_name";
1622 $result = useSelectBlade ($query);
1623 $ret = array();
1624 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1625 {
1626 $attr_id = $row['attr_id'];
1627 if (!isset ($ret[$attr_id]))
1628 {
1629 $ret[$attr_id]['id'] = $attr_id;
1630 $ret[$attr_id]['type'] = $row['attr_type'];
1631 $ret[$attr_id]['name'] = $row['attr_name'];
1632 $ret[$attr_id]['application'] = array();
1633 }
1634 if ($row['objtype_id'] == '')
1635 continue;
1636 $application['objtype_id'] = $row['objtype_id'];
1637 $application['objtype_name'] = $row['objtype_name'];
1638 if ($row['attr_type'] == 'dict')
1639 {
1640 $application['chapter_no'] = $row['chapter_no'];
1641 $application['chapter_name'] = $row['chapter_name'];
1642 }
1643 $ret[$attr_id]['application'][] = $application;
1644 }
1645 $result->closeCursor();
1646 return $ret;
1647 }
1648
1649 function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
1650 {
1651 if ($attr_id <= 0 or empty ($attr_name))
1652 {
1653 showError ('Invalid args', __FUNCTION__);
1654 die;
1655 }
1656 global $dbxlink;
1657 $query =
1658 "update Attribute set attr_name = '${attr_name}' " .
1659 "where attr_id = ${attr_id} limit 1";
1660 $result = $dbxlink->query ($query);
1661 if ($result == NULL)
1662 {
1663 showError ("SQL query '${query}' failed", __FUNCTION__);
1664 die;
1665 }
1666 return TRUE;
1667 }
1668
1669 function commitAddAttribute ($attr_name = '', $attr_type = '')
1670 {
1671 if (empty ($attr_name))
1672 {
1673 showError ('Invalid args', __FUNCTION__);
1674 die;
1675 }
1676 switch ($attr_type)
1677 {
1678 case 'uint':
1679 case 'float':
1680 case 'string':
1681 case 'dict':
1682 break;
1683 default:
1684 showError ('Invalid args', __FUNCTION__);
1685 die;
1686 }
1687 return useInsertBlade
1688 (
1689 'Attribute',
1690 array ('attr_name' => "'${attr_name}'", 'attr_type' => "'${attr_type}'")
1691 );
1692 }
1693
1694 function commitDeleteAttribute ($attr_id = 0)
1695 {
1696 if ($attr_id <= 0)
1697 {
1698 showError ('Invalid args', __FUNCTION__);
1699 die;
1700 }
1701 return useDeleteBlade ('Attribute', 'attr_id', $attr_id, FALSE);
1702 }
1703
1704 // FIXME: don't store garbage in chapter_no for non-dictionary types.
1705 function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
1706 {
1707 if ($attr_id <= 0 or $objtype_id <= 0 or $chapter_no <= 0)
1708 {
1709 showError ('Invalid args', __FUNCTION__);
1710 die;
1711 }
1712 return useInsertBlade
1713 (
1714 'AttributeMap',
1715 array
1716 (
1717 'attr_id' => $attr_id,
1718 'objtype_id' => $objtype_id,
1719 'chapter_no' => $chapter_no
1720 )
1721 );
1722 }
1723
1724 function commitReduceAttrMap ($attr_id = 0, $objtype_id)
1725 {
1726 if ($attr_id <= 0 or $objtype_id <= 0)
1727 {
1728 showError ('Invalid args', __FUNCTION__);
1729 die;
1730 }
1731 global $dbxlink;
1732 $query =
1733 "delete from AttributeMap where attr_id=${attr_id} " .
1734 "and objtype_id=${objtype_id} limit 1";
1735 $result = $dbxlink->query ($query);
1736 if ($result == NULL)
1737 {
1738 showError ('SQL query failed', __FUNCTION__);
1739 die;
1740 }
1741 return TRUE;
1742 }
1743
1744 // This function returns all optional attributes for requested object
1745 // as an array of records. NULL is returned on error and empty array
1746 // is returned, if there are no attributes found.
1747 function getAttrValues ($object_id, $strip_optgroup = FALSE)
1748 {
1749 if ($object_id <= 0)
1750 {
1751 showError ('Invalid argument', __FUNCTION__);
1752 return NULL;
1753 }
1754 $ret = array();
1755 $query =
1756 "select A.attr_id, A.attr_name, A.attr_type, C.chapter_name, " .
1757 "AV.uint_value, AV.float_value, AV.string_value, D.dict_value from " .
1758 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
1759 "inner join Attribute as A using (attr_id) " .
1760 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
1761 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_no = D.chapter_no " .
1762 "left join Chapter as C on AM.chapter_no = C.chapter_no " .
1763 "where RO.id = ${object_id} order by A.attr_type, A.attr_name";
1764 $result = useSelectBlade ($query);
1765 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1766 {
1767 $record = array();
1768 $record['id'] = $row['attr_id'];
1769 $record['name'] = $row['attr_name'];
1770 $record['type'] = $row['attr_type'];
1771 switch ($row['attr_type'])
1772 {
1773 case 'uint':
1774 case 'float':
1775 case 'string':
1776 $record['value'] = $row[$row['attr_type'] . '_value'];
1777 $record['a_value'] = parseWikiLink ($record['value'], 'a');
1778 break;
1779 case 'dict':
1780 $record['value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'o', $strip_optgroup);
1781 $record['a_value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'a', $strip_optgroup);
1782 $record['chapter_name'] = $row['chapter_name'];
1783 $record['key'] = $row['uint_value'];
1784 break;
1785 default:
1786 $record['value'] = NULL;
1787 break;
1788 }
1789 $ret[$row['attr_id']] = $record;
1790 }
1791 $result->closeCursor();
1792 return $ret;
1793 }
1794
1795 function commitResetAttrValue ($object_id = 0, $attr_id = 0)
1796 {
1797 if ($object_id <= 0 or $attr_id <= 0)
1798 {
1799 showError ('Invalid arguments', __FUNCTION__);
1800 die;
1801 }
1802 global $dbxlink;
1803 $query = "delete from AttributeValue where object_id = ${object_id} and attr_id = ${attr_id} limit 1";
1804 $result = $dbxlink->query ($query);
1805 if ($result == NULL)
1806 {
1807 showError ('SQL query failed', __FUNCTION__);
1808 die;
1809 }
1810 return TRUE;
1811 }
1812
1813 // FIXME: don't share common code with use commitResetAttrValue()
1814 function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
1815 {
1816 if ($object_id <= 0 or $attr_id <= 0)
1817 {
1818 showError ('Invalid arguments', __FUNCTION__);
1819 die;
1820 }
1821 if (empty ($value))
1822 return commitResetAttrValue ($object_id, $attr_id);
1823 global $dbxlink;
1824 $query1 = "select attr_type from Attribute where attr_id = ${attr_id}";
1825 $result = $dbxlink->query ($query1);
1826 if ($result == NULL)
1827 {
1828 showError ('SQL query #1 failed', __FUNCTION__);
1829 die;
1830 }
1831 $row = $result->fetch (PDO::FETCH_NUM);
1832 if ($row == NULL)
1833 {
1834 showError ('SQL query #1 returned no results', __FUNCTION__);
1835 die;
1836 }
1837 $attr_type = $row[0];
1838 $result->closeCursor();
1839 switch ($attr_type)
1840 {
1841 case 'uint':
1842 case 'float':
1843 case 'string':
1844 $column = $attr_type . '_value';
1845 break;
1846 case 'dict':
1847 $column = 'uint_value';
1848 break;
1849 default:
1850 showError ("Unknown attribute type '${attr_type}' met", __FUNCTION__);
1851 die;
1852 }
1853 $query2 =
1854 "delete from AttributeValue where " .
1855 "object_id = ${object_id} and attr_id = ${attr_id} limit 1";
1856 $result = $dbxlink->query ($query2);
1857 if ($result == NULL)
1858 {
1859 showError ('SQL query #2 failed', __FUNCTION__);
1860 die;
1861 }
1862 // We know $value isn't empty here.
1863 $query3 =
1864 "insert into AttributeValue set ${column} = '${value}', " .
1865 "object_id = ${object_id}, attr_id = ${attr_id} ";
1866 $result = $dbxlink->query ($query3);
1867 if ($result == NULL)
1868 {
1869 showError ('SQL query #3 failed', __FUNCTION__);
1870 die;
1871 }
1872 return TRUE;
1873 }
1874
1875 function commitUseupPort ($port_id = 0)
1876 {
1877 if ($port_id <= 0)
1878 {
1879 showError ("Invalid argument", __FUNCTION__);
1880 die;
1881 }
1882 global $dbxlink;
1883 $query = "update Port set reservation_comment = NULL where id = ${port_id} limit 1";
1884 $result = $dbxlink->exec ($query);
1885 if ($result == NULL)
1886 {
1887 showError ("SQL query failed", __FUNCTION__);
1888 die;
1889 }
1890 return TRUE;
1891
1892 }
1893
1894 // This is a swiss-knife blade to insert a record into a table.
1895 // The first argument is table name.
1896 // The second argument is an array of "name" => "value" pairs.
1897 // The function returns either TRUE or FALSE (we expect one row
1898 // to be inserted).
1899 function useInsertBlade ($tablename, $values)
1900 {
1901 global $dbxlink;
1902 $namelist = $valuelist = '';
1903 foreach ($values as $name => $value)
1904 {
1905 $namelist = $namelist . ($namelist == '' ? "(${name}" : ", ${name}");
1906 $valuelist = $valuelist . ($valuelist == '' ? "(${value}" : ", ${value}");
1907 }
1908 $query = "insert into ${tablename} ${namelist}) values ${valuelist})";
1909 $result = $dbxlink->exec ($query);
1910 if ($result != 1)
1911 return FALSE;
1912 return TRUE;
1913 }
1914
1915 // This swiss-knife blade deletes one record from the specified table
1916 // using the specified key name and value.
1917 function useDeleteBlade ($tablename, $keyname, $keyvalue, $quotekey = TRUE, $deleteall = FALSE)
1918 {
1919 global $dbxlink;
1920 if ($quotekey == TRUE)
1921 $keyvalue = "'${keyvalue}'";
1922 $query = "delete from ${tablename} where ${keyname}=$keyvalue";
1923 if (!$deleteall)
1924 $query .= ' limit 1';
1925 $result = $dbxlink->exec ($query);
1926 if ($result === NULL)
1927 return FALSE;
1928 elseif (!$deleteall && $result != 1)
1929 return FALSE;
1930 else
1931 return TRUE;
1932 }
1933
1934 function useSelectBlade ($query, $caller = 'N/A')
1935 {
1936 global $dbxlink;
1937 $result = $dbxlink->query ($query);
1938 if ($result == NULL)
1939 {
1940 $ei = $dbxlink->errorInfo();
1941 showError ("SQL query '${query}' failed in useSelectBlade with error ${ei[1]} (${ei[2]})", $caller);
1942 return NULL;
1943 }
1944 return $result;
1945 }
1946
1947 function loadConfigCache ()
1948 {
1949 $query = 'SELECT varname, varvalue, vartype, is_hidden, emptyok, description FROM Config ORDER BY varname';
1950 $result = useSelectBlade ($query);
1951 $cache = array();
1952 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1953 $cache[$row['varname']] = $row;
1954 $result->closeCursor();
1955 return $cache;
1956 }
1957
1958 // setConfigVar() is expected to perform all necessary filtering
1959 function storeConfigVar ($varname = NULL, $varvalue = NULL)
1960 {
1961 global $dbxlink;
1962 if (empty ($varname) || $varvalue === NULL)
1963 {
1964 showError ('Invalid arguments', __FUNCTION__);
1965 return FALSE;
1966 }
1967 $query = "update Config set varvalue='${varvalue}' where varname='${varname}' limit 1";
1968 $result = $dbxlink->query ($query);
1969 if ($result == NULL)
1970 {
1971 showError ("SQL query '${query}' failed", __FUNCTION__);
1972 return FALSE;
1973 }
1974 $rc = $result->rowCount();
1975 $result->closeCursor();
1976 if ($rc == 0 or $rc == 1)
1977 return TRUE;
1978 showError ("Something went wrong for args '${varname}', '${varvalue}'", __FUNCTION__);
1979 return FALSE;
1980 }
1981
1982 // Database version detector. Should behave corretly on any
1983 // working dataset a user might have.
1984 function getDatabaseVersion ()
1985 {
1986 global $dbxlink;
1987 $query = "select varvalue from Config where varname = 'DB_VERSION' and vartype = 'string'";
1988 $result = $dbxlink->query ($query);
1989 if ($result == NULL)
1990 {
1991 $errorInfo = $dbxlink->errorInfo();
1992 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
1993 return '0.14.4';
1994 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
1995 }
1996 $rows = $result->fetchAll (PDO::FETCH_NUM);
1997 if (count ($rows) != 1 || empty ($rows[0][0]))
1998 {
1999 $result->closeCursor();
2000 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
2001 }
2002 $ret = $rows[0][0];
2003 $result->closeCursor();
2004 return $ret;
2005 }
2006
2007 // Return an array of virtual services. For each of them list real server pools
2008 // with their load balancers and other stats.
2009 function getSLBSummary ()
2010 {
2011 $query = 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
2012 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
2013 'from IPVirtualService as vs inner join IPLoadBalancer as lb on vs.id = lb.vs_id ' .
2014 'inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2015 'left join IPRealServer as rs on rs.rspool_id = lb.rspool_id ' .
2016 'group by vs.id, object_id order by vs.vip, object_id';
2017 $result = useSelectBlade ($query);
2018 $ret = array();
2019 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2020 {
2021 $vsid = $row['vsid'];
2022 $object_id = $row['object_id'];
2023 if (!isset ($ret[$vsid]))
2024 {
2025 $ret[$vsid] = array();
2026 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
2027 $ret[$vsid][$cname] = $row[$cname];
2028 $ret[$vsid]['lblist'] = array();
2029 }
2030 // There's only one assigned RS pool possible for each LB-VS combination.
2031 $ret[$vsid]['lblist'][$row['object_id']] = array
2032 (
2033 'id' => $row['rspool_id'],
2034 'size' => $row['rscount'],
2035 'name' => $row['pool_name']
2036 );
2037 }
2038 $result->closeCursor();
2039 return $ret;
2040 }
2041
2042 // Get the detailed composition of a particular virtual service, namely the list
2043 // of all pools, each shown with the list of objects servicing it. VS/RS configs
2044 // will be returned as well.
2045 function getVServiceInfo ($vsid = 0)
2046 {
2047 $query1 = "select inet_ntoa(vip) as vip, vport, proto, name, vsconfig, rsconfig " .
2048 "from IPVirtualService where id = ${vsid}";
2049 $result = useSelectBlade ($query1);
2050 $vsinfo = array ();
2051 $row = $result->fetch (PDO::FETCH_ASSOC);
2052 if (!$row)
2053 return NULL;
2054 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig') as $cname)
2055 $vsinfo[$cname] = $row[$cname];
2056 $vsinfo['rspool'] = array();
2057 $result->closeCursor();
2058 unset ($result);
2059 $query2 = "select pool.id, name, pool.vsconfig, pool.rsconfig, object_id, " .
2060 "lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig from " .
2061 "IPRSPool as pool left join IPLoadBalancer as lb on pool.id = lb.rspool_id " .
2062 "where vs_id = ${vsid} order by pool.name, object_id";
2063 $result = useSelectBlade ($query2);
2064 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2065 {
2066 if (!isset ($vsinfo['rspool'][$row['id']]))
2067 {
2068 $vsinfo['rspool'][$row['id']]['name'] = $row['name'];
2069 $vsinfo['rspool'][$row['id']]['vsconfig'] = $row['vsconfig'];
2070 $vsinfo['rspool'][$row['id']]['rsconfig'] = $row['rsconfig'];
2071 $vsinfo['rspool'][$row['id']]['lblist'] = array();
2072 }
2073 if ($row['object_id'] == NULL)
2074 continue;
2075 $vsinfo['rspool'][$row['id']]['lblist'][$row['object_id']] = array
2076 (
2077 'vsconfig' => $row['lb_vsconfig'],
2078 'rsconfig' => $row['lb_rsconfig']
2079 );
2080 }
2081 $result->closeCursor();
2082 return $vsinfo;
2083 }
2084
2085 // Collect and return the following info about the given real server pool:
2086 // basic information
2087 // parent virtual service information
2088 // load balancers list (each with a list of VSes)
2089 // real servers list
2090
2091 function getRSPoolInfo ($id = 0)
2092 {
2093 $query1 = "select id, name, vsconfig, rsconfig from " .
2094 "IPRSPool where id = ${id}";
2095 $result = useSelectBlade ($query1);
2096 $ret = array();
2097 $row = $result->fetch (PDO::FETCH_ASSOC);
2098 if (!$row)
2099 return NULL;
2100 foreach (array ('id', 'name', 'vsconfig', 'rsconfig') as $c)
2101 $ret[$c] = $row[$c];
2102 $result->closeCursor();
2103 unset ($result);
2104 $ret['lblist'] = array();
2105 $ret['rslist'] = array();
2106 $query2 = "select object_id, vs_id, vsconfig, rsconfig from IPLoadBalancer " .
2107 "where rspool_id = ${id} order by object_id, vs_id";
2108 $result = useSelectBlade ($query2);
2109 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2110 foreach (array ('vsconfig', 'rsconfig') as $c)
2111 $ret['lblist'][$row['object_id']][$row['vs_id']][$c] = $row[$c];
2112 $result->closeCursor();
2113 unset ($result);
2114 $query3 = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rsconfig from " .
2115 "IPRealServer where rspool_id = ${id} order by IPRealServer.rsip, rsport";
2116 $result = useSelectBlade ($query3);
2117 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2118 foreach (array ('inservice', 'rsip', 'rsport', 'rsconfig') as $c)
2119 $ret['rslist'][$row['id']][$c] = $row[$c];
2120 $result->closeCursor();
2121 return $ret;
2122 }
2123
2124 function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
2125 {
2126 if ($pool_id <= 0 or $rsport <= 0)
2127 {
2128 showError ('Invalid arguments', __FUNCTION__);
2129 die;
2130 }
2131 return useInsertBlade
2132 (
2133 'IPRealServer',
2134 array
2135 (
2136 'rsip' => "inet_aton('${rsip}')",
2137 'rsport' => $rsport,
2138 'rspool_id' => $pool_id,
2139 'inservice' => ($inservice == 'yes' ? "'yes'" : "'no'"),
2140 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2141 )
2142 );
2143 }
2144
2145 function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig)
2146 {
2147 if (empty ($vip) or $vport <= 0 or empty ($proto))
2148 {
2149 showError ('Invalid arguments', __FUNCTION__);
2150 die;
2151 }
2152 return useInsertBlade
2153 (
2154 'IPVirtualService',
2155 array
2156 (
2157 'vip' => "inet_aton('${vip}')",
2158 'vport' => $vport,
2159 'proto' => "'${proto}'",
2160 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2161 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2162 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2163 )
2164 );
2165 }
2166
2167 function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
2168 {
2169 if ($pool_id <= 0 or $object_id <= 0 or $vs_id <= 0)
2170 {
2171 showError ('Invalid arguments', __FUNCTION__);
2172 die;
2173 }
2174 return useInsertBlade
2175 (
2176 'IPLoadBalancer',
2177 array
2178 (
2179 'object_id' => $object_id,
2180 'rspool_id' => $pool_id,
2181 'vs_id' => $vs_id,
2182 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2183 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2184 )
2185 );
2186 }
2187
2188 function commitDeleteRS ($id = 0)
2189 {
2190 if ($id <= 0)
2191 return FALSE;
2192 return useDeleteBlade ('IPRealServer', 'id', $id, FALSE);
2193 }
2194
2195 function commitDeleteVS ($id = 0)
2196 {
2197 if ($id <= 0)
2198 return FALSE;
2199 return useDeleteBlade ('IPVirtualService', 'id', $id, FALSE) && deleteTagsForEntity ('ipv4vs', $id);
2200 }
2201
2202 function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
2203 {
2204 global $dbxlink;
2205 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
2206 return FALSE;
2207 $query = "delete from IPLoadBalancer where object_id = ${object_id} and " .
2208 "rspool_id = ${pool_id} and vs_id = ${vs_id} limit 1";
2209 $result = $dbxlink->exec ($query);
2210 if ($result === NULL)
2211 return FALSE;
2212 elseif ($result != 1)
2213 return FALSE;
2214 else
2215 return TRUE;
2216 }
2217
2218 function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2219 {
2220 if ($rsid <= 0 or $rsport <= 0)
2221 {
2222 showError ('Invalid args', __FUNCTION__);
2223 die;
2224 }
2225 if (long2ip (ip2long ($rsip)) !== $rsip)
2226 {
2227 showError ("Invalid IP address '${rsip}'", __FUNCTION__);
2228 die;
2229 }
2230 global $dbxlink;
2231 $query =
2232 "update IPRealServer set rsip = inet_aton('${rsip}'), rsport = ${rsport}, rsconfig = " .
2233 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2234 " where id = ${rsid} limit 1";
2235 $result = $dbxlink->query ($query);
2236 if ($result == NULL)
2237 {
2238 showError ("SQL query '${query}' failed", __FUNCTION__);
2239 die;
2240 }
2241 return TRUE;
2242 }
2243
2244 function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
2245 {
2246 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
2247 {
2248 showError ('Invalid args', __FUNCTION__);
2249 die;
2250 }
2251 global $dbxlink;
2252 $query =
2253 "update IPLoadBalancer set vsconfig = " .
2254 (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'") .
2255 ', rsconfig = ' .
2256 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2257 " where object_id = ${object_id} and rspool_id = ${pool_id} " .
2258 "and vs_id = ${vs_id} limit 1";
2259 $result = $dbxlink->exec ($query);
2260 if ($result === NULL)
2261 return FALSE;
2262 else
2263 return TRUE;
2264 }
2265
2266 function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2267 {
2268 if ($vsid <= 0 or empty ($vip) or $vport <= 0 or empty ($proto))
2269 {
2270 showError ('Invalid args', __FUNCTION__);
2271 die;
2272 }
2273 global $dbxlink;
2274 $query = "update IPVirtualService set " .
2275 "vip = inet_aton('${vip}'), " .
2276 "vport = ${vport}, " .
2277 "proto = '${proto}', " .
2278 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2279 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2280 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2281 " where id = ${vsid} limit 1";
2282 $result = $dbxlink->exec ($query);
2283 if ($result === NULL)
2284 return FALSE;
2285 else
2286 return TRUE;
2287 }
2288
2289 // Return the list of virtual services, indexed by vs_id.
2290 // Each record will be shown with its basic info plus RS pools counter.
2291 function getVSList ($tagfilter = array())
2292 {
2293 $whereclause = getWhereClause ($tagfilter);
2294 $query = "select vs.id, inet_ntoa(vip) as vip, vport, proto, vs.name, vs.vsconfig, vs.rsconfig, count(rspool_id) as poolcount " .
2295 "from IPVirtualService as vs left join IPLoadBalancer as lb on vs.id = lb.vs_id " .
2296 "left join TagStorage on vs.id = TagStorage.target_id and target_realm = 'ipv4vs' " .
2297 "where true ${whereclause} group by vs.id order by vs.vip, proto, vport";
2298 $result = useSelectBlade ($query);
2299 $ret = array ();
2300 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2301 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig', 'poolcount') as $cname)
2302 $ret[$row['id']][$cname] = $row[$cname];
2303 $result->closeCursor();
2304 return $ret;
2305 }
2306
2307 // Return the list of RS pool, indexed by pool id.
2308 function getRSPoolList ($tagfilter = array())
2309 {
2310 $whereclause = getWhereClause ($tagfilter);
2311 $query = "select pool.id, pool.name, count(rspool_id) as refcnt, pool.vsconfig, pool.rsconfig " .
2312 "from IPRSPool as pool left join IPLoadBalancer as lb on pool.id = lb.rspool_id " .
2313 "left join TagStorage on pool.id = TagStorage.target_id and target_realm = 'ipv4rspool' " .
2314 "where true ${whereclause} group by pool.id order by pool.id, name";
2315 $result = useSelectBlade ($query);
2316 $ret = array ();
2317 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2318 foreach (array ('name', 'refcnt', 'vsconfig', 'rsconfig') as $cname)
2319 $ret[$row['id']][$cname] = $row[$cname];
2320 $result->closeCursor();
2321 return $ret;
2322 }
2323
2324 function loadThumbCache ($rack_id = 0)
2325 {
2326 $ret = NULL;
2327 $query = "select thumb_data from Rack where id = ${rack_id} and thumb_data is not null limit 1";
2328 $result = useSelectBlade ($query);
2329 $row = $result->fetch (PDO::FETCH_ASSOC);
2330 if ($row)
2331 $ret = base64_decode ($row['thumb_data']);
2332 $result->closeCursor();
2333 return $ret;
2334 }
2335
2336 function saveThumbCache ($rack_id = 0, $cache = NULL)
2337 {
2338 global $dbxlink;
2339 if ($rack_id == 0 or $cache == NULL)
2340 {
2341 showError ('Invalid arguments', __FUNCTION__);
2342 return;
2343 }
2344 $data = base64_encode ($cache);
2345 $query = "update Rack set thumb_data = '${data}' where id = ${rack_id} limit 1";
2346 $result = $dbxlink->exec ($query);
2347 }
2348
2349 function resetThumbCache ($rack_id = 0)
2350 {
2351 global $dbxlink;
2352 if ($rack_id == 0)
2353 {
2354 showError ('Invalid argument', __FUNCTION__);
2355 return;
2356 }
2357 $query = "update Rack set thumb_data = NULL where id = ${rack_id} limit 1";
2358 $result = $dbxlink->exec ($query);
2359 }
2360
2361 // Return the list of attached RS pools for the given object. As long as we have
2362 // the LB-VS UNIQUE in IPLoadBalancer table, it is Ok to key returned records
2363 // by vs_id, because there will be only one RS pool listed for each VS of the
2364 // current object.
2365 function getRSPoolsForObject ($object_id = 0)
2366 {
2367 if ($object_id <= 0)
2368 {
2369 showError ('Invalid object_id', __FUNCTION__);
2370 return NULL;
2371 }
2372 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
2373 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
2374 'IPLoadBalancer as lb inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2375 'inner join IPVirtualService as vs on lb.vs_id = vs.id ' .
2376 'left join IPRealServer as rs on lb.rspool_id = rs.rspool_id ' .
2377 "where lb.object_id = ${object_id} " .
2378 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name';
2379 $result = useSelectBlade ($query);
2380 $ret = array ();
2381 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2382 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
2383 $ret[$row['vs_id']][$cname] = $row[$cname];
2384 $result->closeCursor();
2385 return $ret;
2386 }
2387
2388 function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '')
2389 {
2390 return useInsertBlade
2391 (
2392 'IPRSPool',
2393 array
2394 (
2395 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2396 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2397 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2398 )
2399 );
2400 }
2401
2402 function commitDeleteRSPool ($pool_id = 0)
2403 {
2404 global $dbxlink;
2405 if ($pool_id <= 0)
2406 return FALSE;
2407 return useDeleteBlade ('IPRSPool', 'id', $pool_id, FALSE) && deleteTagsForEntity ('ipv4rspool', $pool_id);
2408 }
2409
2410 function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2411 {
2412 if ($pool_id <= 0)
2413 {
2414 showError ('Invalid arg', __FUNCTION__);
2415 die;
2416 }
2417 global $dbxlink;
2418 $query = "update IPRSPool set " .
2419 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2420 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2421 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2422 " where id = ${pool_id} limit 1";
2423 $result = $dbxlink->exec ($query);
2424 if ($result === NULL)
2425 return FALSE;
2426 elseif ($result != 1)
2427 return FALSE;
2428 else
2429 return TRUE;
2430 }
2431
2432 function getRSList ()
2433 {
2434 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
2435 "from IPRealServer order by rspool_id, IPRealServer.rsip, rsport";
2436 $result = useSelectBlade ($query);
2437 $ret = array ();
2438 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2439 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
2440 $ret[$row['id']][$cname] = $row[$cname];
2441 $result->closeCursor();
2442 return $ret;
2443 }
2444
2445 // Return the list of all currently configured load balancers with their pool count.
2446 function getLBList ()
2447 {
2448 $query = "select object_id, count(rspool_id) as poolcount " .
2449 "from IPLoadBalancer group by object_id order by object_id";
2450 $result = useSelectBlade ($query);
2451 $ret = array ();
2452 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2453 $ret[$row['object_id']] = $row['poolcount'];
2454 $result->closeCursor();
2455 return $ret;
2456 }
2457
2458 // For the given object return: it vsconfig/rsconfig; the list of RS pools
2459 // attached (each with vsconfig/rsconfig in turn), each with the list of
2460 // virtual services terminating the pool. Each pool also lists all real
2461 // servers with rsconfig.
2462 function buildLBConfig ($object_id)
2463 {
2464 if ($object_id <= 0)
2465 {
2466 showError ('Invalid arg', __FUNCTION__);
2467 return NULL;
2468 }
2469 $ret = array();
2470 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2471 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2472 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
2473 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
2474 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
2475 'IPLoadBalancer as lb inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2476 'inner join IPVirtualService as vs on lb.vs_id = vs.id ' .
2477 'inner join IPRealServer as rs on lb.rspool_id = rs.rspool_id ' .
2478 "where lb.object_id = ${object_id} and rs.inservice = 'yes' " .
2479 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport";
2480 $result = useSelectBlade ($query);
2481 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2482 {
2483 $vs_id = $row['vs_id'];
2484 if (!isset ($ret[$vs_id]))
2485 {
2486 foreach (array ('vip', 'vport', 'proto', 'vs_name', 'vs_vsconfig', 'vs_rsconfig', 'lb_vsconfig', 'lb_rsconfig', 'pool_vsconfig', 'pool_rsconfig', 'pool_id', 'pool_name') as $c)
2487 $ret[$vs_id][$c] = $row[$c];
2488 $ret[$vs_id]['rslist'] = array();
2489 }
2490 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2491 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
2492 }
2493 $result->closeCursor();
2494 return $ret;
2495 }
2496
2497 function commitSetInService ($rs_id = 0, $inservice = '')
2498 {
2499 if ($rs_id <= 0 or empty ($inservice))
2500 {
2501 showError ('Invalid args', __FUNCTION__);
2502 return NULL;
2503 }
2504 global $dbxlink;
2505 $query = "update IPRealServer set inservice = '${inservice}' where id = ${rs_id} limit 1";
2506 $result = $dbxlink->exec ($query);
2507 if ($result === NULL)
2508 return FALSE;
2509 elseif ($result != 1)
2510 return FALSE;
2511 else
2512 return TRUE;
2513 }
2514
2515 function executeAutoPorts ($object_id = 0, $type_id = 0)
2516 {
2517 if ($object_id == 0 or $type_id == 0)
2518 {
2519 showError ('Invalid arguments', __FUNCTION__);
2520 die;
2521 }
2522 $ret = TRUE;
2523 foreach (getAutoPorts ($type_id) as $autoport)
2524 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2525 return $ret;
2526 }
2527
2528 // Return only implicitly listed tags, the rest of the trail will be
2529 // generated/deducted later at higher levels.
2530 function loadEntityTags ($entity_realm = '', $entity_id = 0)
2531 {
2532 if ($entity_realm == '' or $entity_id <= 0)
2533 {
2534 showError ('Invalid or missing arguments', __FUNCTION__);
2535 return NULL;
2536 }
2537 $ret = array();
2538 $result = useSelectBlade ("select tt.id, tag from TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id where target_realm = '${entity_realm}' and target_id = ${entity_id}");
2539 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2540 $ret[$row['id']] = $row;
2541 $result->closeCursor();
2542 return $ret;
2543 }
2544
2545 function loadRackObjectTags ($id)
2546 {
2547 return loadEntityTags ('object', $id);
2548 }
2549
2550 function loadIPv4PrefixTags ($id)
2551 {
2552 return loadEntityTags ('ipv4net', $id);
2553 }
2554
2555 function loadRackTags ($id)
2556 {
2557 return loadEntityTags ('rack', $id);
2558 }
2559
2560 function loadIPv4VSTags ($id)
2561 {
2562 return loadEntityTags ('ipv4vs', $id);
2563 }
2564
2565 function loadIPv4RSPoolTags ($id)
2566 {
2567 return loadEntityTags ('ipv4rspool', $id);
2568 }
2569
2570 function getTagList ()
2571 {
2572 $ret = array();
2573 $query = "select id, parent_id, tag, target_realm as realm, count(target_id) as refcnt " .
2574 "from TagTree left join TagStorage on id = tag_id " .
2575 "group by id, target_realm order by tag";
2576 $result = useSelectBlade ($query);
2577 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2578 {
2579 if (!isset ($ret[$row['id']]))
2580 $ret[$row['id']] = array
2581 (
2582 'id' => $row['id'],
2583 'tag' => $row['tag'],
2584 'parent_id' => $row['parent_id'],
2585 'refcnt' => array()
2586 );
2587 if ($row['realm'])
2588 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
2589 }
2590 $result->closeCursor();
2591 return $ret;
2592 }
2593
2594 function commitCreateTag ($tagname = '', $parent_id = 0)
2595 {
2596 if ($tagname == '' or $parent_id === 0)
2597 return "Invalid args to " . __FUNCTION__;
2598 $result = useInsertBlade
2599 (
2600 'TagTree',
2601 array
2602 (
2603 'tag' => "'${tagname}'",
2604 'parent_id' => $parent_id
2605 )
2606 );
2607 if ($result)
2608 return '';
2609 else
2610 return "SQL query failed in " . __FUNCTION__;
2611 }
2612
2613 function commitDestroyTag ($tagid = 0)
2614 {
2615 if ($tagid == 0)
2616 return 'Invalid arg to ' . __FUNCTION__;
2617 if (useDeleteBlade ('TagTree', 'id', $tagid, FALSE))
2618 return '';
2619 else
2620 return 'useDeleteBlade() failed in ' . __FUNCTION__;
2621 }
2622
2623 function commitUpdateTag ($tag_id, $tag_name, $parent_id)
2624 {
2625 if ($parent_id == 0)
2626 $parent_id = 'NULL';
2627 global $dbxlink;
2628 $query = "update TagTree set tag = '${tag_name}', parent_id = ${parent_id} " .
2629 "where id = ${tag_id} limit 1";
2630 $result = $dbxlink->exec ($query);
2631 if ($result === NULL)
2632 return 'SQL query failed in ' . __FUNCTION__;
2633 return '';
2634 }
2635
2636 function deleteTagsForEntity ($entity_realm, $entity_id)
2637 {
2638 global $dbxlink;
2639 $query = "delete from TagStorage where target_realm = '${entity_realm}' and target_id = ${entity_id}";
2640 $result = $dbxlink->exec ($query);
2641 if ($result === NULL)
2642 return FALSE;
2643 else
2644 return TRUE;
2645 }
2646
2647 ?>