r2100 + replace odd getRangeByIp() with shiny new getIPv4AddressNetworkId() to speed...
[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 = htmlspecialchars ($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(), $tfmode = 'any')
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, __FUNCTION__);
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 // Return detailed information about one rack row.
40 function getRackRowInfo ($rackrow_id)
41 {
42 $query =
43 "select dict_key as id, dict_value as name, count(Rack.id) as count, " .
44 "if(isnull(sum(Rack.height)),0,sum(Rack.height)) as sum " .
45 "from Chapter natural join Dictionary left join Rack on Rack.row_id = dict_key " .
46 "where chapter_name = 'RackRow' and dict_key = ${rackrow_id} " .
47 "group by dict_key";
48 $result = useSelectBlade ($query, __FUNCTION__);
49 if ($row = $result->fetch (PDO::FETCH_ASSOC))
50 return $row;
51 else
52 return NULL;
53 }
54
55 // This function returns id->name map for all object types. The map is used
56 // to build <select> input for objects.
57 function getObjectTypeList ()
58 {
59 return readChapter ('RackObjectType');
60 }
61
62 // Return a part of SQL query suitable for embeding into a bigger text.
63 // The returned result should list all tag IDs shown in the tag filter.
64 function getWhereClause ($tagfilter = array())
65 {
66 $whereclause = '';
67 if (count ($tagfilter))
68 {
69 $whereclause .= ' and (';
70 $conj = '';
71 foreach ($tagfilter as $tag_id)
72 {
73 $whereclause .= $conj . 'tag_id = ' . $tag_id;
74 $conj = ' or ';
75 }
76 $whereclause .= ') ';
77 }
78 return $whereclause;
79 }
80
81 // Return a simple object list w/o related information.
82 function getNarrowObjectList ($type_id = 0)
83 {
84 $ret = array();
85 if (!$type_id)
86 {
87 showError ('Invalid argument', __FUNCTION__);
88 return $ret;
89 }
90 // object type id is known and constant, but it's Ok to have this standard overhead
91 $query =
92 "select RackObject.id as id, RackObject.name as name, dict_value as objtype_name, " .
93 "objtype_id from " .
94 "RackObject inner join Dictionary on objtype_id=dict_key natural join Chapter " .
95 "where RackObject.deleted = 'no' and chapter_name = 'RackObjectType' " .
96 "and objtype_id = ${type_id} " .
97 "order by name";
98 $result = useSelectBlade ($query, __FUNCTION__);
99 while ($row = $result->fetch (PDO::FETCH_ASSOC))
100 {
101 foreach (array (
102 'id',
103 'name',
104 'objtype_name',
105 'objtype_id'
106 ) as $cname)
107 $ret[$row['id']][$cname] = $row[$cname];
108 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
109 }
110 return $ret;
111 }
112
113 // Return a filtered, detailed object list.
114 function getObjectList ($type_id = 0, $tagfilter = array(), $tfmode = 'any')
115 {
116 $whereclause = getWhereClause ($tagfilter);
117 if ($type_id != 0)
118 $whereclause .= " and objtype_id = '${type_id}' ";
119 $query =
120 "select distinct RackObject.id as id , RackObject.name as name, dict_value as objtype_name, " .
121 "RackObject.label as label, RackObject.barcode as barcode, " .
122 "dict_key as objtype_id, asset_no, rack_id, Rack.name as Rack_name from " .
123 "((RackObject inner join Dictionary on objtype_id=dict_key natural join Chapter) " .
124 "left join RackSpace on RackObject.id = object_id) " .
125 "left join Rack on rack_id = Rack.id " .
126 "left join TagStorage on RackObject.id = TagStorage.target_id and target_realm = 'object' " .
127 "where RackObject.deleted = 'no' and chapter_name = 'RackObjectType' " .
128 $whereclause .
129 "order by name";
130 $result = useSelectBlade ($query, __FUNCTION__);
131 $ret = array();
132 while ($row = $result->fetch (PDO::FETCH_ASSOC))
133 {
134 foreach (array (
135 'id',
136 'name',
137 'label',
138 'barcode',
139 'objtype_name',
140 'objtype_id',
141 'asset_no',
142 'rack_id',
143 'Rack_name'
144 ) as $cname)
145 $ret[$row['id']][$cname] = $row[$cname];
146 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
147 }
148 $result->closeCursor();
149 return $ret;
150 }
151
152 function getRacksForRow ($row_id = 0, $tagfilter = array(), $tfmode = 'any')
153 {
154 $query =
155 "select Rack.id, Rack.name, height, Rack.comment, row_id, " .
156 "'yes' as left_is_front, 'yes' as bottom_is_unit1, dict_value as row_name " .
157 "from Rack left join Dictionary on row_id = dict_key natural join Chapter " .
158 "left join TagStorage on Rack.id = TagStorage.target_id and target_realm = 'rack' " .
159 "where chapter_name = 'RackRow' and Rack.deleted = 'no' " .
160 (($row_id == 0) ? "" : "and row_id = ${row_id} ") .
161 getWhereClause ($tagfilter) .
162 " order by row_name, Rack.id";
163 $result = useSelectBlade ($query, __FUNCTION__);
164 $ret = array();
165 $clist = array
166 (
167 'id',
168 'name',
169 'height',
170 'comment',
171 'row_id',
172 'left_is_front',
173 'bottom_is_unit1',
174 'row_name'
175 );
176 while ($row = $result->fetch (PDO::FETCH_ASSOC))
177 foreach ($clist as $cname)
178 $ret[$row['id']][$cname] = $row[$cname];
179 $result->closeCursor();
180 usort ($ret, 'sortRacks');
181 $ret = restoreRackIDs ($ret);
182 return $ret;
183 }
184
185 // This is a popular helper for getting information about
186 // a particular rack and its rackspace at once.
187 function getRackData ($rack_id = 0, $silent = FALSE)
188 {
189 if ($rack_id == 0)
190 {
191 if ($silent == FALSE)
192 showError ('Invalid rack_id', __FUNCTION__);
193 return NULL;
194 }
195 $query =
196 "select Rack.id, Rack.name, row_id, height, Rack.comment, " .
197 "'yes' as left_is_front, 'yes' as bottom_is_unit1, dict_value as row_name from " .
198 "Rack left join Dictionary on Rack.row_id = dict_key natural join Chapter " .
199 "where chapter_name = 'RackRow' and Rack.id='${rack_id}' and Rack.deleted = 'no' limit 1";
200 $result = useSelectBlade ($query, __FUNCTION__);
201 if (($row = $result->fetch (PDO::FETCH_ASSOC)) == NULL)
202 {
203 if ($silent == FALSE)
204 showError ('Query #1 succeded, but returned no data', __FUNCTION__);
205 return NULL;
206 }
207
208 // load metadata
209 $clist = array
210 (
211 'id',
212 'name',
213 'height',
214 'comment',
215 'row_id',
216 'left_is_front',
217 'bottom_is_unit1',
218 'row_name'
219 );
220 foreach ($clist as $cname)
221 $rack[$cname] = $row[$cname];
222 $result->closeCursor();
223 unset ($result);
224
225 // start with default rackspace
226 for ($i = $rack['height']; $i > 0; $i--)
227 for ($locidx = 0; $locidx < 3; $locidx++)
228 $rack[$i][$locidx]['state'] = 'F';
229
230 // load difference
231 $query =
232 "select unit_no, atom, state, object_id " .
233 "from RackSpace where rack_id = ${rack_id} and " .
234 "unit_no between 1 and " . $rack['height'] . " order by unit_no";
235 $result = useSelectBlade ($query, __FUNCTION__);
236 global $loclist;
237 while ($row = $result->fetch (PDO::FETCH_ASSOC))
238 {
239 $rack[$row['unit_no']][$loclist[$row['atom']]]['state'] = $row['state'];
240 $rack[$row['unit_no']][$loclist[$row['atom']]]['object_id'] = $row['object_id'];
241 }
242 $result->closeCursor();
243 return $rack;
244 }
245
246 // This is a popular helper.
247 function getObjectInfo ($object_id = 0)
248 {
249 if ($object_id == 0)
250 {
251 showError ('Invalid object_id', __FUNCTION__);
252 return;
253 }
254 $query =
255 "select id, name, label, barcode, dict_value as objtype_name, asset_no, dict_key as objtype_id, has_problems, comment from " .
256 "RackObject inner join Dictionary on objtype_id = dict_key natural join Chapter " .
257 "where id = '${object_id}' and deleted = 'no' and chapter_name = 'RackObjectType' limit 1";
258 $result = useSelectBlade ($query, __FUNCTION__);
259 if (($row = $result->fetch (PDO::FETCH_ASSOC)) == NULL)
260 {
261 showError ('Query succeeded, but returned no data', __FUNCTION__);
262 $ret = NULL;
263 }
264 else
265 {
266 $ret['id'] = $row['id'];
267 $ret['name'] = $row['name'];
268 $ret['label'] = $row['label'];
269 $ret['barcode'] = $row['barcode'];
270 $ret['objtype_name'] = $row['objtype_name'];
271 $ret['objtype_id'] = $row['objtype_id'];
272 $ret['has_problems'] = $row['has_problems'];
273 $ret['asset_no'] = $row['asset_no'];
274 $ret['dname'] = displayedName ($ret);
275 $ret['comment'] = $row['comment'];
276 }
277 $result->closeCursor();
278 unset ($result);
279 return $ret;
280 }
281
282 function getPortTypes ()
283 {
284 return readChapter ('PortType');
285 }
286
287 function getObjectPortsAndLinks ($object_id = 0)
288 {
289 if ($object_id == 0)
290 {
291 showError ('Invalid object_id', __FUNCTION__);
292 return;
293 }
294 $query =
295 "select Port.id as Port_id, ".
296 "Port.name as Port_name, ".
297 "Port.label as Port_label, ".
298 "Port.l2address as Port_l2address, ".
299 "Port.type as Port_type, ".
300 "Port.reservation_comment as Port_reservation_comment, " .
301 "dict_value as PortType_name, ".
302 "RemotePort.id as RemotePort_id, ".
303 "RemotePort.name as RemotePort_name, ".
304 "RemotePort.object_id as RemotePort_object_id, ".
305 "RackObject.name as RackObject_name ".
306 "from (".
307 "(".
308 "(".
309 "Port inner join Dictionary on Port.type = dict_key natural join Chapter".
310 ") ".
311 "left join Link on Port.id=Link.porta or Port.id=Link.portb ".
312 ") ".
313 "left join Port as RemotePort on Link.portb=RemotePort.id or Link.porta=RemotePort.id ".
314 ") ".
315 "left join RackObject on RemotePort.object_id=RackObject.id ".
316 "where chapter_name = 'PortType' and Port.object_id=${object_id} ".
317 "and (Port.id != RemotePort.id or RemotePort.id is null) ".
318 "order by Port_name";
319 $result = useSelectBlade ($query, __FUNCTION__);
320 $ret=array();
321 $count=0;
322 while ($row = $result->fetch (PDO::FETCH_ASSOC))
323 {
324 $ret[$count]['id'] = $row['Port_id'];
325 $ret[$count]['name'] = $row['Port_name'];
326 $ret[$count]['l2address'] = l2addressFromDatabase ($row['Port_l2address']);
327 $ret[$count]['label'] = $row['Port_label'];
328 $ret[$count]['type_id'] = $row['Port_type'];
329 $ret[$count]['type'] = $row['PortType_name'];
330 $ret[$count]['reservation_comment'] = $row['Port_reservation_comment'];
331 $ret[$count]['remote_id'] = $row['RemotePort_id'];
332 $ret[$count]['remote_name'] = htmlentities ($row['RemotePort_name'], ENT_QUOTES);
333 $ret[$count]['remote_object_id'] = $row['RemotePort_object_id'];
334 $ret[$count]['remote_object_name'] = $row['RackObject_name'];
335 // Save on displayedName() calls.
336 if (empty ($row['RackObject_name']) and !empty ($row['RemotePort_object_id']))
337 {
338 $oi = getObjectInfo ($row['RemotePort_object_id']);
339 $ret[$count]['remote_object_name'] = displayedName ($oi);
340 }
341 $count++;
342 }
343 $result->closeCursor();
344 return $ret;
345 }
346
347 function commitAddRack ($name, $height, $row_id, $comment, $taglist)
348 {
349 $result = useInsertBlade
350 (
351 'Rack',
352 array
353 (
354 'row_id' => $row_id,
355 'name' => "'${name}'",
356 'height' => $height,
357 'comment' => "'${comment}'"
358 )
359 );
360 if ($result == NULL)
361 {
362 showError ('useInsertBlade() failed', __FUNCTION__);
363 return FALSE;
364 }
365 $last_insert_id = lastInsertID();
366 return (addTagsForLastRecord ('rack', $taglist, $last_insert_id) == '') and recordHistory ('Rack', "id = ${last_insert_id}");
367 }
368
369 function commitAddObject ($new_name, $new_label, $new_barcode, $new_type_id, $new_asset_no, $taglist = array())
370 {
371 global $dbxlink;
372 // Maintain UNIQUE INDEX for common names and asset tags by
373 // filtering out empty strings (not NULLs).
374 $result1 = useInsertBlade
375 (
376 'RackObject',
377 array
378 (
379 'name' => empty ($new_name) ? 'NULL' : "'${new_name}'",
380 'label' => "'${new_label}'",
381 'barcode' => empty ($new_barcode) ? 'NULL' : "'${new_barcode}'",
382 'objtype_id' => $new_type_id,
383 'asset_no' => empty ($new_asset_no) ? 'NULL' : "'${new_asset_no}'"
384 )
385 );
386 if ($result1 == NULL)
387 {
388 showError ("SQL query #1 failed", __FUNCTION__);
389 return FALSE;
390 }
391 $last_insert_id = lastInsertID();
392 // Do AutoPorts magic
393 executeAutoPorts ($last_insert_id, $new_type_id);
394 // Now tags...
395 $error = addTagsForLastRecord ('object', $taglist, $last_insert_id);
396 if ($error != '')
397 {
398 showError ("Error adding tags for the object: ${error}");
399 return FALSE;
400 }
401 return recordHistory ('RackObject', "id = ${last_insert_id}");
402 }
403
404 function commitUpdateObject ($object_id = 0, $new_name = '', $new_label = '', $new_barcode = '', $new_type_id = 0, $new_has_problems = 'no', $new_asset_no = '', $new_comment = '')
405 {
406 if ($object_id == 0 || $new_type_id == 0)
407 {
408 showError ('Not all required args are present.', __FUNCTION__);
409 return FALSE;
410 }
411 global $dbxlink;
412 $new_asset_no = empty ($new_asset_no) ? 'NULL' : "'${new_asset_no}'";
413 $new_barcode = empty ($new_barcode) ? 'NULL' : "'${new_barcode}'";
414 $new_name = empty ($new_name) ? 'NULL' : "'${new_name}'";
415 $query = "update RackObject set name=${new_name}, label='${new_label}', barcode=${new_barcode}, objtype_id='${new_type_id}', " .
416 "has_problems='${new_has_problems}', asset_no=${new_asset_no}, comment='${new_comment}' " .
417 "where id='${object_id}' limit 1";
418 $result = $dbxlink->query ($query);
419 if ($result == NULL)
420 {
421 showError ("SQL query '${query}' failed", __FUNCTION__);
422 return FALSE;
423 }
424 $result->closeCursor();
425 return recordHistory ('RackObject', "id = ${object_id}");
426 }
427
428 function commitUpdateRack ($rack_id, $new_name, $new_height, $new_row_id, $new_comment)
429 {
430 if (empty ($rack_id) || empty ($new_name) || empty ($new_height))
431 {
432 showError ('Not all required args are present.', __FUNCTION__);
433 return FALSE;
434 }
435 global $dbxlink;
436 $query = "update Rack set name='${new_name}', height='${new_height}', comment='${new_comment}', row_id=${new_row_id} " .
437 "where id='${rack_id}' limit 1";
438 $result1 = $dbxlink->query ($query);
439 if ($result1->rowCount() != 1)
440 {
441 showError ('Error updating rack information', __FUNCTION__);
442 return FALSE;
443 }
444 return recordHistory ('Rack', "id = ${rack_id}");
445 }
446
447 // This function accepts rack data returned by getRackData(), validates and applies changes
448 // supplied in $_REQUEST and returns resulting array. Only those changes are examined, which
449 // correspond to current rack ID.
450 // 1st arg is rackdata, 2nd arg is unchecked state, 3rd arg is checked state.
451 // If 4th arg is present, object_id fields will be updated accordingly to the new state.
452 // The function returns the modified rack upon success.
453 function processGridForm (&$rackData, $unchecked_state, $checked_state, $object_id = 0)
454 {
455 global $loclist, $dbxlink;
456 $rack_id = $rackData['id'];
457 $rack_name = $rackData['name'];
458 $rackchanged = FALSE;
459 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
460 {
461 for ($locidx = 0; $locidx < 3; $locidx++)
462 {
463 if ($rackData[$unit_no][$locidx]['enabled'] != TRUE)
464 continue;
465 // detect a change
466 $state = $rackData[$unit_no][$locidx]['state'];
467 if (isset ($_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"]) and $_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"] == 'on')
468 $newstate = $checked_state;
469 else
470 $newstate = $unchecked_state;
471 if ($state == $newstate)
472 continue;
473 $rackchanged = TRUE;
474 // and validate
475 $atom = $loclist[$locidx];
476 // The only changes allowed are those introduced by checkbox grid.
477 if
478 (
479 !($state == $checked_state && $newstate == $unchecked_state) &&
480 !($state == $unchecked_state && $newstate == $checked_state)
481 )
482 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, 'atom ${atom}', cannot change state from '${state}' to '${newstate}'");
483 // Here we avoid using ON DUPLICATE KEY UPDATE by first performing DELETE
484 // anyway and then looking for probable need of INSERT.
485 $query =
486 "delete from RackSpace where rack_id = ${rack_id} and " .
487 "unit_no = ${unit_no} and atom = '${atom}' limit 1";
488 $r = $dbxlink->query ($query);
489 if ($r == NULL)
490 return array ('code' => 500, 'message' => __FUNCTION__ . ": ${rack_name}: SQL DELETE query failed");
491 if ($newstate != 'F')
492 {
493 $query =
494 "insert into RackSpace(rack_id, unit_no, atom, state) " .
495 "values(${rack_id}, ${unit_no}, '${atom}', '${newstate}') ";
496 $r = $dbxlink->query ($query);
497 if ($r == NULL)
498 return array ('code' => 500, 'message' => __FUNCTION__ . ": ${rack_name}: SQL INSERT query failed");
499 }
500 if ($newstate == 'T' and $object_id != 0)
501 {
502 // At this point we already have a record in RackSpace.
503 $query =
504 "update RackSpace set object_id=${object_id} " .
505 "where rack_id=${rack_id} and unit_no=${unit_no} and atom='${atom}' limit 1";
506 $r = $dbxlink->query ($query);
507 if ($r->rowCount() == 1)
508 $rackData[$unit_no][$locidx]['object_id'] = $object_id;
509 else
510 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, atom '${atom}' failed to set object_id to '${object_id}'");
511 }
512 }
513 }
514 if ($rackchanged)
515 {
516 resetThumbCache ($rack_id);
517 return array ('code' => 200, 'message' => "${rack_name}: All changes were successfully saved.");
518 }
519 else
520 return array ('code' => 300, 'message' => "${rack_name}: No changes.");
521 }
522
523 // This function builds a list of rack-unit-atom records, which are assigned to
524 // the requested object.
525 function getMoleculeForObject ($object_id = 0)
526 {
527 if ($object_id == 0)
528 {
529 showError ("object_id == 0", __FUNCTION__);
530 return NULL;
531 }
532 $query =
533 "select rack_id, unit_no, atom from RackSpace " .
534 "where state = 'T' and object_id = ${object_id} order by rack_id, unit_no, atom";
535 $result = useSelectBlade ($query, __FUNCTION__);
536 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
537 $result->closeCursor();
538 return $ret;
539 }
540
541 // This function builds a list of rack-unit-atom records for requested molecule.
542 function getMolecule ($mid = 0)
543 {
544 if ($mid == 0)
545 {
546 showError ("mid == 0", __FUNCTION__);
547 return NULL;
548 }
549 $query =
550 "select rack_id, unit_no, atom from Atom " .
551 "where molecule_id=${mid}";
552 $result = useSelectBlade ($query, __FUNCTION__);
553 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
554 $result->closeCursor();
555 return $ret;
556 }
557
558 // returns exactly what is's named after
559 function lastInsertID ()
560 {
561 if (NULL == ($result = useSelectBlade ('select last_insert_id()', __FUNCTION__)))
562 {
563 showError ('SQL query failed!', __FUNCTION__);
564 die;
565 }
566 $row = $result->fetch (PDO::FETCH_NUM);
567 return $row[0];
568 }
569
570 // This function creates a new record in Molecule and number of linked
571 // R-U-A records in Atom.
572 function createMolecule ($molData)
573 {
574 global $dbxlink;
575 $query = "insert into Molecule values()";
576 $result1 = $dbxlink->query ($query);
577 if ($result1->rowCount() != 1)
578 {
579 showError ('Error inserting into Molecule', __FUNCTION__);
580 return NULL;
581 }
582 $molecule_id = lastInsertID();
583 foreach ($molData as $rua)
584 {
585 $rack_id = $rua['rack_id'];
586 $unit_no = $rua['unit_no'];
587 $atom = $rua['atom'];
588 $query =
589 "insert into Atom(molecule_id, rack_id, unit_no, atom) " .
590 "values (${molecule_id}, ${rack_id}, ${unit_no}, '${atom}')";
591 $result3 = $dbxlink->query ($query);
592 if ($result3 == NULL or $result3->rowCount() != 1)
593 {
594 showError ('Error inserting into Atom', __FUNCTION__);
595 return NULL;
596 }
597 }
598 return $molecule_id;
599 }
600
601 // History logger. This function assumes certain table naming convention and
602 // column design:
603 // 1. History table name equals to dictionary table name plus 'History'.
604 // 2. History table must have the same row set (w/o keys) plus one row named
605 // 'ctime' of type 'timestamp'.
606 function recordHistory ($tableName, $whereClause)
607 {
608 global $dbxlink, $remote_username;
609 $query = "insert into ${tableName}History select *, current_timestamp(), '${remote_username}' from ${tableName} where ${whereClause}";
610 $result = $dbxlink->query ($query);
611 if ($result == NULL or $result->rowCount() != 1)
612 {
613 showError ("SQL query '${query}' failed for table ${tableName}", __FUNCTION__);
614 return FALSE;
615 }
616 return TRUE;
617 }
618
619 function getRackspaceHistory ()
620 {
621 $query =
622 "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 " .
623 "MountOperation as mo inner join RackObject as ro on mo.object_id = ro.id " .
624 "inner join Dictionary on objtype_id = dict_key natural join Chapter " .
625 "where chapter_name = 'RackObjectType' order by ctime desc";
626 $result = useSelectBlade ($query, __FUNCTION__);
627 $ret = $result->fetchAll(PDO::FETCH_ASSOC);
628 $result->closeCursor();
629 return $ret;
630 }
631
632 // This function is used in renderRackspaceHistory()
633 function getOperationMolecules ($op_id = 0)
634 {
635 if ($op_id <= 0)
636 {
637 showError ("Missing argument", __FUNCTION__);
638 return;
639 }
640 $query = "select old_molecule_id, new_molecule_id from MountOperation where id = ${op_id}";
641 $result = useSelectBlade ($query, __FUNCTION__);
642 // We expect one row.
643 $row = $result->fetch (PDO::FETCH_ASSOC);
644 if ($row == NULL)
645 {
646 showError ("SQL query succeded, but returned no results.", __FUNCTION__);
647 return;
648 }
649 $omid = $row['old_molecule_id'];
650 $nmid = $row['new_molecule_id'];
651 $result->closeCursor();
652 return array ($omid, $nmid);
653 }
654
655 function getResidentRacksData ($object_id = 0, $fetch_rackdata = TRUE)
656 {
657 if ($object_id <= 0)
658 {
659 showError ('Invalid object_id', __FUNCTION__);
660 return;
661 }
662 $query = "select distinct rack_id from RackSpace where object_id = ${object_id} order by rack_id";
663 $result = useSelectBlade ($query, __FUNCTION__);
664 $rows = $result->fetchAll (PDO::FETCH_NUM);
665 $result->closeCursor();
666 $ret = array();
667 foreach ($rows as $row)
668 {
669 if (!$fetch_rackdata)
670 {
671 $ret[$row[0]] = $row[0];
672 continue;
673 }
674 $rackData = getRackData ($row[0]);
675 if ($rackData == NULL)
676 {
677 showError ('getRackData() failed', __FUNCTION__);
678 return NULL;
679 }
680 $ret[$row[0]] = $rackData;
681 }
682 $result->closeCursor();
683 return $ret;
684 }
685
686 function getObjectGroupInfo ()
687 {
688 $query =
689 'select dict_key as id, dict_value as name, count(id) as count from ' .
690 'Dictionary natural join Chapter left join RackObject on dict_key = objtype_id ' .
691 'where chapter_name = "RackObjectType" ' .
692 'group by dict_key order by dict_value';
693 $result = useSelectBlade ($query, __FUNCTION__);
694 $ret = array();
695 $ret[0] = array ('id' => 0, 'name' => 'ALL types');
696 $clist = array ('id', 'name', 'count');
697 $total = 0;
698 while ($row = $result->fetch (PDO::FETCH_ASSOC))
699 if ($row['count'] > 0)
700 {
701 $total += $row['count'];
702 foreach ($clist as $cname)
703 $ret[$row['id']][$cname] = $row[$cname];
704 }
705 $result->closeCursor();
706 $ret[0]['count'] = $total;
707 return $ret;
708 }
709
710 // This function returns objects, which have no rackspace assigned to them.
711 // Additionally it keeps rack_id parameter, so we can silently pre-select
712 // the rack required.
713 function getUnmountedObjects ()
714 {
715 $query =
716 'select dict_value as objtype_name, dict_key as objtype_id, name, label, barcode, id, asset_no from ' .
717 'RackObject inner join Dictionary on objtype_id = dict_key natural join Chapter ' .
718 'left join RackSpace on id = object_id '.
719 'where rack_id is null and chapter_name = "RackObjectType" order by dict_value, name, label, asset_no, barcode';
720 $result = useSelectBlade ($query, __FUNCTION__);
721 $ret = array();
722 $clist = array ('id', 'name', 'label', 'barcode', 'objtype_name', 'objtype_id', 'asset_no');
723 while ($row = $result->fetch (PDO::FETCH_ASSOC))
724 {
725 foreach ($clist as $cname)
726 $ret[$row['id']][$cname] = $row[$cname];
727 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
728 }
729 $result->closeCursor();
730 return $ret;
731 }
732
733 function getProblematicObjects ()
734 {
735 $query =
736 'select dict_value as objtype_name, dict_key as objtype_id, name, id, asset_no from ' .
737 'RackObject inner join Dictionary on objtype_id = dict_key natural join Chapter '.
738 'where has_problems = "yes" and chapter_name = "RackObjectType" order by objtype_name, name';
739 $result = useSelectBlade ($query, __FUNCTION__);
740 $ret = array();
741 $clist = array ('id', 'name', 'objtype_name', 'objtype_id', 'asset_no');
742 while ($row = $result->fetch (PDO::FETCH_ASSOC))
743 {
744 foreach ($clist as $cname)
745 $ret[$row['id']][$cname] = $row[$cname];
746 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
747 }
748 $result->closeCursor();
749 return $ret;
750 }
751
752 function commitAddPort ($object_id = 0, $port_name, $port_type_id, $port_label, $port_l2address)
753 {
754 if ($object_id <= 0)
755 {
756 showError ('Invalid object_id', __FUNCTION__);
757 return;
758 }
759 $port_l2address = l2addressForDatabase ($port_l2address);
760 $result = useInsertBlade
761 (
762 'Port',
763 array
764 (
765 'name' => "'${port_name}'",
766 'object_id' => "'${object_id}'",
767 'label' => "'${port_label}'",
768 'type' => "'${port_type_id}'",
769 'l2address' => "${port_l2address}"
770 )
771 );
772 if ($result)
773 return '';
774 else
775 return 'SQL query failed';
776 }
777
778 // The fifth argument may be either explicit 'NULL' or some (already quoted by the upper layer)
779 // string value. In case it is omitted, we just assign it its current value.
780 // It would be nice to simplify this semantics later.
781 function commitUpdatePort ($port_id, $port_name, $port_label, $port_l2address, $port_reservation_comment = 'reservation_comment')
782 {
783 global $dbxlink;
784 $port_l2address = l2addressForDatabase ($port_l2address);
785 $query =
786 "update Port set name='$port_name', label='$port_label', " .
787 "reservation_comment = ${port_reservation_comment}, l2address=${port_l2address} " .
788 "where id='$port_id'";
789 $result = $dbxlink->exec ($query);
790 if ($result == 1)
791 return '';
792 $errorInfo = $dbxlink->errorInfo();
793 // We could update nothing.
794 if ($errorInfo[0] == '00000')
795 return '';
796 return $errorInfo[2];
797 }
798
799 function delObjectPort ($port_id)
800 {
801 if (unlinkPort ($port_id) != '')
802 return __FUNCTION__ . ': unlinkPort() failed';
803 if (useDeleteBlade ('Port', 'id', $port_id) != TRUE)
804 return __FUNCTION__ . ': useDeleteBlade() failed';
805 return '';
806 }
807
808 function getAllIPv4Allocations ()
809 {
810 $query =
811 "select object_id as object_id, ".
812 "RackObject.name as object_name, ".
813 "IPBonds.name as name, ".
814 "INET_NTOA(ip) as ip ".
815 "from IPBonds join RackObject on id=object_id ";
816 $result = useSelectBlade ($query, __FUNCTION__);
817 $ret = array();
818 $count=0;
819 while ($row = $result->fetch (PDO::FETCH_ASSOC))
820 {
821 $ret[$count]['object_id']=$row['object_id'];
822 $ret[$count]['object_name']=$row['object_name'];
823 $ret[$count]['name']=$row['name'];
824 $ret[$count]['ip']=$row['ip'];
825 $count++;
826 }
827 $result->closeCursor();
828 return $ret;
829 }
830
831 function getEmptyPortsOfType ($type_id)
832 {
833 $query =
834 "select distinct Port.id as Port_id, ".
835 "Port.object_id as Port_object_id, ".
836 "RackObject.name as Object_name, ".
837 "Port.name as Port_name, ".
838 "Port.type as Port_type_id, ".
839 "dict_value as Port_type_name ".
840 "from ( ".
841 " ( ".
842 " Port inner join Dictionary on Port.type = dict_key natural join Chapter ".
843 " ) ".
844 " join RackObject on Port.object_id = RackObject.id ".
845 ") ".
846 "left join Link on Port.id=Link.porta or Port.id=Link.portb ".
847 "inner join PortCompat on Port.type = PortCompat.type2 ".
848 "where chapter_name = 'PortType' and PortCompat.type1 = '$type_id' and Link.porta is NULL ".
849 "and Port.reservation_comment is null order by Object_name, Port_name";
850 $result = useSelectBlade ($query, __FUNCTION__);
851 $ret = array();
852 $count=0;
853 while ($row = $result->fetch (PDO::FETCH_ASSOC))
854 {
855 $ret[$count]['Port_id']=$row['Port_id'];
856 $ret[$count]['Port_object_id']=$row['Port_object_id'];
857 $ret[$count]['Object_name']=$row['Object_name'];
858 $ret[$count]['Port_name']=$row['Port_name'];
859 $ret[$count]['Port_type_id']=$row['Port_type_id'];
860 $ret[$count]['Port_type_name']=$row['Port_type_name'];
861 $count++;
862 }
863 $result->closeCursor();
864 return $ret;
865 }
866
867 function linkPorts ($porta, $portb)
868 {
869 if ($porta == $portb)
870 return "Ports can't be the same";
871 if ($porta > $portb)
872 {
873 $tmp = $porta;
874 $porta = $portb;
875 $portb = $tmp;
876 }
877 global $dbxlink;
878 $query1 = "insert into Link set porta='${porta}', portb='{$portb}'";
879 $query2 = "update Port set reservation_comment = NULL where id = ${porta} or id = ${portb} limit 2";
880 // FIXME: who cares about the return value?
881 $result = $dbxlink->exec ($query1);
882 $result = $dbxlink->exec ($query2);
883 return '';
884 }
885
886 function unlinkPort ($port)
887 {
888 global $dbxlink;
889 $query =
890 "delete from Link where porta='$port' or portb='$port'";
891 $result = $dbxlink->exec ($query);
892 return '';
893 }
894
895 // Return a list of IPv4 allocations for the object. Each address will list
896 // all other objects, to which it is allocated (except the current object).
897 function getObjectAddresses ($object_id = 0)
898 {
899 if ($object_id == 0)
900 {
901 showError ('Invalid object_id', __FUNCTION__);
902 return;
903 }
904 $query =
905 "select ".
906 "IPAddress.name as IPAddress_name, ".
907 "IPAddress.reserved as IPAddress_reserved, ".
908 "IPBonds.name as IPBonds_name, ".
909 "INET_NTOA(IPBonds.ip) as IPBonds_ip, ".
910 "IPBonds.type as IPBonds_type, ".
911 "RemoteBonds.name as RemoteBonds_name, ".
912 "RemoteBonds.type as RemoteBonds_type, ".
913 "RemoteBonds.object_id as RemoteBonds_object_id ".
914 "from IPBonds " .
915 "left join IPBonds as RemoteBonds on IPBonds.ip=RemoteBonds.ip " .
916 "and IPBonds.object_id!=RemoteBonds.object_id " .
917 "left join IPAddress on IPBonds.ip=IPAddress.ip " .
918 "where ".
919 "IPBonds.object_id = ${object_id} ".
920 "order by IPBonds.ip, RemoteBonds.object_id";
921 $result = useSelectBlade ($query, __FUNCTION__);
922 $ret=array();
923 $count=0;
924 $refcount=0;
925 $prev_ip = 0;
926 // Free the DB connection to enable subqueries.
927 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
928 $result->closeCursor();
929 foreach ($rows as $row)
930 {
931 if ($prev_ip != $row['IPBonds_ip'])
932 {
933 $count++;
934 $refcount=0;
935 $prev_ip = $row['IPBonds_ip'];
936 $ret[$count]['address_name'] = $row['IPAddress_name'];
937 $ret[$count]['address_reserved'] = $row['IPAddress_reserved'];
938 $ret[$count]['ip'] = $row['IPBonds_ip'];
939 $ret[$count]['name'] = $row['IPBonds_name'];
940 $ret[$count]['type'] = $row['IPBonds_type'];
941 $ret[$count]['references'] = array();
942 }
943
944 if ($row['RemoteBonds_type'])
945 {
946 $ret[$count]['references'][$refcount]['type'] = $row['RemoteBonds_type'];
947 $ret[$count]['references'][$refcount]['name'] = $row['RemoteBonds_name'];
948 $ret[$count]['references'][$refcount]['object_id'] = $row['RemoteBonds_object_id'];
949 if (empty ($row['RemoteBonds_object_id']))
950 $ret[$count]['references'][$refcount]['object_name'] = '';
951 else
952 {
953 $oi = getObjectInfo ($row['RemoteBonds_object_id']);
954 $ret[$count]['references'][$refcount]['object_name'] = displayedName ($oi);
955 }
956 $refcount++;
957 }
958 }
959 return $ret;
960 }
961
962 // FIXME: unused function
963 function getIPAddress ($ip = 0)
964 {
965 $ret = array
966 (
967 'bonds' => array(),
968 'outpf' => array(),
969 'inpf' => array(),
970 'vslist' => array(),
971 'rslist' => array(),
972 'exists' => 0,
973 'name' => '',
974 'reserved' => 'no'
975 );
976 $query = "select name, reserved from IPAddress ".
977 "where ip = INET_ATON('$ip') and (reserved = 'yes' or name != '')";
978 $result = useSelectBlade ($query, __FUNCTION__);
979 if ($row = $result->fetch (PDO::FETCH_ASSOC))
980 {
981 $ret['exists'] = 1;
982 $ret['name'] = $row['name'];
983 $ret['reserved'] = $row['reserved'];
984 }
985 $result->closeCursor();
986 unset ($result);
987
988 $query =
989 "select ".
990 "IPBonds.object_id as object_id, ".
991 "IPBonds.name as name, ".
992 "IPBonds.type as type, ".
993 "objtype_id, dict_value as objtype_name, " .
994 "RackObject.name as object_name ".
995 "from IPBonds join RackObject on IPBonds.object_id=RackObject.id ".
996 "left join Dictionary on objtype_id=dict_key natural join Chapter " .
997 "where IPBonds.ip=INET_ATON('$ip') ".
998 "and chapter_name = 'RackObjectType' " .
999 "order by RackObject.id, IPBonds.name";
1000 $result = useSelectBlade ($query, __FUNCTION__);
1001 $count = 0;
1002 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1003 {
1004 $ret['bonds'][$count]['object_id'] = $row['object_id'];
1005 $ret['bonds'][$count]['name'] = $row['name'];
1006 $ret['bonds'][$count]['type'] = $row['type'];
1007 $qo = array();
1008 $qo['name'] = $row['object_name'];
1009 $qo['objtype_id'] = $row['objtype_id'];
1010 $qo['objtype_name'] = $row['objtype_name'];
1011 $ret['bonds'][$count]['object_name'] = displayedName ($qo);
1012 $count++;
1013 $ret['exists'] = 1;
1014 }
1015 $result->closeCursor();
1016 unset ($result);
1017
1018 $query = "select id, vport, proto, name from IPVirtualService where vip = inet_aton('${ip}')";
1019 $result = useSelectBlade ($query, __FUNCTION__);
1020 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1021 {
1022 $new = $row;
1023 $new['vip'] = $ip;
1024 $ret['vslist'][] = $new;
1025 }
1026 $result->closeCursor();
1027 unset ($result);
1028
1029 $query = "select inservice, rsport, IPRSPool.id as pool_id, IPRSPool.name as poolname from " .
1030 "IPRealServer inner join IPRSPool on rspool_id = IPRSPool.id " .
1031 "where rsip = inet_aton('${ip}')";
1032 $result = useSelectBlade ($query, __FUNCTION__);
1033 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1034 {
1035 $new = $row;
1036 $new['rsip'] = $ip;
1037 $ret['rslist'][] = $new;
1038 }
1039 $result->closeCursor();
1040 unset ($result);
1041
1042 $query =
1043 "select " .
1044 "proto, " .
1045 "INET_NTOA(localip) as localip, " .
1046 "localport, " .
1047 "INET_NTOA(remoteip) as remoteip, " .
1048 "remoteport, " .
1049 "description " .
1050 "from PortForwarding " .
1051 "where remoteip = inet_aton('${ip}') or localip = inet_aton('${ip}') " .
1052 "order by localip, localport, remoteip, remoteport, proto";
1053 $result = useSelectBlade ($query, __FUNCTION__);
1054 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1055 {
1056 if ($row['remoteip'] == $ip)
1057 $ret['inpf'][] = $row;
1058 if ($row['localip'] == $ip)
1059 $ret['outpf'][] = $row;
1060 }
1061 $result->closeCursor();
1062 unset ($result);
1063
1064 return $ret;
1065 }
1066
1067 // Check the range requested for meaningful IPv4 records, build them
1068 // into a list and return. Return an empty list if nothing matched.
1069 // Both arguments are expected in signed int32 form. The resulting list
1070 // is keyed by uint32 form of each IP address, items aren't sorted.
1071 function scanIPv4Space ($i32_first, $i32_last)
1072 {
1073 $ret = array();
1074 $addrtemplate = array
1075 (
1076 'name' => '',
1077 'reserved' => 'no',
1078 'bonds' => array(),
1079 'outpf' => array(),
1080 'inpf' => array(),
1081 'vslist' => array(),
1082 'rslist' => array(),
1083 'allocs' => array(),
1084 'lblist' => array()
1085 );
1086 $dnamechache = array();
1087
1088 $db_first = sprintf ('%u', 0x00000000 + $i32_first);
1089 $db_last = sprintf ('%u', 0x00000000 + $i32_last);
1090 // 1. collect labels and reservations
1091 $query = "select INET_NTOA(ip) as ip, name, reserved from IPAddress ".
1092 "where ip between ${db_first} and ${db_last} and (reserved = 'yes' or name != '')";
1093 $result = useSelectBlade ($query, __FUNCTION__);
1094 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1095 {
1096 $ip_bin = ip2long ($row['ip']);
1097 if (!isset ($ret[$ip_bin]))
1098 {
1099 $ret[$ip_bin] = $addrtemplate;
1100 $ret[$ip_bin]['ip'] = $row['ip'];
1101 }
1102 $ret[$ip_bin]['name'] = $row['name'];
1103 $ret[$ip_bin]['reserved'] = $row['reserved'];
1104 }
1105 unset ($result);
1106
1107 // 2. check for allocations
1108 $query =
1109 "select INET_NTOA(ipb.ip) as ip, ro.id as object_id, " .
1110 "ro.name as object_name, ipb.name, ipb.type, objtype_id, " .
1111 "dict_value as objtype_name from " .
1112 "IPBonds as ipb inner join RackObject as ro on ipb.object_id = ro.id " .
1113 "left join Dictionary on objtype_id=dict_key natural join Chapter " .
1114 "where ip between ${db_first} and ${db_last} " .
1115 "and chapter_name = 'RackObjectType'" .
1116 "order by ipb.type, object_name";
1117 $result = useSelectBlade ($query, __FUNCTION__);
1118 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1119 {
1120 $ip_bin = ip2long ($row['ip']);
1121 if (!isset ($ret[$ip_bin]))
1122 {
1123 $ret[$ip_bin] = $addrtemplate;
1124 $ret[$ip_bin]['ip'] = $row['ip'];
1125 }
1126 if (!isset ($dnamecache[$row['object_id']]))
1127 {
1128 $quasiobject['name'] = $row['object_name'];
1129 $quasiobject['objtype_id'] = $row['objtype_id'];
1130 $quasiobject['objtype_name'] = $row['objtype_name'];
1131 $dnamecache[$row['object_id']] = displayedName ($quasiobject);
1132 }
1133 $tmp = array();
1134 foreach (array ('object_id', 'type', 'name') as $cname)
1135 $tmp[$cname] = $row[$cname];
1136 $tmp['object_name'] = $dnamecache[$row['object_id']];
1137 $ret[$ip_bin]['allocs'][] = $tmp;
1138 }
1139 unset ($result);
1140
1141 // 3. look for virtual services and related LB
1142 $query = "select vs_id, inet_ntoa(vip) as ip, vport, proto, vs.name, " .
1143 "object_id, objtype_id, ro.name as object_name, dict_value as objtype_name from " .
1144 "IPVirtualService as vs inner join IPLoadBalancer as lb on vs.id = lb.vs_id " .
1145 "inner join RackObject as ro on lb.object_id = ro.id " .
1146 "left join Dictionary on objtype_id=dict_key " .
1147 "natural join Chapter " .
1148 "where vip between ${db_first} and ${db_last} " .
1149 "and chapter_name = 'RackObjectType'" .
1150 "order by vport, proto, ro.name, object_id";
1151 $result = useSelectBlade ($query, __FUNCTION__);
1152 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1153 {
1154 $ip_bin = ip2long ($row['ip']);
1155 if (!isset ($ret[$ip_bin]))
1156 {
1157 $ret[$ip_bin] = $addrtemplate;
1158 $ret[$ip_bin]['ip'] = $row['ip'];
1159 }
1160 if (!isset ($dnamecache[$row['object_id']]))
1161 {
1162 $quasiobject['name'] = $row['object_name'];
1163 $quasiobject['objtype_id'] = $row['objtype_id'];
1164 $quasiobject['objtype_name'] = $row['objtype_name'];
1165 $dnamecache[$row['object_id']] = displayedName ($quasiobject);
1166 }
1167 $tmp = array();
1168 foreach (array ('object_id', 'vport', 'proto', 'vs_id', 'name') as $cname)
1169 $tmp[$cname] = $row[$cname];
1170 $tmp['object_name'] = $dnamecache[$row['object_id']];
1171 $tmp['vip'] = $row['ip'];
1172 $ret[$ip_bin]['lblist'][] = $tmp;
1173 }
1174 unset ($result);
1175
1176 // 4. don't forget about real servers along with pools
1177 $query = "select inet_ntoa(rsip) as ip, inservice, rsport, rspool_id, rsp.name as rspool_name from " .
1178 "IPRealServer as rs inner join IPRSPool as rsp on rs.rspool_id = rsp.id " .
1179 "where rsip between ${db_first} and ${db_last} " .
1180 "order by ip, rsport, rspool_id";
1181 $result = useSelectBlade ($query, __FUNCTION__);
1182 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1183 {
1184 $ip_bin = ip2long ($row['ip']);
1185 if (!isset ($ret[$ip_bin]))
1186 {
1187 $ret[$ip_bin] = $addrtemplate;
1188 $ret[$ip_bin]['ip'] = $row['ip'];
1189 }
1190 $tmp = array();
1191 foreach (array ('rspool_id', 'rsport', 'rspool_name', 'inservice') as $cname)
1192 $tmp[$cname] = $row[$cname];
1193 $ret[$ip_bin]['rslist'][] = $tmp;
1194 }
1195 unset ($result);
1196
1197 // 5. add NAT rules, part 1
1198 $query =
1199 "select " .
1200 "proto, " .
1201 "INET_NTOA(localip) as localip, " .
1202 "localport, " .
1203 "INET_NTOA(remoteip) as remoteip, " .
1204 "remoteport, " .
1205 "description " .
1206 "from PortForwarding " .
1207 "where remoteip between ${db_first} and ${db_last} or " .
1208 "localip between ${db_first} and ${db_last} " .
1209 "order by localip, localport, remoteip, remoteport, proto";
1210 $result = useSelectBlade ($query, __FUNCTION__);
1211 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1212 {
1213 $remoteip_bin = ip2long ($row['remoteip']);
1214 $localip_bin = ip2long ($row['localip']);
1215 if ($i32_first <= $remoteip_bin and $remoteip_bin <= $i32_last)
1216 {
1217 if (!isset ($ret[$remoteip_bin]))
1218 {
1219 $ret[$remoteip_bin] = $addrtemplate;
1220 $ret[$remoteip_bin]['ip'] = $row['remoteip'];
1221 }
1222 $ret[$remoteip_bin]['inpf'][] = $row;
1223 }
1224 if ($i32_first <= $localip_bin and $localip_bin <= $i32_last)
1225 {
1226 if (!isset ($ret[$localip_bin]))
1227 {
1228 $ret[$localip_bin] = $addrtemplate;
1229 $ret[$localip_bin]['ip'] = $row['localip'];
1230 }
1231 $ret[$localip_bin]['outpf'][] = $row;
1232 }
1233 }
1234 return $ret;
1235 }
1236
1237 // Return summary data about an IPv4 prefix, if it exists, or NULL otherwise.
1238 function getIPv4NetworkInfo ($id = 0)
1239 {
1240 if ($id <= 0)
1241 {
1242 showError ('Invalid arg', __FUNCTION__);
1243 return NULL;
1244 }
1245 $query = "select INET_NTOA(ip) as ip, mask, name ".
1246 "from IPRanges where id = $id";
1247 $result = useSelectBlade ($query, __FUNCTION__);
1248 $ret = $result->fetch (PDO::FETCH_ASSOC);
1249 if ($ret == NULL)
1250 return NULL;
1251 unset ($result);
1252 $ret['id'] = $id;
1253 $ret['ip_bin'] = ip2long ($ret['ip']);
1254 $ret['mask_bin'] = binMaskFromDec ($ret['mask']);
1255 $ret['mask_bin_inv'] = binInvMaskFromDec ($ret['mask']);
1256 $ret['db_first'] = sprintf ('%u', 0x00000000 + $ret['ip_bin'] & $ret['mask_bin']);
1257 $ret['db_last'] = sprintf ('%u', 0x00000000 + $ret['ip_bin'] | ($ret['mask_bin_inv']));
1258 return $ret;
1259 }
1260
1261 function getIPv4Network ($id = 0)
1262 {
1263 $ret = getIPv4NetworkInfo ($id);
1264 if (!$ret)
1265 {
1266 showError ('Record not found', __FUNCTION__);
1267 return NULL;
1268 }
1269 $ret['addrlist'] = scanIPv4Space ($ret['db_first'], $ret['db_last']);
1270 markupIPv4AddrList ($ret['addrlist']);
1271 return $ret;
1272 }
1273
1274 function getIPv4Address ($dottedquad = '')
1275 {
1276 if ($dottedquad == '')
1277 {
1278 showError ('Invalid arg', __FUNCTION__);
1279 return NULL;
1280 }
1281 $i32 = ip2long ($dottedquad); // signed 32 bit
1282 $scanres = scanIPv4Space ($i32, $i32);
1283 if (!isset ($scanres[$i32]))
1284 return NULL;
1285 markupIPv4AddrList ($scanres);
1286 return $scanres[$i32];
1287 }
1288
1289 function bindIpToObject ($ip = '', $object_id = 0, $name = '', $type = '')
1290 {
1291 $result = useInsertBlade
1292 (
1293 'IPBonds',
1294 array
1295 (
1296 'ip' => "INET_ATON('$ip')",
1297 'object_id' => "'${object_id}'",
1298 'name' => "'${name}'",
1299 'type' => "'${type}'"
1300 )
1301 );
1302 return $result ? '' : (__FUNCTION__ . '(): useInsertBlade() failed');
1303 }
1304
1305 function getAddressspaceList ($tagfilter = array(), $tfmode = 'any')
1306 {
1307 $whereclause = getWhereClause ($tagfilter);
1308 $query =
1309 "select distinct ".
1310 "id as IPRanges_id, ".
1311 "INET_NTOA(ip) as IPRanges_ip, ".
1312 "mask as IPRanges_mask, ".
1313 "name as IPRanges_name ".
1314 "from IPRanges left join TagStorage on IPRanges.id = TagStorage.target_id and target_realm = 'ipv4net' " .
1315 "where true ${whereclause} " .
1316 " order by ip";
1317 $result = useSelectBlade ($query, __FUNCTION__);
1318 $ret=array();
1319 $count=0;
1320 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1321 {
1322 $ret[$count]['id'] = $row['IPRanges_id'];
1323 $ret[$count]['ip'] = $row['IPRanges_ip'];
1324 $ret[$count]['ip_bin'] = ip2long($row['IPRanges_ip']);
1325 $ret[$count]['name'] = $row['IPRanges_name'];
1326 $ret[$count]['mask'] = $row['IPRanges_mask'];
1327 $ret[$count]['mask_bin'] = binMaskFromDec($row['IPRanges_mask']);
1328 $ret[$count]['mask_bin_inv'] = binInvMaskFromDec($row['IPRanges_mask']);
1329 $count++;
1330 }
1331 $result->closeCursor();
1332 return $ret;
1333
1334 }
1335
1336 // FIXME: unused function
1337 function getIPRange ($id = 0)
1338 {
1339 global $dbxlink;
1340 $query =
1341 "select ".
1342 "id as IPRanges_id, ".
1343 "INET_NTOA(ip) as IPRanges_ip, ".
1344 "mask as IPRanges_mask, ".
1345 "name as IPRanges_name ".
1346 "from IPRanges ".
1347 "where id = '$id'";
1348 $result = useSelectBlade ($query, __FUNCTION__);
1349 $ret = array();
1350 $row = $result->fetch (PDO::FETCH_ASSOC);
1351 if ($row == NULL)
1352 return $ret;
1353 $ret['id'] = $row['IPRanges_id'];
1354 $ret['ip'] = $row['IPRanges_ip'];
1355 $ret['ip_bin'] = ip2long ($row['IPRanges_ip']);
1356 $ret['mask_bin'] = binMaskFromDec($row['IPRanges_mask']);
1357 $ret['mask_bin_inv'] = binInvMaskFromDec($row['IPRanges_mask']);
1358 $ret['name'] = $row['IPRanges_name'];
1359 $ret['mask'] = $row['IPRanges_mask'];
1360 $ret['addrlist'] = array();
1361 $result->closeCursor();
1362 unset ($result);
1363 // We risk losing some significant bits in an unsigned 32bit integer,
1364 // unless it is converted to a string.
1365 $db_first = "'" . sprintf ('%u', 0x00000000 + $ret['ip_bin'] & $ret['mask_bin']) . "'";
1366 $db_last = "'" . sprintf ('%u', 0x00000000 + $ret['ip_bin'] | ($ret['mask_bin_inv'])) . "'";
1367
1368 // Don't try to build up the whole structure in a single pass. Request
1369 // the list of user comments and reservations and merge allocations in
1370 // at a latter point.
1371 $query =
1372 "select INET_NTOA(ip) as ip, name, reserved from IPAddress " .
1373 "where ip between ${db_first} and ${db_last} " .
1374 "and (reserved = 'yes' or name != '')";
1375 $result = $dbxlink->query ($query);
1376 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1377 {
1378 $ip_bin = ip2long ($row['ip']);
1379 $ret['addrlist'][$ip_bin] = $row;
1380 $tmp = array();
1381 foreach (array ('ip', 'name', 'reserved') as $cname)
1382 $tmp[$cname] = $row[$cname];
1383 $tmp['references'] = array();
1384 $tmp['lbrefs'] = array();
1385 $tmp['rsrefs'] = array();
1386 $ret['addrlist'][$ip_bin] = $tmp;
1387 }
1388 $result->closeCursor();
1389 unset ($result);
1390
1391 $query =
1392 "select INET_NTOA(ipb.ip) as ip, ro.id as object_id, " .
1393 "ro.name as object_name, ipb.name, ipb.type, objtype_id, " .
1394 "dict_value as objtype_name from " .
1395 "IPBonds as ipb inner join RackObject as ro on ipb.object_id = ro.id " .
1396 "left join Dictionary on objtype_id=dict_key natural join Chapter " .
1397 "where ip between ${db_first} and ${db_last} " .
1398 "and chapter_name = 'RackObjectType'" .
1399 "order by ipb.type, object_name";
1400 $result = useSelectBlade ($query, __FUNCTION__);
1401 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1402 {
1403 $ip_bin = ip2long ($row['ip']);
1404 if (!isset ($ret['addrlist'][$ip_bin]))
1405 {
1406 $ret['addrlist'][$ip_bin] = array();
1407 $ret['addrlist'][$ip_bin]['ip'] = $row['ip'];
1408 $ret['addrlist'][$ip_bin]['name'] = '';
1409 $ret['addrlist'][$ip_bin]['reserved'] = 'no';
1410 $ret['addrlist'][$ip_bin]['references'] = array();
1411 $ret['addrlist'][$ip_bin]['lbrefs'] = array();
1412 $ret['addrlist'][$ip_bin]['rsrefs'] = array();
1413 }
1414 $tmp = array();
1415 foreach (array ('object_id', 'type', 'name') as $cname)
1416 $tmp[$cname] = $row[$cname];
1417 $quasiobject['name'] = $row['object_name'];
1418 $quasiobject['objtype_id'] = $row['objtype_id'];
1419 $quasiobject['objtype_name'] = $row['objtype_name'];
1420 $tmp['object_name'] = displayedName ($quasiobject);
1421 $ret['addrlist'][$ip_bin]['references'][] = $tmp;
1422 }
1423 $result->closeCursor();
1424 unset ($result);
1425
1426 $query = "select vs_id, inet_ntoa(vip) as ip, vport, proto, " .
1427 "object_id, objtype_id, ro.name, dict_value as objtype_name from " .
1428 "IPVirtualService as vs inner join IPLoadBalancer as lb on vs.id = lb.vs_id " .
1429 "inner join RackObject as ro on lb.object_id = ro.id " .
1430 "left join Dictionary on objtype_id=dict_key " .
1431 "natural join Chapter " .
1432 "where vip between ${db_first} and ${db_last} " .
1433 "and chapter_name = 'RackObjectType'" .
1434 "order by vport, proto, ro.name, object_id";
1435 $result = useSelectBlade ($query, __FUNCTION__);
1436 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1437 {
1438 $ip_bin = ip2long ($row['ip']);
1439 if (!isset ($ret['addrlist'][$ip_bin]))
1440 {
1441 $ret['addrlist'][$ip_bin] = array();
1442 $ret['addrlist'][$ip_bin]['ip'] = $row['ip'];
1443 $ret['addrlist'][$ip_bin]['name'] = '';
1444 $ret['addrlist'][$ip_bin]['reserved'] = 'no';
1445 $ret['addrlist'][$ip_bin]['references'] = array();
1446 $ret['addrlist'][$ip_bin]['lbrefs'] = array();
1447 $ret['addrlist'][$ip_bin]['rsrefs'] = array();
1448 }
1449 $tmp = $qbject = array();
1450 foreach (array ('object_id', 'vport', 'proto', 'vs_id') as $cname)
1451 $tmp[$cname] = $row[$cname];
1452 foreach (array ('name', 'objtype_id', 'objtype_name') as $cname)
1453 $qobject[$cname] = $row[$cname];
1454 $tmp['object_name'] = displayedName ($qobject);
1455 $ret['addrlist'][$ip_bin]['lbrefs'][] = $tmp;
1456 }
1457 $result->closeCursor();
1458 unset ($result);
1459
1460 $query = "select inet_ntoa(rsip) as ip, rsport, rspool_id, rsp.name as rspool_name from " .
1461 "IPRealServer as rs inner join IPRSPool as rsp on rs.rspool_id = rsp.id " .
1462 "where rsip between ${db_first} and ${db_last} " .
1463 "order by ip, rsport, rspool_id";
1464 $result = useSelectBlade ($query, __FUNCTION__);
1465 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1466 {
1467 $ip_bin = ip2long ($row['ip']);
1468 if (!isset ($ret['addrlist'][$ip_bin]))
1469 {
1470 $ret['addrlist'][$ip_bin] = array();
1471 $ret['addrlist'][$ip_bin]['ip'] = $row['ip'];
1472 $ret['addrlist'][$ip_bin]['name'] = '';
1473 $ret['addrlist'][$ip_bin]['reserved'] = 'no';
1474 $ret['addrlist'][$ip_bin]['references'] = array();
1475 $ret['addrlist'][$ip_bin]['lbrefs'] = array();
1476 $ret['addrlist'][$ip_bin]['rsrefs'] = array();
1477 }
1478 $tmp = array();
1479 foreach (array ('rspool_id', 'rsport', 'rspool_name') as $cname)
1480 $tmp[$cname] = $row[$cname];
1481 $ret['addrlist'][$ip_bin]['rsrefs'][] = $tmp;
1482 }
1483
1484 return $ret;
1485 }
1486
1487 // Return the id of the smallest IPv4 network containing the given IPv4 address
1488 // or NULL, if nothing was found.
1489 function getIPv4AddressNetworkId ($dottedquad)
1490 {
1491 $query = 'select id from IPRanges where ' .
1492 "inet_aton('${dottedquad}') & (4294967295 >> (32 - mask)) << (32 - mask) = ip " .
1493 'order by mask desc limit 1';
1494 $result = useSelectBlade ($query, __FUNCTION__);
1495 if ($row = $result->fetch (PDO::FETCH_ASSOC))
1496 return $row['id'];
1497 return NULL;
1498 }
1499
1500 function updateRange ($id=0, $name='')
1501 {
1502 global $dbxlink;
1503 $query =
1504 "update IPRanges set name='$name' where id='$id'";
1505 $result = $dbxlink->exec ($query);
1506 return '';
1507 }
1508
1509 // This function is actually used not only to update, but also to create records,
1510 // that's why ON DUPLICATE KEY UPDATE was replaced by DELETE-INSERT pair
1511 // (MySQL 4.0 workaround).
1512 function updateAddress ($ip = 0, $name = '', $reserved = 'no')
1513 {
1514 // DELETE may safely fail.
1515 $r = useDeleteBlade ('IPAddress', 'ip', "INET_ATON('${ip}')", FALSE);
1516 // INSERT may appear not necessary.
1517 if ($name == '' and $reserved == 'no')
1518 return '';
1519 if (useInsertBlade ('IPAddress', array ('name' => "'${name}'", 'reserved' => "'${reserved}'", 'ip' => "INET_ATON('${ip}')")))
1520 return '';
1521 else
1522 return __FUNCTION__ . '(): useInsertBlade() failed';
1523 }
1524
1525 function updateBond ($ip='', $object_id=0, $name='', $type='')
1526 {
1527 global $dbxlink;
1528
1529 $query =
1530 "update IPBonds set name='$name', type='$type' where ip=INET_ATON('$ip') and object_id='$object_id'";
1531 $result = $dbxlink->exec ($query);
1532 return '';
1533 }
1534
1535 function unbindIpFromObject ($ip='', $object_id=0)
1536 {
1537 global $dbxlink;
1538
1539 $query =
1540 "delete from IPBonds where ip=INET_ATON('$ip') and object_id='$object_id'";
1541 $result = $dbxlink->exec ($query);
1542 return '';
1543 }
1544
1545 // This function returns either all or one user account. Array key is user name.
1546 function getUserAccounts ($tagfilter = array(), $tfmode = 'any')
1547 {
1548 $whereclause = getWhereClause ($tagfilter);
1549 $query =
1550 'select user_id, user_name, user_password_hash, user_realname, user_enabled ' .
1551 'from UserAccount left join TagStorage ' .
1552 "on UserAccount.user_id = TagStorage.target_id and target_realm = 'user' " .
1553 "where true ${whereclause} " .
1554 'order by user_name';
1555 $result = useSelectBlade ($query, __FUNCTION__);
1556 $ret = array();
1557 $clist = array ('user_id', 'user_name', 'user_realname', 'user_password_hash', 'user_enabled');
1558 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1559 foreach ($clist as $cname)
1560 $ret[$row['user_name']][$cname] = $row[$cname];
1561 $result->closeCursor();
1562 return $ret;
1563 }
1564
1565 function searchByl2address ($l2addr)
1566 {
1567 $l2addr = l2addressForDatabase ($l2addr);
1568 $query = "select object_id, Port.id as port_id from RackObject as ro inner join Port on ro.id = Port.object_id " .
1569 "where l2address = ${l2addr}";
1570 $result = useSelectBlade ($query, __FUNCTION__);
1571 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
1572 $result->closeCursor();
1573 if (count ($rows) == 0) // No results.
1574 return NULL;
1575 if (count ($rows) == 1) // Target found.
1576 return $rows[0];
1577 showError ('More than one results was found. This is probably a broken unique key.', __FUNCTION__);
1578 return NULL;
1579 }
1580
1581 function getIPv4PrefixSearchResult ($terms)
1582 {
1583 $query = "select id, inet_ntoa(ip) as ip, mask, name from IPRanges where ";
1584 $or = '';
1585 foreach (explode (' ', $terms) as $term)
1586 {
1587 $query .= $or . "name like '%${term}%'";
1588 $or = ' or ';
1589 }
1590 $result = useSelectBlade ($query, __FUNCTION__);
1591 $ret = array();
1592 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1593 $ret[] = $row;
1594 return $ret;
1595 }
1596
1597 function getIPv4AddressSearchResult ($terms)
1598 {
1599 $query = "select inet_ntoa(ip) as ip, name from IPAddress where ";
1600 $or = '';
1601 foreach (explode (' ', $terms) as $term)
1602 {
1603 $query .= $or . "name like '%${term}%'";
1604 $or = ' or ';
1605 }
1606 $result = useSelectBlade ($query, __FUNCTION__);
1607 $ret = array();
1608 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1609 $ret[] = $row;
1610 return $ret;
1611 }
1612
1613 function getIPv4RSPoolSearchResult ($terms)
1614 {
1615 $query = "select id as pool_id, name from IPRSPool where ";
1616 $or = '';
1617 foreach (explode (' ', $terms) as $term)
1618 {
1619 $query .= $or . "name like '%${term}%'";
1620 $or = ' or ';
1621 }
1622 $result = useSelectBlade ($query, __FUNCTION__);
1623 $ret = array();
1624 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1625 $ret[] = $row;
1626 return $ret;
1627 }
1628
1629 function getIPv4VServiceSearchResult ($terms)
1630 {
1631 $query = "select id, inet_ntoa(vip) as vip, vport, proto, name from IPVirtualService where ";
1632 $or = '';
1633 foreach (explode (' ', $terms) as $term)
1634 {
1635 $query .= $or . "name like '%${term}%'";
1636 $or = ' or ';
1637 }
1638 $result = useSelectBlade ($query, __FUNCTION__);
1639 $ret = array();
1640 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1641 $ret[] = $row;
1642 return $ret;
1643 }
1644
1645 function getAccountSearchResult ($terms)
1646 {
1647 return getSearchResultByField
1648 (
1649 'UserAccount',
1650 array ('user_id', 'user_name', 'user_realname'),
1651 'user_name',
1652 $terms,
1653 'user_name'
1654 );
1655 }
1656
1657 function getSearchResultByField ($tname, $rcolumns, $scolumn, $terms, $ocolumn = '')
1658 {
1659 $pfx = '';
1660 $query = 'select ';
1661 foreach ($rcolumns as $col)
1662 {
1663 $query .= $pfx . $col;
1664 $pfx = ', ';
1665 }
1666 $pfx = '';
1667 $query .= " from ${tname} where ";
1668 foreach (explode (' ', $terms) as $term)
1669 {
1670 $query .= $pfx . "${scolumn} like '%${term}%'";
1671 $pfx = ' or ';
1672 }
1673 if ($ocolumn != '')
1674 $query .= " order by ${ocolumn}";
1675 $result = useSelectBlade ($query, __FUNCTION__);
1676 $ret = array();
1677 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1678 $ret[] = $row;
1679 return $ret;
1680 }
1681
1682 // This function returns either port ID or NULL for specified arguments.
1683 function getPortID ($object_id, $port_name)
1684 {
1685 $query = "select id from Port where object_id=${object_id} and name='${port_name}' limit 2";
1686 $result = useSelectBlade ($query, __FUNCTION__);
1687 $rows = $result->fetchAll (PDO::FETCH_NUM);
1688 if (count ($rows) != 1)
1689 return NULL;
1690 $ret = $rows[0][0];
1691 $result->closeCursor();
1692 return $ret;
1693 }
1694
1695 function commitCreateUserAccount ($username, $realname, $password)
1696 {
1697 return useInsertBlade
1698 (
1699 'UserAccount',
1700 array
1701 (
1702 'user_name' => "'${username}'",
1703 'user_realname' => "'${realname}'",
1704 'user_password_hash' => "'${password}'"
1705 )
1706 );
1707 }
1708
1709 function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
1710 {
1711 global $dbxlink;
1712 $query =
1713 "update UserAccount set user_name = '${new_username}', user_realname = '${new_realname}', " .
1714 "user_password_hash = '${new_password}' where user_id = ${id} limit 1";
1715 $result = $dbxlink->query ($query);
1716 if ($result == NULL)
1717 {
1718 showError ('SQL query failed', __FUNCTION__);
1719 die;
1720 }
1721 return TRUE;
1722 }
1723
1724 function commitEnableUserAccount ($id, $new_enabled_value)
1725 {
1726 global $dbxlink;
1727 $query =
1728 "update UserAccount set user_enabled = '${new_enabled_value}' " .
1729 "where user_id = ${id} limit 1";
1730 $result = $dbxlink->query ($query);
1731 if ($result == NULL)
1732 {
1733 showError ('SQL query failed', __FUNCTION__);
1734 die;
1735 }
1736 return TRUE;
1737 }
1738
1739 // This function returns an array of all port type pairs from PortCompat table.
1740 function getPortCompat ()
1741 {
1742 $query =
1743 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
1744 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
1745 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
1746 "inner join Chapter as c1 on d1.chapter_no = c1.chapter_no " .
1747 "inner join Chapter as c2 on d2.chapter_no = c2.chapter_no " .
1748 "where c1.chapter_name = 'PortType' and c2.chapter_name = 'PortType'";
1749 $result = useSelectBlade ($query, __FUNCTION__);
1750 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
1751 $result->closeCursor();
1752 return $ret;
1753 }
1754
1755 function removePortCompat ($type1 = 0, $type2 = 0)
1756 {
1757 global $dbxlink;
1758 if ($type1 == 0 or $type2 == 0)
1759 {
1760 showError ('Invalid arguments', __FUNCTION__);
1761 die;
1762 }
1763 $query = "delete from PortCompat where type1 = ${type1} and type2 = ${type2} limit 1";
1764 $result = $dbxlink->query ($query);
1765 if ($result == NULL)
1766 {
1767 showError ('SQL query failed', __FUNCTION__);
1768 die;
1769 }
1770 return TRUE;
1771 }
1772
1773 function addPortCompat ($type1 = 0, $type2 = 0)
1774 {
1775 if ($type1 <= 0 or $type2 <= 0)
1776 {
1777 showError ('Invalid arguments', __FUNCTION__);
1778 die;
1779 }
1780 return useInsertBlade
1781 (
1782 'PortCompat',
1783 array ('type1' => $type1, 'type2' => $type2)
1784 );
1785 }
1786
1787 // This function returns the dictionary as an array of trees, each tree
1788 // representing a single chapter. Each element has 'id', 'name', 'sticky'
1789 // and 'word' keys with the latter holding all the words within the chapter.
1790 function getDict ($parse_links = FALSE)
1791 {
1792 $query1 =
1793 "select chapter_name, Chapter.chapter_no, dict_key, dict_value, sticky from " .
1794 "Chapter natural left join Dictionary order by chapter_name, dict_value";
1795 $result = useSelectBlade ($query1, __FUNCTION__);
1796 $dict = array();
1797 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1798 {
1799 $chapter_no = $row['chapter_no'];
1800 if (!isset ($dict[$chapter_no]))
1801 {
1802 $dict[$chapter_no]['no'] = $chapter_no;
1803 $dict[$chapter_no]['name'] = $row['chapter_name'];
1804 $dict[$chapter_no]['sticky'] = $row['sticky'] == 'yes' ? TRUE : FALSE;
1805 $dict[$chapter_no]['word'] = array();
1806 }
1807 if ($row['dict_key'] != NULL)
1808 {
1809 $dict[$chapter_no]['word'][$row['dict_key']] = $parse_links ?
1810 parseWikiLink ($row['dict_value'], 'a') : $row['dict_value'];
1811 $dict[$chapter_no]['refcnt'][$row['dict_key']] = 0;
1812 }
1813 }
1814 $result->closeCursor();
1815 unset ($result);
1816 // Find the list of all assigned values of dictionary-addressed attributes, each with
1817 // chapter/word keyed reference counters. Use the structure to adjust reference counters
1818 // of the returned disctionary words.
1819 $query2 = "select a.attr_id, am.chapter_no, uint_value, count(object_id) as refcnt " .
1820 "from Attribute as a inner join AttributeMap as am on a.attr_id = am.attr_id " .
1821 "inner join AttributeValue as av on a.attr_id = av.attr_id " .
1822 "inner join Dictionary as d on am.chapter_no = d.chapter_no and av.uint_value = d.dict_key " .
1823 "where attr_type = 'dict' group by a.attr_id, am.chapter_no, uint_value " .
1824 "order by a.attr_id, am.chapter_no, uint_value";
1825 $result = useSelectBlade ($query2, __FUNCTION__);
1826 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1827 $dict[$row['chapter_no']]['refcnt'][$row['uint_value']] = $row['refcnt'];
1828 $result->closeCursor();
1829 return $dict;
1830 }
1831
1832 function getDictStats ()
1833 {
1834 $stock_chapters = array (1, 2, 3, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23);
1835 $query =
1836 "select Chapter.chapter_no, chapter_name, count(dict_key) as wc from " .
1837 "Chapter natural left join Dictionary group by Chapter.chapter_no";
1838 $result = useSelectBlade ($query, __FUNCTION__);
1839 $tc = $tw = $uc = $uw = 0;
1840 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1841 {
1842 $tc++;
1843 $tw += $row['wc'];;
1844 if (in_array ($row['chapter_no'], $stock_chapters))
1845 continue;
1846 $uc++;
1847 $uw += $row['wc'];;
1848 }
1849 $result->closeCursor();
1850 unset ($result);
1851 $query = "select count(attr_id) as attrc from RackObject as ro left join " .
1852 "AttributeValue as av on ro.id = av.object_id group by ro.id";
1853 $result = useSelectBlade ($query, __FUNCTION__);
1854 $to = $ta = $so = 0;
1855 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1856 {
1857 $to++;
1858 if ($row['attrc'] != 0)
1859 {
1860 $so++;
1861 $ta += $row['attrc'];
1862 }
1863 }
1864 $result->closeCursor();
1865 $ret = array();
1866 $ret['Total chapters in dictionary'] = $tc;
1867 $ret['Total words in dictionary'] = $tw;
1868 $ret['User chapters'] = $uc;
1869 $ret['Words in user chapters'] = $uw;
1870 $ret['Total objects'] = $to;
1871 $ret['Objects with stickers'] = $so;
1872 $ret['Total stickers attached'] = $ta;
1873 return $ret;
1874 }
1875
1876 function getIPv4Stats()
1877 {
1878 $ret = array();
1879 $subject = array();
1880 $subject[] = array ('q' => 'select count(id) from IPRanges', 'txt' => 'Networks');
1881 $subject[] = array ('q' => 'select count(ip) from IPAddress', 'txt' => 'Addresses commented/reserved');
1882 $subject[] = array ('q' => 'select count(ip) from IPBonds', 'txt' => 'Addresses allocated');
1883 $subject[] = array ('q' => 'select count(*) from PortForwarding', 'txt' => 'NAT rules');
1884 $subject[] = array ('q' => 'select count(id) from IPVirtualService', 'txt' => 'Virtual services');
1885 $subject[] = array ('q' => 'select count(id) from IPRSPool', 'txt' => 'Real server pools');
1886 $subject[] = array ('q' => 'select count(id) from IPRealServer', 'txt' => 'Real servers');
1887 $subject[] = array ('q' => 'select count(distinct object_id) from IPLoadBalancer', 'txt' => 'Load balancers');
1888
1889 foreach ($subject as $item)
1890 {
1891 $result = useSelectBlade ($item['q'], __FUNCTION__);
1892 $row = $result->fetch (PDO::FETCH_NUM);
1893 $ret[$item['txt']] = $row[0];
1894 $result->closeCursor();
1895 unset ($result);
1896 }
1897 return $ret;
1898 }
1899
1900 function getRackspaceStats()
1901 {
1902 $ret = array();
1903 $subject = array();
1904 $subject[] = array ('q' => 'select count(*) from Dictionary where chapter_no = 3', 'txt' => 'Rack rows');
1905 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
1906 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
1907 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
1908
1909 foreach ($subject as $item)
1910 {
1911 $result = useSelectBlade ($item['q'], __FUNCTION__);
1912 $row = $result->fetch (PDO::FETCH_NUM);
1913 $ret[$item['txt']] = empty ($row[0]) ? 0 : $row[0];
1914 $result->closeCursor();
1915 unset ($result);
1916 }
1917 return $ret;
1918 }
1919
1920 function getTagStats ()
1921 {
1922 $ret = array();
1923 $query = "select tag, count(tag_id) as refcnt from " .
1924 "TagTree inner join TagStorage on TagTree.id = TagStorage.tag_id " .
1925 "group by tag_id order by refcnt desc";
1926 $result = useSelectBlade ($query, __FUNCTION__);
1927 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1928 $ret[$row['tag']] = $row['refcnt'];
1929 $result->closeCursor();
1930 return $ret;
1931 }
1932
1933 function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1934 {
1935 if ($chapter_no <= 0 or $dict_key <= 0 or empty ($dict_value))
1936 {
1937 showError ('Invalid args', __FUNCTION__);
1938 die;
1939 }
1940 global $dbxlink;
1941 $query =
1942 "update Dictionary set dict_value = '${dict_value}' where chapter_no=${chapter_no} " .
1943 "and dict_key=${dict_key} limit 1";
1944 $result = $dbxlink->query ($query);
1945 if ($result == NULL)
1946 {
1947 showError ('SQL query failed', __FUNCTION__);
1948 die;
1949 }
1950 return TRUE;
1951 }
1952
1953 function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1954 {
1955 if ($chapter_no <= 0 or empty ($dict_value))
1956 {
1957 showError ('Invalid args', __FUNCTION__);
1958 die;
1959 }
1960 return useInsertBlade
1961 (
1962 'Dictionary',
1963 array ('chapter_no' => $chapter_no, 'dict_value' => "'${dict_value}'")
1964 );
1965 }
1966
1967 function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1968 {
1969 if ($chapter_no <= 0 or $dict_key <= 0)
1970 {
1971 showError ('Invalid args', __FUNCTION__);
1972 die;
1973 }
1974 global $dbxlink;
1975 $query =
1976 "delete from Dictionary where chapter_no=${chapter_no} " .
1977 "and dict_key=${dict_key} limit 1";
1978 $result = $dbxlink->query ($query);
1979 if ($result == NULL)
1980 {
1981 showError ('SQL query failed', __FUNCTION__);
1982 die;
1983 }
1984 return TRUE;
1985 }
1986
1987 function commitAddChapter ($chapter_name = '')
1988 {
1989 if (empty ($chapter_name))
1990 {
1991 showError ('Invalid args', __FUNCTION__);
1992 die;
1993 }
1994 return useInsertBlade
1995 (
1996 'Chapter',
1997 array ('chapter_name' => "'${chapter_name}'")
1998 );
1999 }
2000
2001 function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
2002 {
2003 if ($chapter_no <= 0 or empty ($chapter_name))
2004 {
2005 showError ('Invalid args', __FUNCTION__);
2006 die;
2007 }
2008 global $dbxlink;
2009 $query =
2010 "update Chapter set chapter_name = '${chapter_name}' where chapter_no = ${chapter_no} " .
2011 "and sticky = 'no' limit 1";
2012 $result = $dbxlink->query ($query);
2013 if ($result == NULL)
2014 {
2015 showError ('SQL query failed', __FUNCTION__);
2016 die;
2017 }
2018 return TRUE;
2019 }
2020
2021 function commitDeleteChapter ($chapter_no = 0)
2022 {
2023 if ($chapter_no <= 0)
2024 {
2025 showError ('Invalid args', __FUNCTION__);
2026 die;
2027 }
2028 global $dbxlink;
2029 $query =
2030 "delete from Chapter where chapter_no = ${chapter_no} and sticky = 'no' limit 1";
2031 $result = $dbxlink->query ($query);
2032 if ($result == NULL)
2033 {
2034 showError ('SQL query failed', __FUNCTION__);
2035 die;
2036 }
2037 return TRUE;
2038 }
2039
2040 // This is a dictionary accessor. We perform link rendering, so the user sees
2041 // nice <select> drop-downs.
2042 function readChapter ($chapter_name = '')
2043 {
2044 if (empty ($chapter_name))
2045 {
2046 showError ('invalid argument', __FUNCTION__);
2047 return NULL;
2048 }
2049 $query =
2050 "select dict_key, dict_value from Dictionary natural join Chapter " .
2051 "where chapter_name = '${chapter_name}'";
2052 $result = useSelectBlade ($query, __FUNCTION__);
2053 $chapter = array();
2054 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2055 $chapter[$row['dict_key']] = parseWikiLink ($row['dict_value'], 'o');
2056 $result->closeCursor();
2057 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
2058 asort ($chapter);
2059 return $chapter;
2060 }
2061
2062 function getAttrMap ()
2063 {
2064 $query =
2065 "select a.attr_id, a.attr_type, a.attr_name, am.objtype_id, " .
2066 "d.dict_value as objtype_name, am.chapter_no, c2.chapter_name from " .
2067 "Attribute as a natural left join AttributeMap as am " .
2068 "left join Dictionary as d on am.objtype_id = d.dict_key " .
2069 "left join Chapter as c1 on d.chapter_no = c1.chapter_no " .
2070 "left join Chapter as c2 on am.chapter_no = c2.chapter_no " .
2071 "where c1.chapter_name = 'RackObjectType' or c1.chapter_name is null " .
2072 "order by attr_name";
2073 $result = useSelectBlade ($query, __FUNCTION__);
2074 $ret = array();
2075 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2076 {
2077 $attr_id = $row['attr_id'];
2078 if (!isset ($ret[$attr_id]))
2079 {
2080 $ret[$attr_id]['id'] = $attr_id;
2081 $ret[$attr_id]['type'] = $row['attr_type'];
2082 $ret[$attr_id]['name'] = $row['attr_name'];
2083 $ret[$attr_id]['application'] = array();
2084 }
2085 if ($row['objtype_id'] == '')
2086 continue;
2087 $application['objtype_id'] = $row['objtype_id'];
2088 $application['objtype_name'] = $row['objtype_name'];
2089 if ($row['attr_type'] == 'dict')
2090 {
2091 $application['chapter_no'] = $row['chapter_no'];
2092 $application['chapter_name'] = $row['chapter_name'];
2093 }
2094 $ret[$attr_id]['application'][] = $application;
2095 }
2096 $result->closeCursor();
2097 return $ret;
2098 }
2099
2100 function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
2101 {
2102 if ($attr_id <= 0 or empty ($attr_name))
2103 {
2104 showError ('Invalid args', __FUNCTION__);
2105 die;
2106 }
2107 global $dbxlink;
2108 $query =
2109 "update Attribute set attr_name = '${attr_name}' " .
2110 "where attr_id = ${attr_id} limit 1";
2111 $result = $dbxlink->query ($query);
2112 if ($result == NULL)
2113 {
2114 showError ("SQL query '${query}' failed", __FUNCTION__);
2115 die;
2116 }
2117 return TRUE;
2118 }
2119
2120 function commitAddAttribute ($attr_name = '', $attr_type = '')
2121 {
2122 if (empty ($attr_name))
2123 {
2124 showError ('Invalid args', __FUNCTION__);
2125 die;
2126 }
2127 switch ($attr_type)
2128 {
2129 case 'uint':
2130 case 'float':
2131 case 'string':
2132 case 'dict':
2133 break;
2134 default:
2135 showError ('Invalid args', __FUNCTION__);
2136 die;
2137 }
2138 return useInsertBlade
2139 (
2140 'Attribute',
2141 array ('attr_name' => "'${attr_name}'", 'attr_type' => "'${attr_type}'")
2142 );
2143 }
2144
2145 function commitDeleteAttribute ($attr_id = 0)
2146 {
2147 if ($attr_id <= 0)
2148 {
2149 showError ('Invalid args', __FUNCTION__);
2150 die;
2151 }
2152 return useDeleteBlade ('Attribute', 'attr_id', $attr_id, FALSE);
2153 }
2154
2155 // FIXME: don't store garbage in chapter_no for non-dictionary types.
2156 function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
2157 {
2158 if ($attr_id <= 0 or $objtype_id <= 0 or $chapter_no <= 0)
2159 {
2160 showError ('Invalid args', __FUNCTION__);
2161 die;
2162 }
2163 return useInsertBlade
2164 (
2165 'AttributeMap',
2166 array
2167 (
2168 'attr_id' => $attr_id,
2169 'objtype_id' => $objtype_id,
2170 'chapter_no' => $chapter_no
2171 )
2172 );
2173 }
2174
2175 function commitReduceAttrMap ($attr_id = 0, $objtype_id)
2176 {
2177 if ($attr_id <= 0 or $objtype_id <= 0)
2178 {
2179 showError ('Invalid args', __FUNCTION__);
2180 die;
2181 }
2182 global $dbxlink;
2183 $query =
2184 "delete from AttributeMap where attr_id=${attr_id} " .
2185 "and objtype_id=${objtype_id} limit 1";
2186 $result = $dbxlink->query ($query);
2187 if ($result == NULL)
2188 {
2189 showError ('SQL query failed', __FUNCTION__);
2190 die;
2191 }
2192 return TRUE;
2193 }
2194
2195 // This function returns all optional attributes for requested object
2196 // as an array of records. NULL is returned on error and empty array
2197 // is returned, if there are no attributes found.
2198 function getAttrValues ($object_id, $strip_optgroup = FALSE)
2199 {
2200 if ($object_id <= 0)
2201 {
2202 showError ('Invalid argument', __FUNCTION__);
2203 return NULL;
2204 }
2205 $ret = array();
2206 $query =
2207 "select A.attr_id, A.attr_name, A.attr_type, C.chapter_name, " .
2208 "AV.uint_value, AV.float_value, AV.string_value, D.dict_value from " .
2209 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
2210 "inner join Attribute as A using (attr_id) " .
2211 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
2212 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_no = D.chapter_no " .
2213 "left join Chapter as C on AM.chapter_no = C.chapter_no " .
2214 "where RO.id = ${object_id} order by A.attr_type, A.attr_name";
2215 $result = useSelectBlade ($query, __FUNCTION__);
2216 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2217 {
2218 $record = array();
2219 $record['id'] = $row['attr_id'];
2220 $record['name'] = $row['attr_name'];
2221 $record['type'] = $row['attr_type'];
2222 switch ($row['attr_type'])
2223 {
2224 case 'uint':
2225 case 'float':
2226 case 'string':
2227 $record['value'] = $row[$row['attr_type'] . '_value'];
2228 $record['a_value'] = parseWikiLink ($record['value'], 'a');
2229 break;
2230 case 'dict':
2231 $record['value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'o', $strip_optgroup);
2232 $record['a_value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'a', $strip_optgroup);
2233 $record['chapter_name'] = $row['chapter_name'];
2234 $record['key'] = $row['uint_value'];
2235 break;
2236 default:
2237 $record['value'] = NULL;
2238 break;
2239 }
2240 $ret[$row['attr_id']] = $record;
2241 }
2242 $result->closeCursor();
2243 return $ret;
2244 }
2245
2246 function commitResetAttrValue ($object_id = 0, $attr_id = 0)
2247 {
2248 if ($object_id <= 0 or $attr_id <= 0)
2249 {
2250 showError ('Invalid arguments', __FUNCTION__);
2251 die;
2252 }
2253 global $dbxlink;
2254 $query = "delete from AttributeValue where object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2255 $result = $dbxlink->query ($query);
2256 if ($result == NULL)
2257 {
2258 showError ('SQL query failed', __FUNCTION__);
2259 die;
2260 }
2261 return TRUE;
2262 }
2263
2264 // FIXME: don't share common code with use commitResetAttrValue()
2265 function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
2266 {
2267 if ($object_id <= 0 or $attr_id <= 0)
2268 {
2269 showError ('Invalid arguments', __FUNCTION__);
2270 die;
2271 }
2272 if (empty ($value))
2273 return commitResetAttrValue ($object_id, $attr_id);
2274 global $dbxlink;
2275 $query1 = "select attr_type from Attribute where attr_id = ${attr_id}";
2276 $result = $dbxlink->query ($query1);
2277 if ($result == NULL)
2278 {
2279 showError ('SQL query #1 failed', __FUNCTION__);
2280 die;
2281 }
2282 $row = $result->fetch (PDO::FETCH_NUM);
2283 if ($row == NULL)
2284 {
2285 showError ('SQL query #1 returned no results', __FUNCTION__);
2286 die;
2287 }
2288 $attr_type = $row[0];
2289 $result->closeCursor();
2290 switch ($attr_type)
2291 {
2292 case 'uint':
2293 case 'float':
2294 case 'string':
2295 $column = $attr_type . '_value';
2296 break;
2297 case 'dict':
2298 $column = 'uint_value';
2299 break;
2300 default:
2301 showError ("Unknown attribute type '${attr_type}' met", __FUNCTION__);
2302 die;
2303 }
2304 $query2 =
2305 "delete from AttributeValue where " .
2306 "object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2307 $result = $dbxlink->query ($query2);
2308 if ($result == NULL)
2309 {
2310 showError ('SQL query #2 failed', __FUNCTION__);
2311 die;
2312 }
2313 // We know $value isn't empty here.
2314 $query3 =
2315 "insert into AttributeValue set ${column} = '${value}', " .
2316 "object_id = ${object_id}, attr_id = ${attr_id} ";
2317 $result = $dbxlink->query ($query3);
2318 if ($result == NULL)
2319 {
2320 showError ('SQL query #3 failed', __FUNCTION__);
2321 die;
2322 }
2323 return TRUE;
2324 }
2325
2326 function commitUseupPort ($port_id = 0)
2327 {
2328 if ($port_id <= 0)
2329 {
2330 showError ("Invalid argument", __FUNCTION__);
2331 die;
2332 }
2333 global $dbxlink;
2334 $query = "update Port set reservation_comment = NULL where id = ${port_id} limit 1";
2335 $result = $dbxlink->exec ($query);
2336 if ($result == NULL)
2337 {
2338 showError ("SQL query failed", __FUNCTION__);
2339 die;
2340 }
2341 return TRUE;
2342
2343 }
2344
2345 // This is a swiss-knife blade to insert a record into a table.
2346 // The first argument is table name.
2347 // The second argument is an array of "name" => "value" pairs.
2348 // The function returns either TRUE or FALSE (we expect one row
2349 // to be inserted).
2350 function useInsertBlade ($tablename, $values)
2351 {
2352 global $dbxlink;
2353 $namelist = $valuelist = '';
2354 foreach ($values as $name => $value)
2355 {
2356 $namelist = $namelist . ($namelist == '' ? "(${name}" : ", ${name}");
2357 $valuelist = $valuelist . ($valuelist == '' ? "(${value}" : ", ${value}");
2358 }
2359 $query = "insert into ${tablename} ${namelist}) values ${valuelist})";
2360 $result = $dbxlink->exec ($query);
2361 if ($result != 1)
2362 return FALSE;
2363 return TRUE;
2364 }
2365
2366 // This swiss-knife blade deletes one record from the specified table
2367 // using the specified key name and value.
2368 function useDeleteBlade ($tablename, $keyname, $keyvalue, $quotekey = TRUE, $deleteall = FALSE)
2369 {
2370 global $dbxlink;
2371 if ($quotekey == TRUE)
2372 $keyvalue = "'${keyvalue}'";
2373 $query = "delete from ${tablename} where ${keyname}=$keyvalue";
2374 if (!$deleteall)
2375 $query .= ' limit 1';
2376 $result = $dbxlink->exec ($query);
2377 if ($result === NULL)
2378 return FALSE;
2379 elseif (!$deleteall && $result != 1)
2380 return FALSE;
2381 else
2382 return TRUE;
2383 }
2384
2385 function useSelectBlade ($query, $caller = 'N/A')
2386 {
2387 global $dbxlink;
2388 $result = $dbxlink->query ($query);
2389 if ($result == NULL)
2390 {
2391 $ei = $dbxlink->errorInfo();
2392 showError ("SQL query '${query}'\n failed in useSelectBlade with error ${ei[1]} (${ei[2]})", $caller);
2393 return NULL;
2394 }
2395 return $result;
2396 }
2397
2398 function loadConfigCache ()
2399 {
2400 $query = 'SELECT varname, varvalue, vartype, is_hidden, emptyok, description FROM Config ORDER BY varname';
2401 $result = useSelectBlade ($query, __FUNCTION__);
2402 $cache = array();
2403 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2404 $cache[$row['varname']] = $row;
2405 $result->closeCursor();
2406 return $cache;
2407 }
2408
2409 // setConfigVar() is expected to perform all necessary filtering
2410 function storeConfigVar ($varname = NULL, $varvalue = NULL)
2411 {
2412 global $dbxlink;
2413 if (empty ($varname) || $varvalue === NULL)
2414 {
2415 showError ('Invalid arguments', __FUNCTION__);
2416 return FALSE;
2417 }
2418 $query = "update Config set varvalue='${varvalue}' where varname='${varname}' limit 1";
2419 $result = $dbxlink->query ($query);
2420 if ($result == NULL)
2421 {
2422 showError ("SQL query '${query}' failed", __FUNCTION__);
2423 return FALSE;
2424 }
2425 $rc = $result->rowCount();
2426 $result->closeCursor();
2427 if ($rc == 0 or $rc == 1)
2428 return TRUE;
2429 showError ("Something went wrong for args '${varname}', '${varvalue}'", __FUNCTION__);
2430 return FALSE;
2431 }
2432
2433 // Database version detector. Should behave corretly on any
2434 // working dataset a user might have.
2435 function getDatabaseVersion ()
2436 {
2437 global $dbxlink;
2438 $query = "select varvalue from Config where varname = 'DB_VERSION' and vartype = 'string'";
2439 $result = $dbxlink->query ($query);
2440 if ($result == NULL)
2441 {
2442 $errorInfo = $dbxlink->errorInfo();
2443 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
2444 return '0.14.4';
2445 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
2446 }
2447 $rows = $result->fetchAll (PDO::FETCH_NUM);
2448 if (count ($rows) != 1 || empty ($rows[0][0]))
2449 {
2450 $result->closeCursor();
2451 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
2452 }
2453 $ret = $rows[0][0];
2454 $result->closeCursor();
2455 return $ret;
2456 }
2457
2458 // Return an array of virtual services. For each of them list real server pools
2459 // with their load balancers and other stats.
2460 function getSLBSummary ()
2461 {
2462 $query = 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
2463 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
2464 'from IPVirtualService as vs inner join IPLoadBalancer as lb on vs.id = lb.vs_id ' .
2465 'inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2466 'left join IPRealServer as rs on rs.rspool_id = lb.rspool_id ' .
2467 'group by vs.id, object_id order by vs.vip, object_id';
2468 $result = useSelectBlade ($query, __FUNCTION__);
2469 $ret = array();
2470 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2471 {
2472 $vsid = $row['vsid'];
2473 $object_id = $row['object_id'];
2474 if (!isset ($ret[$vsid]))
2475 {
2476 $ret[$vsid] = array();
2477 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
2478 $ret[$vsid][$cname] = $row[$cname];
2479 $ret[$vsid]['lblist'] = array();
2480 }
2481 // There's only one assigned RS pool possible for each LB-VS combination.
2482 $ret[$vsid]['lblist'][$row['object_id']] = array
2483 (
2484 'id' => $row['rspool_id'],
2485 'size' => $row['rscount'],
2486 'name' => $row['pool_name']
2487 );
2488 }
2489 $result->closeCursor();
2490 return $ret;
2491 }
2492
2493 // Get the detailed composition of a particular virtual service, namely the list
2494 // of all pools, each shown with the list of objects servicing it. VS/RS configs
2495 // will be returned as well.
2496 function getVServiceInfo ($vsid = 0)
2497 {
2498 $query1 = "select inet_ntoa(vip) as vip, vport, proto, name, vsconfig, rsconfig " .
2499 "from IPVirtualService where id = ${vsid}";
2500 $result = useSelectBlade ($query1, __FUNCTION__);
2501 $vsinfo = array ();
2502 $row = $result->fetch (PDO::FETCH_ASSOC);
2503 if (!$row)
2504 return NULL;
2505 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig') as $cname)
2506 $vsinfo[$cname] = $row[$cname];
2507 $vsinfo['rspool'] = array();
2508 $result->closeCursor();
2509 unset ($result);
2510 $query2 = "select pool.id, name, pool.vsconfig, pool.rsconfig, object_id, " .
2511 "lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig from " .
2512 "IPRSPool as pool left join IPLoadBalancer as lb on pool.id = lb.rspool_id " .
2513 "where vs_id = ${vsid} order by pool.name, object_id";
2514 $result = useSelectBlade ($query2, __FUNCTION__);
2515 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2516 {
2517 if (!isset ($vsinfo['rspool'][$row['id']]))
2518 {
2519 $vsinfo['rspool'][$row['id']]['name'] = $row['name'];
2520 $vsinfo['rspool'][$row['id']]['vsconfig'] = $row['vsconfig'];
2521 $vsinfo['rspool'][$row['id']]['rsconfig'] = $row['rsconfig'];
2522 $vsinfo['rspool'][$row['id']]['lblist'] = array();
2523 }
2524 if ($row['object_id'] == NULL)
2525 continue;
2526 $vsinfo['rspool'][$row['id']]['lblist'][$row['object_id']] = array
2527 (
2528 'vsconfig' => $row['lb_vsconfig'],
2529 'rsconfig' => $row['lb_rsconfig']
2530 );
2531 }
2532 $result->closeCursor();
2533 return $vsinfo;
2534 }
2535
2536 // Collect and return the following info about the given real server pool:
2537 // basic information
2538 // parent virtual service information
2539 // load balancers list (each with a list of VSes)
2540 // real servers list
2541
2542 function getRSPoolInfo ($id = 0)
2543 {
2544 $query1 = "select id, name, vsconfig, rsconfig from " .
2545 "IPRSPool where id = ${id}";
2546 $result = useSelectBlade ($query1, __FUNCTION__);
2547 $ret = array();
2548 $row = $result->fetch (PDO::FETCH_ASSOC);
2549 if (!$row)
2550 return NULL;
2551 foreach (array ('id', 'name', 'vsconfig', 'rsconfig') as $c)
2552 $ret[$c] = $row[$c];
2553 $result->closeCursor();
2554 unset ($result);
2555 $ret['lblist'] = array();
2556 $ret['rslist'] = array();
2557 $query2 = "select object_id, vs_id, vsconfig, rsconfig from IPLoadBalancer " .
2558 "where rspool_id = ${id} order by object_id, vs_id";
2559 $result = useSelectBlade ($query2, __FUNCTION__);
2560 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2561 foreach (array ('vsconfig', 'rsconfig') as $c)
2562 $ret['lblist'][$row['object_id']][$row['vs_id']][$c] = $row[$c];
2563 $result->closeCursor();
2564 unset ($result);
2565 $query3 = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rsconfig from " .
2566 "IPRealServer where rspool_id = ${id} order by IPRealServer.rsip, rsport";
2567 $result = useSelectBlade ($query3, __FUNCTION__);
2568 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2569 foreach (array ('inservice', 'rsip', 'rsport', 'rsconfig') as $c)
2570 $ret['rslist'][$row['id']][$c] = $row[$c];
2571 $result->closeCursor();
2572 return $ret;
2573 }
2574
2575 function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
2576 {
2577 if ($pool_id <= 0 or $rsport <= 0)
2578 {
2579 showError ('Invalid arguments', __FUNCTION__);
2580 die;
2581 }
2582 return useInsertBlade
2583 (
2584 'IPRealServer',
2585 array
2586 (
2587 'rsip' => "inet_aton('${rsip}')",
2588 'rsport' => $rsport,
2589 'rspool_id' => $pool_id,
2590 'inservice' => ($inservice == 'yes' ? "'yes'" : "'no'"),
2591 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2592 )
2593 );
2594 }
2595
2596 function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig, $taglist = array())
2597 {
2598 if (empty ($vip) or $vport <= 0 or empty ($proto))
2599 return __FUNCTION__ . ': invalid arguments';
2600 if (!useInsertBlade
2601 (
2602 'IPVirtualService',
2603 array
2604 (
2605 'vip' => "inet_aton('${vip}')",
2606 'vport' => $vport,
2607 'proto' => "'${proto}'",
2608 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2609 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2610 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2611 )
2612 ))
2613 return __FUNCTION__ . ': SQL insertion failed';
2614 return addTagsForLastRecord ('ipv4vs', $taglist);
2615 }
2616
2617 function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
2618 {
2619 if ($pool_id <= 0 or $object_id <= 0 or $vs_id <= 0)
2620 {
2621 showError ('Invalid arguments', __FUNCTION__);
2622 die;
2623 }
2624 return useInsertBlade
2625 (
2626 'IPLoadBalancer',
2627 array
2628 (
2629 'object_id' => $object_id,
2630 'rspool_id' => $pool_id,
2631 'vs_id' => $vs_id,
2632 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2633 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2634 )
2635 );
2636 }
2637
2638 function commitDeleteRS ($id = 0)
2639 {
2640 if ($id <= 0)
2641 return FALSE;
2642 return useDeleteBlade ('IPRealServer', 'id', $id, FALSE);
2643 }
2644
2645 function commitDeleteVS ($id = 0)
2646 {
2647 if ($id <= 0)
2648 return FALSE;
2649 return useDeleteBlade ('IPVirtualService', 'id', $id, FALSE) && deleteTagsForEntity ('ipv4vs', $id);
2650 }
2651
2652 function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
2653 {
2654 global $dbxlink;
2655 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
2656 return FALSE;
2657 $query = "delete from IPLoadBalancer where object_id = ${object_id} and " .
2658 "rspool_id = ${pool_id} and vs_id = ${vs_id} limit 1";
2659 $result = $dbxlink->exec ($query);
2660 if ($result === NULL)
2661 return FALSE;
2662 elseif ($result != 1)
2663 return FALSE;
2664 else
2665 return TRUE;
2666 }
2667
2668 function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2669 {
2670 if ($rsid <= 0 or $rsport <= 0)
2671 {
2672 showError ('Invalid args', __FUNCTION__);
2673 die;
2674 }
2675 if (long2ip (ip2long ($rsip)) !== $rsip)
2676 {
2677 showError ("Invalid IP address '${rsip}'", __FUNCTION__);
2678 die;
2679 }
2680 global $dbxlink;
2681 $query =
2682 "update IPRealServer set rsip = inet_aton('${rsip}'), rsport = ${rsport}, rsconfig = " .
2683 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2684 " where id = ${rsid} limit 1";
2685 $result = $dbxlink->query ($query);
2686 if ($result == NULL)
2687 {
2688 showError ("SQL query '${query}' failed", __FUNCTION__);
2689 die;
2690 }
2691 return TRUE;
2692 }
2693
2694 function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
2695 {
2696 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
2697 {
2698 showError ('Invalid args', __FUNCTION__);
2699 die;
2700 }
2701 global $dbxlink;
2702 $query =
2703 "update IPLoadBalancer set vsconfig = " .
2704 (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'") .
2705 ', rsconfig = ' .
2706 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2707 " where object_id = ${object_id} and rspool_id = ${pool_id} " .
2708 "and vs_id = ${vs_id} limit 1";
2709 $result = $dbxlink->exec ($query);
2710 if ($result === NULL)
2711 return FALSE;
2712 else
2713 return TRUE;
2714 }
2715
2716 function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2717 {
2718 if ($vsid <= 0 or empty ($vip) or $vport <= 0 or empty ($proto))
2719 {
2720 showError ('Invalid args', __FUNCTION__);
2721 die;
2722 }
2723 global $dbxlink;
2724 $query = "update IPVirtualService set " .
2725 "vip = inet_aton('${vip}'), " .
2726 "vport = ${vport}, " .
2727 "proto = '${proto}', " .
2728 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2729 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2730 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2731 " where id = ${vsid} limit 1";
2732 $result = $dbxlink->exec ($query);
2733 if ($result === NULL)
2734 return FALSE;
2735 else
2736 return TRUE;
2737 }
2738
2739 // Return the list of virtual services, indexed by vs_id.
2740 // Each record will be shown with its basic info plus RS pools counter.
2741 function getVSList ($tagfilter = array(), $tfmode = 'any')
2742 {
2743 $whereclause = getWhereClause ($tagfilter);
2744 $query = "select vs.id, inet_ntoa(vip) as vip, vport, proto, vs.name, vs.vsconfig, vs.rsconfig, count(rspool_id) as poolcount " .
2745 "from IPVirtualService as vs left join IPLoadBalancer as lb on vs.id = lb.vs_id " .
2746 "left join TagStorage on vs.id = TagStorage.target_id and target_realm = 'ipv4vs' " .
2747 "where true ${whereclause} group by vs.id order by vs.vip, proto, vport";
2748 $result = useSelectBlade ($query, __FUNCTION__);
2749 $ret = array ();
2750 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2751 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig', 'poolcount') as $cname)
2752 $ret[$row['id']][$cname] = $row[$cname];
2753 $result->closeCursor();
2754 return $ret;
2755 }
2756
2757 // Return the list of RS pool, indexed by pool id.
2758 function getRSPoolList ($tagfilter = array(), $tfmode = 'any')
2759 {
2760 $whereclause = getWhereClause ($tagfilter);
2761 $query = "select pool.id, pool.name, count(rspool_id) as refcnt, pool.vsconfig, pool.rsconfig " .
2762 "from IPRSPool as pool left join IPLoadBalancer as lb on pool.id = lb.rspool_id " .
2763 "left join TagStorage on pool.id = TagStorage.target_id and target_realm = 'ipv4rspool' " .
2764 "where true ${whereclause} group by pool.id order by pool.name, pool.id";
2765 $result = useSelectBlade ($query, __FUNCTION__);
2766 $ret = array ();
2767 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2768 foreach (array ('name', 'refcnt', 'vsconfig', 'rsconfig') as $cname)
2769 $ret[$row['id']][$cname] = $row[$cname];
2770 $result->closeCursor();
2771 return $ret;
2772 }
2773
2774 function loadThumbCache ($rack_id = 0)
2775 {
2776 $ret = NULL;
2777 $query = "select thumb_data from Rack where id = ${rack_id} and thumb_data is not null limit 1";
2778 $result = useSelectBlade ($query, __FUNCTION__);
2779 $row = $result->fetch (PDO::FETCH_ASSOC);
2780 if ($row)
2781 $ret = base64_decode ($row['thumb_data']);
2782 $result->closeCursor();
2783 return $ret;
2784 }
2785
2786 function saveThumbCache ($rack_id = 0, $cache = NULL)
2787 {
2788 global $dbxlink;
2789 if ($rack_id == 0 or $cache == NULL)
2790 {
2791 showError ('Invalid arguments', __FUNCTION__);
2792 return;
2793 }
2794 $data = base64_encode ($cache);
2795 $query = "update Rack set thumb_data = '${data}' where id = ${rack_id} limit 1";
2796 $result = $dbxlink->exec ($query);
2797 }
2798
2799 function resetThumbCache ($rack_id = 0)
2800 {
2801 global $dbxlink;
2802 if ($rack_id == 0)
2803 {
2804 showError ('Invalid argument', __FUNCTION__);
2805 return;
2806 }
2807 $query = "update Rack set thumb_data = NULL where id = ${rack_id} limit 1";
2808 $result = $dbxlink->exec ($query);
2809 }
2810
2811 // Return the list of attached RS pools for the given object. As long as we have
2812 // the LB-VS UNIQUE in IPLoadBalancer table, it is Ok to key returned records
2813 // by vs_id, because there will be only one RS pool listed for each VS of the
2814 // current object.
2815 function getRSPoolsForObject ($object_id = 0)
2816 {
2817 if ($object_id <= 0)
2818 {
2819 showError ('Invalid object_id', __FUNCTION__);
2820 return NULL;
2821 }
2822 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
2823 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
2824 'IPLoadBalancer as lb inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2825 'inner join IPVirtualService as vs on lb.vs_id = vs.id ' .
2826 'left join IPRealServer as rs on lb.rspool_id = rs.rspool_id ' .
2827 "where lb.object_id = ${object_id} " .
2828 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name';
2829 $result = useSelectBlade ($query, __FUNCTION__);
2830 $ret = array ();
2831 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2832 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
2833 $ret[$row['vs_id']][$cname] = $row[$cname];
2834 $result->closeCursor();
2835 return $ret;
2836 }
2837
2838 function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
2839 {
2840 if (empty ($name))
2841 return __FUNCTION__ . ': invalid arguments';
2842 if (!useInsertBlade
2843 (
2844 'IPRSPool',
2845 array
2846 (
2847 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2848 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2849 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2850 )
2851 ))
2852 return __FUNCTION__ . ': SQL insertion failed';
2853 return addTagsForLastRecord ('ipv4rspool', $taglist);
2854 }
2855
2856 function commitDeleteRSPool ($pool_id = 0)
2857 {
2858 global $dbxlink;
2859 if ($pool_id <= 0)
2860 return FALSE;
2861 return useDeleteBlade ('IPRSPool', 'id', $pool_id, FALSE) && deleteTagsForEntity ('ipv4rspool', $pool_id);
2862 }
2863
2864 function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2865 {
2866 if ($pool_id <= 0)
2867 {
2868 showError ('Invalid arg', __FUNCTION__);
2869 die;
2870 }
2871 global $dbxlink;
2872 $query = "update IPRSPool set " .
2873 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2874 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2875 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2876 " where id = ${pool_id} limit 1";
2877 $result = $dbxlink->exec ($query);
2878 if ($result === NULL)
2879 return FALSE;
2880 elseif ($result != 1)
2881 return FALSE;
2882 else
2883 return TRUE;
2884 }
2885
2886 function getRSList ()
2887 {
2888 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
2889 "from IPRealServer order by rspool_id, IPRealServer.rsip, rsport";
2890 $result = useSelectBlade ($query, __FUNCTION__);
2891 $ret = array ();
2892 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2893 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
2894 $ret[$row['id']][$cname] = $row[$cname];
2895 $result->closeCursor();
2896 return $ret;
2897 }
2898
2899 // Return the list of all currently configured load balancers with their pool count.
2900 function getLBList ()
2901 {
2902 $query = "select object_id, count(rspool_id) as poolcount " .
2903 "from IPLoadBalancer group by object_id order by object_id";
2904 $result = useSelectBlade ($query, __FUNCTION__);
2905 $ret = array ();
2906 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2907 $ret[$row['object_id']] = $row['poolcount'];
2908 $result->closeCursor();
2909 return $ret;
2910 }
2911
2912 // For the given object return: it vsconfig/rsconfig; the list of RS pools
2913 // attached (each with vsconfig/rsconfig in turn), each with the list of
2914 // virtual services terminating the pool. Each pool also lists all real
2915 // servers with rsconfig.
2916 function getSLBConfig ($object_id)
2917 {
2918 if ($object_id <= 0)
2919 {
2920 showError ('Invalid arg', __FUNCTION__);
2921 return NULL;
2922 }
2923 $ret = array();
2924 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2925 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2926 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
2927 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
2928 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
2929 'IPLoadBalancer as lb inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2930 'inner join IPVirtualService as vs on lb.vs_id = vs.id ' .
2931 'inner join IPRealServer as rs on lb.rspool_id = rs.rspool_id ' .
2932 "where lb.object_id = ${object_id} and rs.inservice = 'yes' " .
2933 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport";
2934 $result = useSelectBlade ($query, __FUNCTION__);
2935 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2936 {
2937 $vs_id = $row['vs_id'];
2938 if (!isset ($ret[$vs_id]))
2939 {
2940 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)
2941 $ret[$vs_id][$c] = $row[$c];
2942 $ret[$vs_id]['rslist'] = array();
2943 }
2944 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2945 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
2946 }
2947 $result->closeCursor();
2948 return $ret;
2949 }
2950
2951 function commitSetInService ($rs_id = 0, $inservice = '')
2952 {
2953 if ($rs_id <= 0 or empty ($inservice))
2954 {
2955 showError ('Invalid args', __FUNCTION__);
2956 return NULL;
2957 }
2958 global $dbxlink;
2959 $query = "update IPRealServer set inservice = '${inservice}' where id = ${rs_id} limit 1";
2960 $result = $dbxlink->exec ($query);
2961 if ($result === NULL)
2962 return FALSE;
2963 elseif ($result != 1)
2964 return FALSE;
2965 else
2966 return TRUE;
2967 }
2968
2969 function executeAutoPorts ($object_id = 0, $type_id = 0)
2970 {
2971 if ($object_id == 0 or $type_id == 0)
2972 {
2973 showError ('Invalid arguments', __FUNCTION__);
2974 die;
2975 }
2976 $ret = TRUE;
2977 foreach (getAutoPorts ($type_id) as $autoport)
2978 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2979 return $ret;
2980 }
2981
2982 // Return only implicitly listed tags, the rest of the chain will be
2983 // generated/deducted later at higher levels.
2984 function loadEntityTags ($entity_realm = '', $entity_id = 0)
2985 {
2986 if ($entity_realm == '' or $entity_id <= 0)
2987 {
2988 showError ('Invalid or missing arguments', __FUNCTION__);
2989 return NULL;
2990 }
2991 $ret = array();
2992 $query = "select tt.id, tag from " .
2993 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
2994 "where target_realm = '${entity_realm}' and target_id = ${entity_id} " .
2995 "order by tt.tag";
2996 $result = useSelectBlade ($query, __FUNCTION__);
2997 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2998 $ret[$row['id']] = $row;
2999 $result->closeCursor();
3000 return $ret;
3001 }
3002
3003 function loadRackObjectTags ($id)
3004 {
3005 return loadEntityTags ('object', $id);
3006 }
3007
3008 function loadIPv4PrefixTags ($id)
3009 {
3010 return loadEntityTags ('ipv4net', $id);
3011 }
3012
3013 function loadRackTags ($id)
3014 {
3015 return loadEntityTags ('rack', $id);
3016 }
3017
3018 function loadIPv4VSTags ($id)
3019 {
3020 return loadEntityTags ('ipv4vs', $id);
3021 }
3022
3023 function loadIPv4RSPoolTags ($id)
3024 {
3025 return loadEntityTags ('ipv4rspool', $id);
3026 }
3027
3028 function loadUserTags ($user_id)
3029 {
3030 return loadEntityTags ('user', $user_id);
3031 }
3032
3033 function getTagList ()
3034 {
3035 $ret = array();
3036 $query = "select id, parent_id, tag, target_realm as realm, count(target_id) as refcnt " .
3037 "from TagTree left join TagStorage on id = tag_id " .
3038 "group by id, target_realm order by tag";
3039 $result = useSelectBlade ($query, __FUNCTION__);
3040 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3041 {
3042 if (!isset ($ret[$row['id']]))
3043 $ret[$row['id']] = array
3044 (
3045 'id' => $row['id'],
3046 'tag' => $row['tag'],
3047 'parent_id' => $row['parent_id'],
3048 'refcnt' => array()
3049 );
3050 if ($row['realm'])
3051 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
3052 }
3053 $result->closeCursor();
3054 return $ret;
3055 }
3056
3057 function commitCreateTag ($tagname = '', $parent_id = 0)
3058 {
3059 if ($tagname == '' or $parent_id === 0)
3060 return "Invalid args to " . __FUNCTION__;
3061 $result = useInsertBlade
3062 (
3063 'TagTree',
3064 array
3065 (
3066 'tag' => "'${tagname}'",
3067 'parent_id' => $parent_id
3068 )
3069 );
3070 if ($result)
3071 return '';
3072 else
3073 return "SQL query failed in " . __FUNCTION__;
3074 }
3075
3076 function commitDestroyTag ($tagid = 0)
3077 {
3078 if ($tagid == 0)
3079 return 'Invalid arg to ' . __FUNCTION__;
3080 if (useDeleteBlade ('TagTree', 'id', $tagid, FALSE))
3081 return '';
3082 else
3083 return 'useDeleteBlade() failed in ' . __FUNCTION__;
3084 }
3085
3086 function commitUpdateTag ($tag_id, $tag_name, $parent_id)
3087 {
3088 if ($parent_id == 0)
3089 $parent_id = 'NULL';
3090 global $dbxlink;
3091 $query = "update TagTree set tag = '${tag_name}', parent_id = ${parent_id} " .
3092 "where id = ${tag_id} limit 1";
3093 $result = $dbxlink->exec ($query);
3094 if ($result === NULL)
3095 return 'SQL query failed in ' . __FUNCTION__;
3096 return '';
3097 }
3098
3099 function deleteTagsForEntity ($entity_realm, $entity_id)
3100 {
3101 global $dbxlink;
3102 $query = "delete from TagStorage where target_realm = '${entity_realm}' and target_id = ${entity_id}";
3103 $result = $dbxlink->exec ($query);
3104 if ($result === NULL)
3105 return FALSE;
3106 else
3107 return TRUE;
3108 }
3109
3110 function addTagForEntity ($realm, $entity_id, $tag_id)
3111 {
3112 return useInsertBlade
3113 (
3114 'TagStorage',
3115 array
3116 (
3117 'target_realm' => "'${realm}'",
3118 'target_id' => $entity_id,
3119 'tag_id' => $tag_id,
3120 )
3121 );
3122 }
3123
3124 function addTagsForLastRecord ($realm, $taglist, $last_insert_id = 0)
3125 {
3126 if (!count ($taglist))
3127 return '';
3128 if (!$last_insert_id)
3129 $last_insert_id = lastInsertID();
3130 $errcount = 0;
3131 foreach ($taglist as $tag_id)
3132 if (addTagForEntity ($realm, $last_insert_id, $tag_id) == FALSE)
3133 $errcount++;
3134 if (!$errcount)
3135 return '';
3136 else
3137 return "Experienced ${errcount} errors adding tags in realm '${realm}' for entity ID == ${last_insert_id}";
3138 }
3139
3140 function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
3141 {
3142 // $range is in x.x.x.x/x format, split into ip/mask vars
3143 $rangeArray = explode('/', $range);
3144 if (count ($rangeArray) != 2)
3145 return "Invalid IPv4 prefix '${range}'";
3146 $ip = $rangeArray[0];
3147 $mask = $rangeArray[1];
3148
3149 if (empty ($ip) or empty ($mask))
3150 return "Invalid IPv4 prefix '${range}'";
3151 $ipL = ip2long($ip);
3152 $maskL = ip2long($mask);
3153 if ($ipL == -1 || $ipL === FALSE)
3154 return 'Bad IPv4 address';
3155 if ($mask < 32 && $mask > 0)
3156 $maskL = $mask;
3157 else
3158 {
3159 $maskB = decbin($maskL);
3160 if (strlen($maskB)!=32)
3161 return 'Invalid netmask';
3162 $ones=0;
3163 $zeroes=FALSE;
3164 foreach( str_split ($maskB) as $digit)
3165 {
3166 if ($digit == '0')
3167 $zeroes = TRUE;
3168 if ($digit == '1')
3169 {
3170 $ones++;
3171 if ($zeroes == TRUE)
3172 return 'Invalid netmask';
3173 }
3174 }
3175 $maskL = $ones;
3176 }
3177 $binmask = binMaskFromDec($maskL);
3178 $ipL = $ipL & $binmask;
3179
3180 $query =
3181 "select ".
3182 "id, ip, mask, name ".
3183 "from IPRanges ";
3184
3185 $result = useSelectBlade ($query, __FUNCTION__);
3186
3187 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3188 {
3189 $otherip = $row['ip'];
3190 $othermask = binMaskFromDec($row['mask']);
3191 if (($otherip & $othermask) == ($ipL & $othermask))
3192 return "This subnet intersects with ".long2ip($row['ip'])."/${row['mask']}";
3193 if (($otherip & $binmask) == ($ipL & $binmask))
3194 return "This subnet intersects with ".long2ip($row['ip'])."/${row['mask']}";
3195 }
3196 $result->closeCursor();
3197 unset ($result);
3198 $result = useInsertBlade
3199 (
3200 'IPRanges',
3201 array
3202 (
3203 'ip' => sprintf ('%u', $ipL),
3204 'mask' => "'${maskL}'",
3205 'name' => "'${name}'"
3206 )
3207 );
3208
3209 if ($is_bcast and $maskL < 31)
3210 {
3211 $network_addr = long2ip ($ipL);
3212 $broadcast_addr = long2ip ($ipL | binInvMaskFromDec ($maskL));
3213 updateAddress ($network_addr, 'network', 'yes');
3214 updateAddress ($broadcast_addr, 'broadcast', 'yes');
3215 }
3216 return addTagsForLastRecord ('ipv4net', $taglist);
3217 }
3218
3219 // FIXME: This function doesn't wipe relevant records from IPAddress table.
3220 function destroyIPv4Prefix ($id = 0)
3221 {
3222 if ($id <= 0)
3223 return __FUNCTION__ . ': Invalid IPv4 prefix ID';
3224 if (!useDeleteBlade ('IPRanges', 'id', $id, FALSE))
3225 return __FUNCTION__ . ': SQL query #1 failed';
3226 if (!deleteTagsForEntity ('ipv4net', $id))
3227 return __FUNCTION__ . ': SQL query #2 failed';
3228 return '';
3229 }
3230
3231 function loadScript ($name)
3232 {
3233 $result = useSelectBlade ("select script_text from Script where script_name = '${name}'");
3234 $row = $result->fetch (PDO::FETCH_NUM);
3235 if ($row !== FALSE)
3236 return $row[0];
3237 else
3238 return NULL;
3239 }
3240
3241 function saveScript ($name, $text)
3242 {
3243 if (empty ($name))
3244 {
3245 showError ('Invalid argument');
3246 return FALSE;
3247 }
3248 // delete regardless of existence
3249 useDeleteBlade ('Script', 'script_name', $name, TRUE);
3250 return useInsertBlade
3251 (
3252 'Script',
3253 array
3254 (
3255 'script_name' => "'${name}'",
3256 'script_text' => "'${text}'"
3257 )
3258 );
3259 }
3260
3261 function saveUserPassword ($user_id, $newp)
3262 {
3263 $newhash = hash (PASSWORD_HASH, $newp);
3264 $query = "update UserAccount set user_password_hash = ${newhash} where user_id = ${user_id} limit 1";
3265 }
3266
3267 function objectIsPortless ($id = 0)
3268 {
3269 if ($id <= 0)
3270 {
3271 showError ('Invalid argument', __FUNCTION__);
3272 return;
3273 }
3274 if (($result = useSelectBlade ("select count(id) from Port where object_id = ${id}", __FUNCTION__)) == NULL)
3275 {
3276 showError ('SQL query failed', __FUNCTION__);
3277 return;
3278 }
3279 $row = $result->fetch (PDO::FETCH_NUM);
3280 $count = $row[0];
3281 $result->closeCursor();
3282 unset ($result);
3283 return $count === '0';
3284 }
3285
3286 function tagExistsInDatabase ($tname)
3287 {
3288 $result = useSelectBlade ("select count(*) from TagTree where lower(tag) = lower('${tname}')");
3289 $row = $result->fetch (PDO::FETCH_NUM);
3290 $count = $row[0];
3291 $result->closeCursor();
3292 unset ($result);
3293 return $count !== '0';
3294 }
3295
3296 ?>