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