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