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