r2278 fix typos
[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']));
d65353ad 1153 $ret['parent_id'] = getIPv4AddressNetworkId ($ret['ip'], $ret['mask']);
a910829d
DO
1154 return $ret;
1155}
1156
2d318652
DO
1157function getIPv4Address ($dottedquad = '')
1158{
1159 if ($dottedquad == '')
1160 {
1161 showError ('Invalid arg', __FUNCTION__);
1162 return NULL;
1163 }
1164 $i32 = ip2long ($dottedquad); // signed 32 bit
f7414fa5 1165 $scanres = scanIPv4Space (array (array ('i32_first' => $i32, 'i32_last' => $i32)));
2d318652 1166 if (!isset ($scanres[$i32]))
8b980e24 1167 //$scanres[$i32] = constructIPv4Address ($dottedquad); // XXX: this should be verified to not break things
e6ca609a 1168 return constructIPv4Address ($dottedquad);
2d318652
DO
1169 markupIPv4AddrList ($scanres);
1170 return $scanres[$i32];
a910829d
DO
1171}
1172
5222f192
DO
1173function bindIpToObject ($ip = '', $object_id = 0, $name = '', $type = '')
1174{
1175 $result = useInsertBlade
1176 (
1177 'IPBonds',
1178 array
1179 (
1180 'ip' => "INET_ATON('$ip')",
1181 'object_id' => "'${object_id}'",
1182 'name' => "'${name}'",
1183 'type' => "'${type}'"
1184 )
1185 );
1186 return $result ? '' : (__FUNCTION__ . '(): useInsertBlade() failed');
1187}
1188
d65353ad
DO
1189function getIPv4NetworkList ($tagfilter = array(), $tfmode = 'any')
1190{
1191 $whereclause = getWhereClause ($tagfilter);
1192 $query =
1193 "select distinct id ".
1194 "from IPRanges left join TagStorage on id = target_id and target_realm = 'ipv4net' " .
1195 "where true ${whereclause} order by ip";
1196 $result = useSelectBlade ($query, __FUNCTION__);
1197 $ret = array();
1198 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1199 $ret[$row['id']] = NULL;
1200 unset ($result);
1201 $keys = array_keys ($ret);
1202 foreach ($keys as $netid)
1203 {
1204 $ret[$netid] = getIPv4NetworkInfo ($netid);
1205 if ($ret[$netid]['parent_id'] and !in_array ($ret[$netid]['parent_id'], $keys))
1206 {
1207 $ret[$netid]['real_parent_id'] = $ret[$netid]['parent_id'];
1208 $ret[$netid]['parent_id'] = NULL;
1209 }
1210 }
1211 return $ret;
1212}
1213
bb0a44e9 1214// Return the id of the smallest IPv4 network containing the given IPv4 address
d65353ad
DO
1215// or NULL, if nothing was found. When finding the covering network for
1216// another network, it is important to filter out matched records with longer
1217// masks (they aren't going to be the right pick).
1218function getIPv4AddressNetworkId ($dottedquad, $masklen = 32)
e673ee24 1219{
3702d093
DO
1220// N.B. To perform the same for IPv6 address and networks, some pre-requisites
1221// are necessary and a different query. IPv6 addresses are 128 bit long, which
1222// is too much for both PHP and MySQL data types. These values must be split
1223// into 4 32-byte long parts (b_u32_0, b_u32_1, b_u32_2, b_u32_3).
1224// Then each network must have its 128-bit netmask split same way and either
1225// stored right in its record or JOINed from decoder and accessible as m_u32_0,
1226// m_u32_1, m_u32_2, m_u32_3. After that the query to pick the smallest network
1227// covering the given address would look as follows:
1228// $query = 'select id from IPv6Network as n where ' .
1229// "(${b_u32_0} & n.m_u32_0 = n.b_u32_0) and " .
1230// "(${b_u32_1} & n.m_u32_1 = n.b_u32_1) and " .
1231// "(${b_u32_2} & n.m_u32_2 = n.b_u32_2) and " .
1232// "(${b_u32_3} & n.m_u32_3 = n.b_u32_3) and " .
1233// "mask < ${masklen} " .
1234// 'order by mask desc limit 1';
1235
bb0a44e9
DO
1236 $query = 'select id from IPRanges where ' .
1237 "inet_aton('${dottedquad}') & (4294967295 >> (32 - mask)) << (32 - mask) = ip " .
d65353ad 1238 "and mask < ${masklen} " .
bb0a44e9 1239 'order by mask desc limit 1';
065eeb52 1240 $result = useSelectBlade ($query, __FUNCTION__);
bb0a44e9
DO
1241 if ($row = $result->fetch (PDO::FETCH_ASSOC))
1242 return $row['id'];
e673ee24
DO
1243 return NULL;
1244}
1245
1246function updateRange ($id=0, $name='')
1247{
1248 global $dbxlink;
1249 $query =
1250 "update IPRanges set name='$name' where id='$id'";
1251 $result = $dbxlink->exec ($query);
1252 return '';
e673ee24
DO
1253}
1254
1255// This function is actually used not only to update, but also to create records,
1256// that's why ON DUPLICATE KEY UPDATE was replaced by DELETE-INSERT pair
1257// (MySQL 4.0 workaround).
b4c1ef87 1258function updateAddress ($ip = 0, $name = '', $reserved = 'no')
e673ee24
DO
1259{
1260 // DELETE may safely fail.
f5575f12 1261 $r = useDeleteBlade ('IPAddress', 'ip', "INET_ATON('${ip}')");
e673ee24
DO
1262 // INSERT may appear not necessary.
1263 if ($name == '' and $reserved == 'no')
1264 return '';
1265 if (useInsertBlade ('IPAddress', array ('name' => "'${name}'", 'reserved' => "'${reserved}'", 'ip' => "INET_ATON('${ip}')")))
1266 return '';
1267 else
b4c1ef87 1268 return __FUNCTION__ . '(): useInsertBlade() failed';
e673ee24
DO
1269}
1270
e673ee24
DO
1271function updateBond ($ip='', $object_id=0, $name='', $type='')
1272{
1273 global $dbxlink;
1274
1275 $query =
1276 "update IPBonds set name='$name', type='$type' where ip=INET_ATON('$ip') and object_id='$object_id'";
1277 $result = $dbxlink->exec ($query);
1278 return '';
1279}
1280
1281function unbindIpFromObject ($ip='', $object_id=0)
1282{
1283 global $dbxlink;
1284
1285 $query =
1286 "delete from IPBonds where ip=INET_ATON('$ip') and object_id='$object_id'";
1287 $result = $dbxlink->exec ($query);
1288 return '';
1289}
1290
1291// This function returns either all or one user account. Array key is user name.
11c8e4be 1292function getUserAccounts ($tagfilter = array(), $tfmode = 'any')
e673ee24 1293{
81736ac1 1294 $whereclause = getWhereClause ($tagfilter);
e673ee24
DO
1295 $query =
1296 'select user_id, user_name, user_password_hash, user_realname, user_enabled ' .
ebae41b3
DO
1297 'from UserAccount left join TagStorage ' .
1298 "on UserAccount.user_id = TagStorage.target_id and target_realm = 'user' " .
1299 "where true ${whereclause} " .
1300 'order by user_name';
065eeb52 1301 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1302 $ret = array();
1303 $clist = array ('user_id', 'user_name', 'user_realname', 'user_password_hash', 'user_enabled');
1304 while ($row = $result->fetch (PDO::FETCH_ASSOC))
64b95774 1305 foreach ($clist as $cname)
e673ee24
DO
1306 $ret[$row['user_name']][$cname] = $row[$cname];
1307 $result->closeCursor();
1308 return $ret;
1309}
1310
e673ee24
DO
1311function searchByl2address ($l2addr)
1312{
e673ee24
DO
1313 $l2addr = l2addressForDatabase ($l2addr);
1314 $query = "select object_id, Port.id as port_id from RackObject as ro inner join Port on ro.id = Port.object_id " .
1315 "where l2address = ${l2addr}";
065eeb52 1316 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1317 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
1318 $result->closeCursor();
1319 if (count ($rows) == 0) // No results.
1320 return NULL;
1321 if (count ($rows) == 1) // Target found.
1322 return $rows[0];
f41b492f 1323 showError ('More than one results was found. This is probably a broken unique key.', __FUNCTION__);
e673ee24
DO
1324 return NULL;
1325}
1326
ea5fc465
DO
1327function getIPv4PrefixSearchResult ($terms)
1328{
1329 $query = "select id, inet_ntoa(ip) as ip, mask, name from IPRanges where ";
1330 $or = '';
1331 foreach (explode (' ', $terms) as $term)
1332 {
1333 $query .= $or . "name like '%${term}%'";
1334 $or = ' or ';
1335 }
065eeb52 1336 $result = useSelectBlade ($query, __FUNCTION__);
ea5fc465
DO
1337 $ret = array();
1338 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1339 $ret[] = $row;
1340 return $ret;
1341}
1342
1343function getIPv4AddressSearchResult ($terms)
1344{
1345 $query = "select inet_ntoa(ip) as ip, name from IPAddress where ";
1346 $or = '';
1347 foreach (explode (' ', $terms) as $term)
1348 {
1349 $query .= $or . "name like '%${term}%'";
1350 $or = ' or ';
1351 }
065eeb52 1352 $result = useSelectBlade ($query, __FUNCTION__);
ea5fc465
DO
1353 $ret = array();
1354 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1355 $ret[] = $row;
1356 return $ret;
1357}
1358
05411ccd
DO
1359function getIPv4RSPoolSearchResult ($terms)
1360{
1361 $query = "select id as pool_id, name from IPRSPool where ";
1362 $or = '';
1363 foreach (explode (' ', $terms) as $term)
1364 {
1365 $query .= $or . "name like '%${term}%'";
1366 $or = ' or ';
1367 }
065eeb52 1368 $result = useSelectBlade ($query, __FUNCTION__);
05411ccd
DO
1369 $ret = array();
1370 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1371 $ret[] = $row;
1372 return $ret;
1373}
1374
1375function getIPv4VServiceSearchResult ($terms)
1376{
1377 $query = "select id, inet_ntoa(vip) as vip, vport, proto, name from IPVirtualService where ";
1378 $or = '';
1379 foreach (explode (' ', $terms) as $term)
1380 {
1381 $query .= $or . "name like '%${term}%'";
1382 $or = ' or ';
1383 }
065eeb52 1384 $result = useSelectBlade ($query, __FUNCTION__);
05411ccd
DO
1385 $ret = array();
1386 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1387 $ret[] = $row;
1388 return $ret;
1389}
1390
6a88e734
DO
1391function getAccountSearchResult ($terms)
1392{
ea62d9dc 1393 $byUsername = getSearchResultByField
6a88e734
DO
1394 (
1395 'UserAccount',
1396 array ('user_id', 'user_name', 'user_realname'),
1397 'user_name',
1398 $terms,
1399 'user_name'
1400 );
ea62d9dc
DO
1401 $byRealname = getSearchResultByField
1402 (
1403 'UserAccount',
1404 array ('user_id', 'user_name', 'user_realname'),
1405 'user_realname',
1406 $terms,
1407 'user_name'
1408 );
1409 // Filter out dupes.
1410 foreach ($byUsername as $res1)
1411 foreach (array_keys ($byRealname) as $key2)
1412 if ($res1['user_id'] == $byRealname[$key2]['user_id'])
1413 {
1414 unset ($byRealname[$key2]);
1415 continue 2;
1416 }
1417 return array_merge ($byUsername, $byRealname);
6a88e734
DO
1418}
1419
e1ae3fb4
AD
1420function getFileSearchResult ($terms)
1421{
1422 $byFilename = getSearchResultByField
1423 (
1424 'File',
1425 array ('id', 'name', 'comment'),
1426 'name',
1427 $terms,
1428 'name'
1429 );
1430 $byComment = getSearchResultByField
1431 (
1432 'File',
1433 array ('id', 'name', 'comment'),
1434 'comment',
1435 $terms,
1436 'name'
1437 );
1438 // Filter out dupes.
1439 foreach ($byFilename as $res1)
1440 foreach (array_keys ($byComment) as $key2)
1441 if ($res1['id'] == $byComment[$key2]['id'])
1442 {
1443 unset ($byComment[$key2]);
1444 continue 2;
1445 }
1446 return array_merge ($byFilename, $byComment);
1447}
1448
6a88e734
DO
1449function getSearchResultByField ($tname, $rcolumns, $scolumn, $terms, $ocolumn = '')
1450{
1451 $pfx = '';
1452 $query = 'select ';
1453 foreach ($rcolumns as $col)
1454 {
1455 $query .= $pfx . $col;
1456 $pfx = ', ';
1457 }
1458 $pfx = '';
1459 $query .= " from ${tname} where ";
1460 foreach (explode (' ', $terms) as $term)
1461 {
1462 $query .= $pfx . "${scolumn} like '%${term}%'";
1463 $pfx = ' or ';
1464 }
1465 if ($ocolumn != '')
1466 $query .= " order by ${ocolumn}";
1467 $result = useSelectBlade ($query, __FUNCTION__);
1468 $ret = array();
1469 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1470 $ret[] = $row;
1471 return $ret;
1472}
1473
e673ee24
DO
1474// This function returns either port ID or NULL for specified arguments.
1475function getPortID ($object_id, $port_name)
1476{
e673ee24 1477 $query = "select id from Port where object_id=${object_id} and name='${port_name}' limit 2";
065eeb52 1478 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1479 $rows = $result->fetchAll (PDO::FETCH_NUM);
1480 if (count ($rows) != 1)
1481 return NULL;
1482 $ret = $rows[0][0];
1483 $result->closeCursor();
1484 return $ret;
1485}
1486
1487function commitCreateUserAccount ($username, $realname, $password)
1488{
1489 return useInsertBlade
1490 (
1491 'UserAccount',
1492 array
1493 (
1494 'user_name' => "'${username}'",
1495 'user_realname' => "'${realname}'",
1496 'user_password_hash' => "'${password}'"
1497 )
1498 );
1499}
1500
1501function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
1502{
1503 global $dbxlink;
1504 $query =
1505 "update UserAccount set user_name = '${new_username}', user_realname = '${new_realname}', " .
1506 "user_password_hash = '${new_password}' where user_id = ${id} limit 1";
1507 $result = $dbxlink->query ($query);
1508 if ($result == NULL)
1509 {
f41b492f 1510 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1511 die;
1512 }
1513 return TRUE;
1514}
1515
1516function commitEnableUserAccount ($id, $new_enabled_value)
1517{
1518 global $dbxlink;
1519 $query =
1520 "update UserAccount set user_enabled = '${new_enabled_value}' " .
1521 "where user_id = ${id} limit 1";
1522 $result = $dbxlink->query ($query);
1523 if ($result == NULL)
1524 {
f41b492f 1525 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1526 die;
1527 }
1528 return TRUE;
1529}
1530
e673ee24
DO
1531// This function returns an array of all port type pairs from PortCompat table.
1532function getPortCompat ()
1533{
e673ee24
DO
1534 $query =
1535 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
1536 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
1537 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
1538 "inner join Chapter as c1 on d1.chapter_no = c1.chapter_no " .
1539 "inner join Chapter as c2 on d2.chapter_no = c2.chapter_no " .
1540 "where c1.chapter_name = 'PortType' and c2.chapter_name = 'PortType'";
065eeb52 1541 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1542 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
1543 $result->closeCursor();
1544 return $ret;
1545}
1546
1547function removePortCompat ($type1 = 0, $type2 = 0)
1548{
1549 global $dbxlink;
1550 if ($type1 == 0 or $type2 == 0)
1551 {
f41b492f 1552 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
1553 die;
1554 }
1555 $query = "delete from PortCompat where type1 = ${type1} and type2 = ${type2} limit 1";
1556 $result = $dbxlink->query ($query);
1557 if ($result == NULL)
1558 {
f41b492f 1559 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1560 die;
1561 }
1562 return TRUE;
1563}
1564
1565function addPortCompat ($type1 = 0, $type2 = 0)
1566{
1567 if ($type1 <= 0 or $type2 <= 0)
1568 {
f41b492f 1569 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
1570 die;
1571 }
1572 return useInsertBlade
1573 (
1574 'PortCompat',
1575 array ('type1' => $type1, 'type2' => $type2)
1576 );
1577}
1578
1579// This function returns the dictionary as an array of trees, each tree
1580// representing a single chapter. Each element has 'id', 'name', 'sticky'
1581// and 'word' keys with the latter holding all the words within the chapter.
2dd59b15 1582function getDict ($parse_links = FALSE)
e673ee24 1583{
6bb8e41d 1584 $query1 =
e673ee24
DO
1585 "select chapter_name, Chapter.chapter_no, dict_key, dict_value, sticky from " .
1586 "Chapter natural left join Dictionary order by chapter_name, dict_value";
065eeb52 1587 $result = useSelectBlade ($query1, __FUNCTION__);
e673ee24 1588 $dict = array();
89fa639f 1589 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24
DO
1590 {
1591 $chapter_no = $row['chapter_no'];
1592 if (!isset ($dict[$chapter_no]))
1593 {
1594 $dict[$chapter_no]['no'] = $chapter_no;
1595 $dict[$chapter_no]['name'] = $row['chapter_name'];
1596 $dict[$chapter_no]['sticky'] = $row['sticky'] == 'yes' ? TRUE : FALSE;
1597 $dict[$chapter_no]['word'] = array();
1598 }
1599 if ($row['dict_key'] != NULL)
6bb8e41d 1600 {
2dd59b15
DO
1601 $dict[$chapter_no]['word'][$row['dict_key']] = $parse_links ?
1602 parseWikiLink ($row['dict_value'], 'a') : $row['dict_value'];
6bb8e41d
DO
1603 $dict[$chapter_no]['refcnt'][$row['dict_key']] = 0;
1604 }
e673ee24 1605 }
89fa639f
DO
1606 $result->closeCursor();
1607 unset ($result);
6bb8e41d
DO
1608// Find the list of all assigned values of dictionary-addressed attributes, each with
1609// chapter/word keyed reference counters. Use the structure to adjust reference counters
1610// of the returned disctionary words.
1611 $query2 = "select a.attr_id, am.chapter_no, uint_value, count(object_id) as refcnt " .
1612 "from Attribute as a inner join AttributeMap as am on a.attr_id = am.attr_id " .
1613 "inner join AttributeValue as av on a.attr_id = av.attr_id " .
1614 "inner join Dictionary as d on am.chapter_no = d.chapter_no and av.uint_value = d.dict_key " .
1615 "where attr_type = 'dict' group by a.attr_id, am.chapter_no, uint_value " .
1616 "order by a.attr_id, am.chapter_no, uint_value";
065eeb52 1617 $result = useSelectBlade ($query2, __FUNCTION__);
89fa639f 1618 while ($row = $result->fetch (PDO::FETCH_ASSOC))
6bb8e41d 1619 $dict[$row['chapter_no']]['refcnt'][$row['uint_value']] = $row['refcnt'];
89fa639f 1620 $result->closeCursor();
e673ee24
DO
1621 return $dict;
1622}
1623
da95280e
DO
1624function getDictStats ()
1625{
82f7e2e8 1626 $stock_chapters = array (1, 2, 3, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23);
da95280e 1627 $query =
5aa28abb
DO
1628 "select Chapter.chapter_no, chapter_name, count(dict_key) as wc from " .
1629 "Chapter natural left join Dictionary group by Chapter.chapter_no";
065eeb52 1630 $result = useSelectBlade ($query, __FUNCTION__);
da95280e 1631 $tc = $tw = $uc = $uw = 0;
89fa639f 1632 while ($row = $result->fetch (PDO::FETCH_ASSOC))
da95280e
DO
1633 {
1634 $tc++;
1635 $tw += $row['wc'];;
1636 if (in_array ($row['chapter_no'], $stock_chapters))
1637 continue;
1638 $uc++;
1639 $uw += $row['wc'];;
1640 }
89fa639f
DO
1641 $result->closeCursor();
1642 unset ($result);
08b4cb24
DO
1643 $query = "select count(attr_id) as attrc from RackObject as ro left join " .
1644 "AttributeValue as av on ro.id = av.object_id group by ro.id";
065eeb52 1645 $result = useSelectBlade ($query, __FUNCTION__);
08b4cb24 1646 $to = $ta = $so = 0;
89fa639f 1647 while ($row = $result->fetch (PDO::FETCH_ASSOC))
08b4cb24
DO
1648 {
1649 $to++;
1650 if ($row['attrc'] != 0)
1651 {
1652 $so++;
1653 $ta += $row['attrc'];
1654 }
1655 }
89fa639f 1656 $result->closeCursor();
da95280e
DO
1657 $ret = array();
1658 $ret['Total chapters in dictionary'] = $tc;
1659 $ret['Total words in dictionary'] = $tw;
1660 $ret['User chapters'] = $uc;
1661 $ret['Words in user chapters'] = $uw;
08b4cb24
DO
1662 $ret['Total objects'] = $to;
1663 $ret['Objects with stickers'] = $so;
1664 $ret['Total stickers attached'] = $ta;
da95280e
DO
1665 return $ret;
1666}
1667
6807f0be 1668function getIPv4Stats ()
9ec5fdf1 1669{
9ec5fdf1
DO
1670 $ret = array();
1671 $subject = array();
1672 $subject[] = array ('q' => 'select count(id) from IPRanges', 'txt' => 'Networks');
1673 $subject[] = array ('q' => 'select count(ip) from IPAddress', 'txt' => 'Addresses commented/reserved');
1674 $subject[] = array ('q' => 'select count(ip) from IPBonds', 'txt' => 'Addresses allocated');
1675 $subject[] = array ('q' => 'select count(*) from PortForwarding', 'txt' => 'NAT rules');
1676 $subject[] = array ('q' => 'select count(id) from IPVirtualService', 'txt' => 'Virtual services');
1677 $subject[] = array ('q' => 'select count(id) from IPRSPool', 'txt' => 'Real server pools');
1678 $subject[] = array ('q' => 'select count(id) from IPRealServer', 'txt' => 'Real servers');
1679 $subject[] = array ('q' => 'select count(distinct object_id) from IPLoadBalancer', 'txt' => 'Load balancers');
1680
1681 foreach ($subject as $item)
1682 {
065eeb52 1683 $result = useSelectBlade ($item['q'], __FUNCTION__);
9ec5fdf1
DO
1684 $row = $result->fetch (PDO::FETCH_NUM);
1685 $ret[$item['txt']] = $row[0];
1686 $result->closeCursor();
1687 unset ($result);
1688 }
1689 return $ret;
1690}
1691
6807f0be 1692function getRackspaceStats ()
9ec5fdf1 1693{
9ec5fdf1
DO
1694 $ret = array();
1695 $subject = array();
1696 $subject[] = array ('q' => 'select count(*) from Dictionary where chapter_no = 3', 'txt' => 'Rack rows');
1697 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
1698 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
1699 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
1700
1701 foreach ($subject as $item)
1702 {
065eeb52 1703 $result = useSelectBlade ($item['q'], __FUNCTION__);
9ec5fdf1 1704 $row = $result->fetch (PDO::FETCH_NUM);
82f7e2e8 1705 $ret[$item['txt']] = empty ($row[0]) ? 0 : $row[0];
9ec5fdf1
DO
1706 $result->closeCursor();
1707 unset ($result);
1708 }
1709 return $ret;
1710}
1711
e9b9a095 1712function renderTagStats ()
5bbbeaa2 1713{
e9b9a095
DO
1714 global $taglist, $root;
1715 $query = "select id, tag, count(tag_id) as refcnt from " .
5bbbeaa2 1716 "TagTree inner join TagStorage on TagTree.id = TagStorage.tag_id " .
e9b9a095
DO
1717 "group by tag_id order by refcnt desc limit 50";
1718 // The same data is already present in pre-loaded tag list, but not in
1719 // the form we need. So let's ask the DB server for cooked top list and
1720 // use the cooked tag list to break it down.
065eeb52 1721 $result = useSelectBlade ($query, __FUNCTION__);
e9b9a095
DO
1722 $refc = $result->fetchAll (PDO::FETCH_ASSOC);
1723 echo '<table border=1><tr><th>tag</th><th>total</th><th>objects</th><th>IPv4 nets</th><th>racks</th>';
1724 echo '<th>IPv4 VS</th><th>IPv4 RS pools</th><th>users</th></tr>';
1725 $pagebyrealm = array
1726 (
e1ae3fb4 1727 'file' => 'filesbylink&entity_type=all',
e9b9a095 1728 'ipv4net' => 'ipv4space&tab=default',
e9b9a095
DO
1729 'ipv4vs' => 'ipv4vslist&tab=default',
1730 'ipv4rspool' => 'ipv4rsplist&tab=default',
e1ae3fb4
AD
1731 'object' => 'objgroup&group_id=0',
1732 'rack' => 'rackspace&tab=default',
e9b9a095
DO
1733 'user' => 'userlist&tab=default'
1734 );
1735 foreach ($refc as $ref)
1736 {
1737 echo "<tr><td>${ref['tag']}</td><td>${ref['refcnt']}</td>";
e1ae3fb4 1738 foreach (array ('file', 'ipv4net', 'ipv4rspool', 'ipv4vs', 'object', 'rack', 'user') as $realm)
e9b9a095
DO
1739 {
1740 echo '<td>';
1741 if (!isset ($taglist[$ref['id']]['refcnt'][$realm]))
1742 echo '&nbsp;';
1743 else
1744 {
1745 echo "<a href='${root}?page=" . $pagebyrealm[$realm] . "&tagfilter[]=${ref['id']}'>";
1746 echo $taglist[$ref['id']]['refcnt'][$realm] . '</a>';
1747 }
1748 echo '</td>';
1749 }
1750 echo '</tr>';
1751 }
1752 echo '</table>';
5bbbeaa2
DO
1753}
1754
6807f0be
DO
1755/*
1756
1757The following allows figuring out records in TagStorage, which refer to non-existing entities:
1758
e1ae3fb4 1759mysql> select target_id from TagStorage left join Files on target_id = id where target_realm = 'file' and id is null;
6807f0be
DO
1760mysql> select target_id from TagStorage left join IPRanges on target_id = id where target_realm = 'ipv4net' and id is null;
1761mysql> select target_id from TagStorage left join RackObject on target_id = id where target_realm = 'object' and id is null;
1762mysql> select target_id from TagStorage left join Rack on target_id = id where target_realm = 'rack' and id is null;
1763mysql> select target_id from TagStorage left join IPVirtualService on target_id = id where target_realm = 'ipv4vs' and id is null;
1764mysql> select target_id from TagStorage left join IPRSPool on target_id = id where target_realm = 'ipv4rspool' and id is null;
1765mysql> select target_id from TagStorage left join UserAccount on target_id = user_id where target_realm = 'user' and user_id is null;
1766
1767Accordingly, these are the records, which refer to non-existent tags:
1768
1769mysql> select tag_id from TagStorage left join TagTree on tag_id = id where id is null;
1770
1771*/
1772
e673ee24
DO
1773function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1774{
1775 if ($chapter_no <= 0 or $dict_key <= 0 or empty ($dict_value))
1776 {
f41b492f 1777 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1778 die;
1779 }
1780 global $dbxlink;
1781 $query =
1782 "update Dictionary set dict_value = '${dict_value}' where chapter_no=${chapter_no} " .
1783 "and dict_key=${dict_key} limit 1";
1784 $result = $dbxlink->query ($query);
1785 if ($result == NULL)
1786 {
f41b492f 1787 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1788 die;
1789 }
1790 return TRUE;
1791}
1792
1793function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1794{
1795 if ($chapter_no <= 0 or empty ($dict_value))
1796 {
f41b492f 1797 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1798 die;
1799 }
1800 return useInsertBlade
1801 (
1802 'Dictionary',
1803 array ('chapter_no' => $chapter_no, 'dict_value' => "'${dict_value}'")
1804 );
1805}
1806
1807function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1808{
1809 if ($chapter_no <= 0 or $dict_key <= 0)
1810 {
f41b492f 1811 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1812 die;
1813 }
1814 global $dbxlink;
1815 $query =
1816 "delete from Dictionary where chapter_no=${chapter_no} " .
1817 "and dict_key=${dict_key} limit 1";
1818 $result = $dbxlink->query ($query);
1819 if ($result == NULL)
1820 {
f41b492f 1821 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1822 die;
1823 }
1824 return TRUE;
1825}
1826
1827function commitAddChapter ($chapter_name = '')
1828{
1829 if (empty ($chapter_name))
1830 {
f41b492f 1831 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1832 die;
1833 }
1834 return useInsertBlade
1835 (
1836 'Chapter',
1837 array ('chapter_name' => "'${chapter_name}'")
1838 );
1839}
1840
1841function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
1842{
1843 if ($chapter_no <= 0 or empty ($chapter_name))
1844 {
f41b492f 1845 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1846 die;
1847 }
1848 global $dbxlink;
1849 $query =
1850 "update Chapter set chapter_name = '${chapter_name}' where chapter_no = ${chapter_no} " .
1851 "and sticky = 'no' limit 1";
1852 $result = $dbxlink->query ($query);
1853 if ($result == NULL)
1854 {
f41b492f 1855 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1856 die;
1857 }
1858 return TRUE;
1859}
1860
1861function commitDeleteChapter ($chapter_no = 0)
1862{
1863 if ($chapter_no <= 0)
1864 {
f41b492f 1865 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1866 die;
1867 }
1868 global $dbxlink;
1869 $query =
1870 "delete from Chapter where chapter_no = ${chapter_no} and sticky = 'no' limit 1";
1871 $result = $dbxlink->query ($query);
1872 if ($result == NULL)
1873 {
f41b492f 1874 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1875 die;
1876 }
1877 return TRUE;
1878}
1879
4c330a14
DO
1880// This is a dictionary accessor. We perform link rendering, so the user sees
1881// nice <select> drop-downs.
e673ee24
DO
1882function readChapter ($chapter_name = '')
1883{
1884 if (empty ($chapter_name))
1885 {
f41b492f 1886 showError ('invalid argument', __FUNCTION__);
e673ee24
DO
1887 return NULL;
1888 }
e673ee24
DO
1889 $query =
1890 "select dict_key, dict_value from Dictionary natural join Chapter " .
4aa8609b 1891 "where chapter_name = '${chapter_name}'";
065eeb52 1892 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1893 $chapter = array();
1894 while ($row = $result->fetch (PDO::FETCH_ASSOC))
4c330a14 1895 $chapter[$row['dict_key']] = parseWikiLink ($row['dict_value'], 'o');
e673ee24 1896 $result->closeCursor();
4aa8609b
DO
1897 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
1898 asort ($chapter);
e673ee24
DO
1899 return $chapter;
1900}
1901
1902function getAttrMap ()
1903{
e673ee24
DO
1904 $query =
1905 "select a.attr_id, a.attr_type, a.attr_name, am.objtype_id, " .
1906 "d.dict_value as objtype_name, am.chapter_no, c2.chapter_name from " .
1907 "Attribute as a natural left join AttributeMap as am " .
1908 "left join Dictionary as d on am.objtype_id = d.dict_key " .
1909 "left join Chapter as c1 on d.chapter_no = c1.chapter_no " .
1910 "left join Chapter as c2 on am.chapter_no = c2.chapter_no " .
1911 "where c1.chapter_name = 'RackObjectType' or c1.chapter_name is null " .
1912 "order by attr_name";
065eeb52 1913 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1914 $ret = array();
1915 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1916 {
1917 $attr_id = $row['attr_id'];
1918 if (!isset ($ret[$attr_id]))
1919 {
1920 $ret[$attr_id]['id'] = $attr_id;
1921 $ret[$attr_id]['type'] = $row['attr_type'];
1922 $ret[$attr_id]['name'] = $row['attr_name'];
1923 $ret[$attr_id]['application'] = array();
1924 }
1925 if ($row['objtype_id'] == '')
1926 continue;
1927 $application['objtype_id'] = $row['objtype_id'];
1928 $application['objtype_name'] = $row['objtype_name'];
1929 if ($row['attr_type'] == 'dict')
1930 {
1931 $application['chapter_no'] = $row['chapter_no'];
1932 $application['chapter_name'] = $row['chapter_name'];
1933 }
1934 $ret[$attr_id]['application'][] = $application;
1935 }
1936 $result->closeCursor();
1937 return $ret;
1938}
1939
1940function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
1941{
1942 if ($attr_id <= 0 or empty ($attr_name))
1943 {
f41b492f 1944 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1945 die;
1946 }
1947 global $dbxlink;
1948 $query =
1949 "update Attribute set attr_name = '${attr_name}' " .
1950 "where attr_id = ${attr_id} limit 1";
1951 $result = $dbxlink->query ($query);
1952 if ($result == NULL)
1953 {
f41b492f 1954 showError ("SQL query '${query}' failed", __FUNCTION__);
e673ee24
DO
1955 die;
1956 }
1957 return TRUE;
1958}
1959
1960function commitAddAttribute ($attr_name = '', $attr_type = '')
1961{
1962 if (empty ($attr_name))
1963 {
f41b492f 1964 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1965 die;
1966 }
1967 switch ($attr_type)
1968 {
1969 case 'uint':
1970 case 'float':
1971 case 'string':
1972 case 'dict':
1973 break;
1974 default:
f41b492f 1975 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1976 die;
1977 }
1978 return useInsertBlade
1979 (
1980 'Attribute',
1981 array ('attr_name' => "'${attr_name}'", 'attr_type' => "'${attr_type}'")
1982 );
1983}
1984
1985function commitDeleteAttribute ($attr_id = 0)
1986{
1987 if ($attr_id <= 0)
1988 {
f41b492f 1989 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1990 die;
1991 }
f5575f12 1992 return useDeleteBlade ('Attribute', 'attr_id', $attr_id);
e673ee24
DO
1993}
1994
1995// FIXME: don't store garbage in chapter_no for non-dictionary types.
1996function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
1997{
1998 if ($attr_id <= 0 or $objtype_id <= 0 or $chapter_no <= 0)
1999 {
f41b492f 2000 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
2001 die;
2002 }
2003 return useInsertBlade
2004 (
2005 'AttributeMap',
2006 array
2007 (
2008 'attr_id' => $attr_id,
2009 'objtype_id' => $objtype_id,
2010 'chapter_no' => $chapter_no
2011 )
2012 );
2013}
2014
2015function commitReduceAttrMap ($attr_id = 0, $objtype_id)
2016{
2017 if ($attr_id <= 0 or $objtype_id <= 0)
2018 {
f41b492f 2019 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
2020 die;
2021 }
2022 global $dbxlink;
2023 $query =
2024 "delete from AttributeMap where attr_id=${attr_id} " .
2025 "and objtype_id=${objtype_id} limit 1";
2026 $result = $dbxlink->query ($query);
2027 if ($result == NULL)
2028 {
f41b492f 2029 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
2030 die;
2031 }
2032 return TRUE;
2033}
2034
2035// This function returns all optional attributes for requested object
2036// as an array of records. NULL is returned on error and empty array
2037// is returned, if there are no attributes found.
24cbe8af 2038function getAttrValues ($object_id, $strip_optgroup = FALSE)
e673ee24
DO
2039{
2040 if ($object_id <= 0)
2041 {
f41b492f 2042 showError ('Invalid argument', __FUNCTION__);
e673ee24
DO
2043 return NULL;
2044 }
e673ee24
DO
2045 $ret = array();
2046 $query =
2047 "select A.attr_id, A.attr_name, A.attr_type, C.chapter_name, " .
2048 "AV.uint_value, AV.float_value, AV.string_value, D.dict_value from " .
2049 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
2050 "inner join Attribute as A using (attr_id) " .
2051 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
2052 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_no = D.chapter_no " .
2053 "left join Chapter as C on AM.chapter_no = C.chapter_no " .
1a576609 2054 "where RO.id = ${object_id} order by A.attr_type, A.attr_name";
065eeb52 2055 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
2056 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2057 {
2058 $record = array();
2059 $record['id'] = $row['attr_id'];
2060 $record['name'] = $row['attr_name'];
2061 $record['type'] = $row['attr_type'];
2062 switch ($row['attr_type'])
2063 {
2064 case 'uint':
2065 case 'float':
2066 case 'string':
24cbe8af
DO
2067 $record['value'] = $row[$row['attr_type'] . '_value'];
2068 $record['a_value'] = parseWikiLink ($record['value'], 'a');
2069 break;
e673ee24 2070 case 'dict':
24cbe8af
DO
2071 $record['value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'o', $strip_optgroup);
2072 $record['a_value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'a', $strip_optgroup);
e673ee24
DO
2073 $record['chapter_name'] = $row['chapter_name'];
2074 $record['key'] = $row['uint_value'];
2075 break;
2076 default:
2077 $record['value'] = NULL;
2078 break;
2079 }
2080 $ret[$row['attr_id']] = $record;
2081 }
2082 $result->closeCursor();
2083 return $ret;
2084}
2085
2086function commitResetAttrValue ($object_id = 0, $attr_id = 0)
2087{
2088 if ($object_id <= 0 or $attr_id <= 0)
2089 {
f41b492f 2090 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
2091 die;
2092 }
2093 global $dbxlink;
2094 $query = "delete from AttributeValue where object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2095 $result = $dbxlink->query ($query);
2096 if ($result == NULL)
2097 {
f41b492f 2098 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
2099 die;
2100 }
2101 return TRUE;
2102}
2103
2104// FIXME: don't share common code with use commitResetAttrValue()
2105function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
2106{
2107 if ($object_id <= 0 or $attr_id <= 0)
2108 {
f41b492f 2109 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
2110 die;
2111 }
2112 if (empty ($value))
2113 return commitResetAttrValue ($object_id, $attr_id);
2114 global $dbxlink;
2115 $query1 = "select attr_type from Attribute where attr_id = ${attr_id}";
2116 $result = $dbxlink->query ($query1);
2117 if ($result == NULL)
2118 {
f41b492f 2119 showError ('SQL query #1 failed', __FUNCTION__);
e673ee24
DO
2120 die;
2121 }
2122 $row = $result->fetch (PDO::FETCH_NUM);
2123 if ($row == NULL)
2124 {
f41b492f 2125 showError ('SQL query #1 returned no results', __FUNCTION__);
e673ee24
DO
2126 die;
2127 }
2128 $attr_type = $row[0];
2129 $result->closeCursor();
2130 switch ($attr_type)
2131 {
2132 case 'uint':
2133 case 'float':
2134 case 'string':
2135 $column = $attr_type . '_value';
2136 break;
2137 case 'dict':
2138 $column = 'uint_value';
2139 break;
2140 default:
f41b492f 2141 showError ("Unknown attribute type '${attr_type}' met", __FUNCTION__);
e673ee24
DO
2142 die;
2143 }
2144 $query2 =
2145 "delete from AttributeValue where " .
2146 "object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2147 $result = $dbxlink->query ($query2);
2148 if ($result == NULL)
2149 {
f41b492f 2150 showError ('SQL query #2 failed', __FUNCTION__);
e673ee24
DO
2151 die;
2152 }
2153 // We know $value isn't empty here.
2154 $query3 =
2155 "insert into AttributeValue set ${column} = '${value}', " .
2156 "object_id = ${object_id}, attr_id = ${attr_id} ";
2157 $result = $dbxlink->query ($query3);
2158 if ($result == NULL)
2159 {
f41b492f 2160 showError ('SQL query #3 failed', __FUNCTION__);
e673ee24
DO
2161 die;
2162 }
2163 return TRUE;
2164}
2165
2166function commitUseupPort ($port_id = 0)
2167{
2168 if ($port_id <= 0)
2169 {
f41b492f 2170 showError ("Invalid argument", __FUNCTION__);
e673ee24
DO
2171 die;
2172 }
2173 global $dbxlink;
2174 $query = "update Port set reservation_comment = NULL where id = ${port_id} limit 1";
2175 $result = $dbxlink->exec ($query);
2176 if ($result == NULL)
2177 {
f41b492f 2178 showError ("SQL query failed", __FUNCTION__);
e673ee24
DO
2179 die;
2180 }
2181 return TRUE;
2182
2183}
2184
2185// This is a swiss-knife blade to insert a record into a table.
2186// The first argument is table name.
2187// The second argument is an array of "name" => "value" pairs.
2188// The function returns either TRUE or FALSE (we expect one row
2189// to be inserted).
2190function useInsertBlade ($tablename, $values)
2191{
2192 global $dbxlink;
2193 $namelist = $valuelist = '';
2194 foreach ($values as $name => $value)
2195 {
2196 $namelist = $namelist . ($namelist == '' ? "(${name}" : ", ${name}");
2197 $valuelist = $valuelist . ($valuelist == '' ? "(${value}" : ", ${value}");
2198 }
2199 $query = "insert into ${tablename} ${namelist}) values ${valuelist})";
2200 $result = $dbxlink->exec ($query);
2201 if ($result != 1)
2202 return FALSE;
2203 return TRUE;
2204}
2205
2206// This swiss-knife blade deletes one record from the specified table
2207// using the specified key name and value.
f5575f12 2208function useDeleteBlade ($tablename, $keyname, $keyvalue)
e673ee24
DO
2209{
2210 global $dbxlink;
f5575f12 2211 return 1 === $dbxlink->exec ("delete from ${tablename} where ${keyname}=${keyvalue} limit 1");
e673ee24
DO
2212}
2213
5967b83d
DO
2214function useSelectBlade ($query, $caller = 'N/A')
2215{
2216 global $dbxlink;
2217 $result = $dbxlink->query ($query);
2218 if ($result == NULL)
2219 {
2220 $ei = $dbxlink->errorInfo();
105a3bc8 2221 showError ("SQL query '${query}'\n failed in useSelectBlade with error ${ei[1]} (${ei[2]})", $caller);
5967b83d
DO
2222 return NULL;
2223 }
2224 return $result;
2225}
2226
9c0b0016
DO
2227function loadConfigCache ()
2228{
4fe32e78 2229 $query = 'SELECT varname, varvalue, vartype, is_hidden, emptyok, description FROM Config ORDER BY varname';
065eeb52 2230 $result = useSelectBlade ($query, __FUNCTION__);
9c0b0016
DO
2231 $cache = array();
2232 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2233 $cache[$row['varname']] = $row;
2234 $result->closeCursor();
2235 return $cache;
2236}
2237
2238// setConfigVar() is expected to perform all necessary filtering
2239function storeConfigVar ($varname = NULL, $varvalue = NULL)
2240{
c461c579 2241 global $dbxlink;
bb6b9880 2242 if (empty ($varname) || $varvalue === NULL)
9c0b0016 2243 {
f41b492f 2244 showError ('Invalid arguments', __FUNCTION__);
9c0b0016
DO
2245 return FALSE;
2246 }
2247 $query = "update Config set varvalue='${varvalue}' where varname='${varname}' limit 1";
2248 $result = $dbxlink->query ($query);
2249 if ($result == NULL)
2250 {
f41b492f 2251 showError ("SQL query '${query}' failed", __FUNCTION__);
9c0b0016
DO
2252 return FALSE;
2253 }
2254 $rc = $result->rowCount();
2255 $result->closeCursor();
f7ee57a1 2256 if ($rc == 0 or $rc == 1)
9c0b0016 2257 return TRUE;
f41b492f 2258 showError ("Something went wrong for args '${varname}', '${varvalue}'", __FUNCTION__);
9c0b0016
DO
2259 return FALSE;
2260}
2261
fbbb74fb
DO
2262// Database version detector. Should behave corretly on any
2263// working dataset a user might have.
2264function getDatabaseVersion ()
2265{
2266 global $dbxlink;
2267 $query = "select varvalue from Config where varname = 'DB_VERSION' and vartype = 'string'";
2268 $result = $dbxlink->query ($query);
2269 if ($result == NULL)
2270 {
2271 $errorInfo = $dbxlink->errorInfo();
2272 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
2273 return '0.14.4';
4d2e93f2 2274 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
fbbb74fb
DO
2275 }
2276 $rows = $result->fetchAll (PDO::FETCH_NUM);
2277 if (count ($rows) != 1 || empty ($rows[0][0]))
2278 {
2279 $result->closeCursor();
4d2e93f2 2280 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
fbbb74fb
DO
2281 }
2282 $ret = $rows[0][0];
2283 $result->closeCursor();
2284 return $ret;
2285}
2286
da04825a
DO
2287// Return an array of virtual services. For each of them list real server pools
2288// with their load balancers and other stats.
62a1dcb5
DO
2289function getSLBSummary ()
2290{
6fec9f39
DO
2291 $query = 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
2292 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
2293 'from IPVirtualService as vs inner join IPLoadBalancer as lb on vs.id = lb.vs_id ' .
3e56d972 2294 'inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
6fec9f39
DO
2295 'left join IPRealServer as rs on rs.rspool_id = lb.rspool_id ' .
2296 'group by vs.id, object_id order by vs.vip, object_id';
065eeb52 2297 $result = useSelectBlade ($query, __FUNCTION__);
c3bdc503
DO
2298 $ret = array();
2299 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2300 {
4cadac8f 2301 $vsid = $row['vsid'];
da04825a 2302 $object_id = $row['object_id'];
4cadac8f
DO
2303 if (!isset ($ret[$vsid]))
2304 {
2305 $ret[$vsid] = array();
13bffb29 2306 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
4cadac8f 2307 $ret[$vsid][$cname] = $row[$cname];
da04825a 2308 $ret[$vsid]['lblist'] = array();
4cadac8f 2309 }
6fec9f39
DO
2310 // There's only one assigned RS pool possible for each LB-VS combination.
2311 $ret[$vsid]['lblist'][$row['object_id']] = array
2312 (
2313 'id' => $row['rspool_id'],
2314 'size' => $row['rscount'],
2315 'name' => $row['pool_name']
2316 );
c3bdc503 2317 }
060ba26e 2318 $result->closeCursor();
c3bdc503 2319 return $ret;
62a1dcb5
DO
2320}
2321
da04825a
DO
2322// Get the detailed composition of a particular virtual service, namely the list
2323// of all pools, each shown with the list of objects servicing it. VS/RS configs
2324// will be returned as well.
060ba26e
DO
2325function getVServiceInfo ($vsid = 0)
2326{
2b4eee17
DO
2327 $query1 = "select inet_ntoa(vip) as vip, vport, proto, name, vsconfig, rsconfig " .
2328 "from IPVirtualService where id = ${vsid}";
065eeb52 2329 $result = useSelectBlade ($query1, __FUNCTION__);
060ba26e 2330 $vsinfo = array ();
89fa639f 2331 $row = $result->fetch (PDO::FETCH_ASSOC);
2b4eee17
DO
2332 if (!$row)
2333 return NULL;
2334 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig') as $cname)
2335 $vsinfo[$cname] = $row[$cname];
2336 $vsinfo['rspool'] = array();
89fa639f
DO
2337 $result->closeCursor();
2338 unset ($result);
2b4eee17
DO
2339 $query2 = "select pool.id, name, pool.vsconfig, pool.rsconfig, object_id, " .
2340 "lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig from " .
2341 "IPRSPool as pool left join IPLoadBalancer as lb on pool.id = lb.rspool_id " .
2342 "where vs_id = ${vsid} order by pool.name, object_id";
065eeb52 2343 $result = useSelectBlade ($query2, __FUNCTION__);
89fa639f 2344 while ($row = $result->fetch (PDO::FETCH_ASSOC))
060ba26e 2345 {
2b4eee17 2346 if (!isset ($vsinfo['rspool'][$row['id']]))
060ba26e 2347 {
2b4eee17
DO
2348 $vsinfo['rspool'][$row['id']]['name'] = $row['name'];
2349 $vsinfo['rspool'][$row['id']]['vsconfig'] = $row['vsconfig'];
2350 $vsinfo['rspool'][$row['id']]['rsconfig'] = $row['rsconfig'];
2351 $vsinfo['rspool'][$row['id']]['lblist'] = array();
060ba26e 2352 }
2b4eee17
DO
2353 if ($row['object_id'] == NULL)
2354 continue;
2355 $vsinfo['rspool'][$row['id']]['lblist'][$row['object_id']] = array
2356 (
2357 'vsconfig' => $row['lb_vsconfig'],
2358 'rsconfig' => $row['lb_rsconfig']
2359 );
060ba26e 2360 }
89fa639f 2361 $result->closeCursor();
060ba26e
DO
2362 return $vsinfo;
2363}
2364
71b8bda1
DO
2365// Collect and return the following info about the given real server pool:
2366// basic information
2367// parent virtual service information
c1ca768c 2368// load balancers list (each with a list of VSes)
71b8bda1
DO
2369// real servers list
2370
2371function getRSPoolInfo ($id = 0)
2372{
c1ca768c 2373 $query1 = "select id, name, vsconfig, rsconfig from " .
481a7f8b 2374 "IPRSPool where id = ${id}";
065eeb52 2375 $result = useSelectBlade ($query1, __FUNCTION__);
71b8bda1 2376 $ret = array();
89fa639f 2377 $row = $result->fetch (PDO::FETCH_ASSOC);
71b8bda1
DO
2378 if (!$row)
2379 return NULL;
70c24883 2380 foreach (array ('id', 'name', 'vsconfig', 'rsconfig') as $c)
71b8bda1 2381 $ret[$c] = $row[$c];
89fa639f
DO
2382 $result->closeCursor();
2383 unset ($result);
71b8bda1
DO
2384 $ret['lblist'] = array();
2385 $ret['rslist'] = array();
e7959acb
DO
2386 $query2 = "select object_id, vs_id, lb.vsconfig, lb.rsconfig from " .
2387 "IPLoadBalancer as lb inner join IPVirtualService as vs on lb.vs_id = vs.id " .
2388 "where rspool_id = ${id} order by object_id, vip, vport";
065eeb52 2389 $result = useSelectBlade ($query2, __FUNCTION__);
89fa639f 2390 while ($row = $result->fetch (PDO::FETCH_ASSOC))
71b8bda1 2391 foreach (array ('vsconfig', 'rsconfig') as $c)
c1ca768c 2392 $ret['lblist'][$row['object_id']][$row['vs_id']][$c] = $row[$c];
89fa639f
DO
2393 $result->closeCursor();
2394 unset ($result);
1f7d18fa 2395 $query3 = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rsconfig from " .
676a8268 2396 "IPRealServer where rspool_id = ${id} order by IPRealServer.rsip, rsport";
065eeb52 2397 $result = useSelectBlade ($query3, __FUNCTION__);
89fa639f 2398 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1f7d18fa 2399 foreach (array ('inservice', 'rsip', 'rsport', 'rsconfig') as $c)
71b8bda1 2400 $ret['rslist'][$row['id']][$c] = $row[$c];
89fa639f 2401 $result->closeCursor();
71b8bda1
DO
2402 return $ret;
2403}
2404
7e7a8387 2405function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
ca461127 2406{
79a9edb4 2407 if ($pool_id <= 0)
ca461127
DO
2408 {
2409 showError ('Invalid arguments', __FUNCTION__);
2410 die;
2411 }
79a9edb4
DO
2412 if (empty ($rsport) or $rsport == 0)
2413 $rsport = 'NULL';
ca461127
DO
2414 return useInsertBlade
2415 (
2416 'IPRealServer',
2417 array
2418 (
2419 'rsip' => "inet_aton('${rsip}')",
2420 'rsport' => $rsport,
2421 'rspool_id' => $pool_id,
bcbeadb4 2422 'inservice' => ($inservice == 'yes' ? "'yes'" : "'no'"),
3241551e
DO
2423 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2424 )
2425 );
2426}
2427
c63a8d6e 2428function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig, $taglist = array())
d6517a21
DO
2429{
2430 if (empty ($vip) or $vport <= 0 or empty ($proto))
c63a8d6e
DO
2431 return __FUNCTION__ . ': invalid arguments';
2432 if (!useInsertBlade
d6517a21
DO
2433 (
2434 'IPVirtualService',
2435 array
2436 (
2437 'vip' => "inet_aton('${vip}')",
2438 'vport' => $vport,
2439 'proto' => "'${proto}'",
2440 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2441 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2442 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2443 )
c63a8d6e
DO
2444 ))
2445 return __FUNCTION__ . ': SQL insertion failed';
351c0966 2446 return produceTagsForLastRecord ('ipv4vs', $taglist);
d6517a21
DO
2447}
2448
c1ca768c 2449function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2450{
c1ca768c 2451 if ($pool_id <= 0 or $object_id <= 0 or $vs_id <= 0)
3241551e
DO
2452 {
2453 showError ('Invalid arguments', __FUNCTION__);
2454 die;
2455 }
2456 return useInsertBlade
2457 (
2458 'IPLoadBalancer',
2459 array
2460 (
2461 'object_id' => $object_id,
2462 'rspool_id' => $pool_id,
c1ca768c 2463 'vs_id' => $vs_id,
3241551e
DO
2464 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2465 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2466 )
ca461127
DO
2467 );
2468}
2469
fb1c4a54
DO
2470function commitDeleteRS ($id = 0)
2471{
2472 if ($id <= 0)
2473 return FALSE;
f5575f12 2474 return useDeleteBlade ('IPRealServer', 'id', $id);
fb1c4a54
DO
2475}
2476
d6517a21
DO
2477function commitDeleteVS ($id = 0)
2478{
2479 if ($id <= 0)
2480 return FALSE;
01b6b4d6 2481 return useDeleteBlade ('IPVirtualService', 'id', $id) && destroyTagsForEntity ('ipv4vs', $id);
d6517a21
DO
2482}
2483
c1ca768c 2484function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
3241551e
DO
2485{
2486 global $dbxlink;
c4d85fd1 2487 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
3241551e 2488 return FALSE;
c1ca768c
DO
2489 $query = "delete from IPLoadBalancer where object_id = ${object_id} and " .
2490 "rspool_id = ${pool_id} and vs_id = ${vs_id} limit 1";
3241551e
DO
2491 $result = $dbxlink->exec ($query);
2492 if ($result === NULL)
2493 return FALSE;
2494 elseif ($result != 1)
2495 return FALSE;
2496 else
2497 return TRUE;
2498}
2499
fb1c4a54
DO
2500function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2501{
79a9edb4 2502 if ($rsid <= 0)
fb1c4a54
DO
2503 {
2504 showError ('Invalid args', __FUNCTION__);
2505 die;
2506 }
2507 if (long2ip (ip2long ($rsip)) !== $rsip)
2508 {
2509 showError ("Invalid IP address '${rsip}'", __FUNCTION__);
2510 die;
2511 }
79a9edb4
DO
2512 if (empty ($rsport) or $rsport == 0)
2513 $rsport = 'NULL';
fb1c4a54
DO
2514 global $dbxlink;
2515 $query =
2516 "update IPRealServer set rsip = inet_aton('${rsip}'), rsport = ${rsport}, rsconfig = " .
3241551e 2517 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
fb1c4a54
DO
2518 " where id = ${rsid} limit 1";
2519 $result = $dbxlink->query ($query);
2520 if ($result == NULL)
2521 {
2522 showError ("SQL query '${query}' failed", __FUNCTION__);
2523 die;
2524 }
2525 return TRUE;
2526}
2527
c1ca768c 2528function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2529{
c1ca768c 2530 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
3241551e
DO
2531 {
2532 showError ('Invalid args', __FUNCTION__);
2533 die;
2534 }
2535 global $dbxlink;
2536 $query =
2537 "update IPLoadBalancer set vsconfig = " .
2538 (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'") .
2539 ', rsconfig = ' .
2540 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
c1ca768c
DO
2541 " where object_id = ${object_id} and rspool_id = ${pool_id} " .
2542 "and vs_id = ${vs_id} limit 1";
3241551e
DO
2543 $result = $dbxlink->exec ($query);
2544 if ($result === NULL)
2545 return FALSE;
3241551e
DO
2546 else
2547 return TRUE;
2548}
2549
d6517a21
DO
2550function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2551{
2552 if ($vsid <= 0 or empty ($vip) or $vport <= 0 or empty ($proto))
2553 {
2554 showError ('Invalid args', __FUNCTION__);
2555 die;
2556 }
2557 global $dbxlink;
2558 $query = "update IPVirtualService set " .
2559 "vip = inet_aton('${vip}'), " .
2560 "vport = ${vport}, " .
2561 "proto = '${proto}', " .
2562 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2563 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
5ad76f01
DO
2564 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2565 " where id = ${vsid} limit 1";
d6517a21
DO
2566 $result = $dbxlink->exec ($query);
2567 if ($result === NULL)
2568 return FALSE;
d6517a21
DO
2569 else
2570 return TRUE;
2571}
2572
e57dca7f 2573// Return the list of virtual services, indexed by vs_id.
70c24883 2574// Each record will be shown with its basic info plus RS pools counter.
11c8e4be 2575function getVSList ($tagfilter = array(), $tfmode = 'any')
e57dca7f 2576{
81736ac1 2577 $whereclause = getWhereClause ($tagfilter);
70c24883
DO
2578 $query = "select vs.id, inet_ntoa(vip) as vip, vport, proto, vs.name, vs.vsconfig, vs.rsconfig, count(rspool_id) as poolcount " .
2579 "from IPVirtualService as vs left join IPLoadBalancer as lb on vs.id = lb.vs_id " .
996b02ba 2580 "left join TagStorage on vs.id = TagStorage.target_id and target_realm = 'ipv4vs' " .
83d3dde9 2581 "where true ${whereclause} group by vs.id order by vs.vip, proto, vport";
065eeb52 2582 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6 2583 $ret = array ();
e57dca7f 2584 while ($row = $result->fetch (PDO::FETCH_ASSOC))
d6517a21 2585 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig', 'poolcount') as $cname)
4b0932b6 2586 $ret[$row['id']][$cname] = $row[$cname];
e57dca7f 2587 $result->closeCursor();
4b0932b6 2588 return $ret;
e57dca7f
DO
2589}
2590
9a81d416 2591// Return the list of RS pool, indexed by pool id.
11c8e4be 2592function getRSPoolList ($tagfilter = array(), $tfmode = 'any')
9a81d416 2593{
81736ac1 2594 $whereclause = getWhereClause ($tagfilter);
70c24883
DO
2595 $query = "select pool.id, pool.name, count(rspool_id) as refcnt, pool.vsconfig, pool.rsconfig " .
2596 "from IPRSPool as pool left join IPLoadBalancer as lb on pool.id = lb.rspool_id " .
2e4170aa 2597 "left join TagStorage on pool.id = TagStorage.target_id and target_realm = 'ipv4rspool' " .
56c076ed 2598 "where true ${whereclause} group by pool.id order by pool.name, pool.id";
065eeb52 2599 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6 2600 $ret = array ();
9a81d416 2601 while ($row = $result->fetch (PDO::FETCH_ASSOC))
70c24883 2602 foreach (array ('name', 'refcnt', 'vsconfig', 'rsconfig') as $cname)
4b0932b6 2603 $ret[$row['id']][$cname] = $row[$cname];
9a81d416 2604 $result->closeCursor();
4b0932b6 2605 return $ret;
9a81d416
DO
2606}
2607
5a1680d2
DO
2608function loadThumbCache ($rack_id = 0)
2609{
5a1680d2
DO
2610 $ret = NULL;
2611 $query = "select thumb_data from Rack where id = ${rack_id} and thumb_data is not null limit 1";
065eeb52 2612 $result = useSelectBlade ($query, __FUNCTION__);
5a1680d2
DO
2613 $row = $result->fetch (PDO::FETCH_ASSOC);
2614 if ($row)
2615 $ret = base64_decode ($row['thumb_data']);
2616 $result->closeCursor();
2617 return $ret;
2618}
2619
2620function saveThumbCache ($rack_id = 0, $cache = NULL)
2621{
2622 global $dbxlink;
2623 if ($rack_id == 0 or $cache == NULL)
2624 {
2625 showError ('Invalid arguments', __FUNCTION__);
2626 return;
2627 }
2628 $data = base64_encode ($cache);
2629 $query = "update Rack set thumb_data = '${data}' where id = ${rack_id} limit 1";
2630 $result = $dbxlink->exec ($query);
2631}
9a81d416 2632
c7fe33be
DO
2633function resetThumbCache ($rack_id = 0)
2634{
2635 global $dbxlink;
2636 if ($rack_id == 0)
2637 {
2638 showError ('Invalid argument', __FUNCTION__);
2639 return;
2640 }
2641 $query = "update Rack set thumb_data = NULL where id = ${rack_id} limit 1";
2642 $result = $dbxlink->exec ($query);
2643}
2644
748805bf
DO
2645// Return the list of attached RS pools for the given object. As long as we have
2646// the LB-VS UNIQUE in IPLoadBalancer table, it is Ok to key returned records
2647// by vs_id, because there will be only one RS pool listed for each VS of the
2648// current object.
78e7b769
DO
2649function getRSPoolsForObject ($object_id = 0)
2650{
2651 if ($object_id <= 0)
2652 {
2653 showError ('Invalid object_id', __FUNCTION__);
2654 return NULL;
2655 }
748805bf 2656 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
732e4578 2657 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
748805bf
DO
2658 'IPLoadBalancer as lb inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2659 'inner join IPVirtualService as vs on lb.vs_id = vs.id ' .
2660 'left join IPRealServer as rs on lb.rspool_id = rs.rspool_id ' .
2661 "where lb.object_id = ${object_id} " .
2662 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name';
065eeb52 2663 $result = useSelectBlade ($query, __FUNCTION__);
748805bf 2664 $ret = array ();
78e7b769 2665 while ($row = $result->fetch (PDO::FETCH_ASSOC))
732e4578 2666 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
748805bf 2667 $ret[$row['vs_id']][$cname] = $row[$cname];
78e7b769 2668 $result->closeCursor();
748805bf 2669 return $ret;
78e7b769
DO
2670}
2671
c63a8d6e 2672function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
5ad76f01 2673{
c63a8d6e
DO
2674 if (empty ($name))
2675 return __FUNCTION__ . ': invalid arguments';
2676 if (!useInsertBlade
5ad76f01
DO
2677 (
2678 'IPRSPool',
2679 array
2680 (
5ad76f01
DO
2681 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2682 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2683 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2684 )
c63a8d6e
DO
2685 ))
2686 return __FUNCTION__ . ': SQL insertion failed';
351c0966 2687 return produceTagsForLastRecord ('ipv4rspool', $taglist);
5ad76f01
DO
2688}
2689
2690function commitDeleteRSPool ($pool_id = 0)
2691{
2692 global $dbxlink;
2693 if ($pool_id <= 0)
2694 return FALSE;
01b6b4d6 2695 return useDeleteBlade ('IPRSPool', 'id', $pool_id) && destroyTagsForEntity ('ipv4rspool', $pool_id);
5ad76f01
DO
2696}
2697
2698function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2699{
2700 if ($pool_id <= 0)
2701 {
2702 showError ('Invalid arg', __FUNCTION__);
2703 die;
2704 }
2705 global $dbxlink;
2706 $query = "update IPRSPool set " .
2707 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2708 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2709 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2710 " where id = ${pool_id} limit 1";
2711 $result = $dbxlink->exec ($query);
2712 if ($result === NULL)
2713 return FALSE;
2714 elseif ($result != 1)
2715 return FALSE;
2716 else
2717 return TRUE;
2718}
2719
8253d9f0
DO
2720function getRSList ()
2721{
1f7d18fa 2722 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
8253d9f0 2723 "from IPRealServer order by rspool_id, IPRealServer.rsip, rsport";
065eeb52 2724 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6 2725 $ret = array ();
8253d9f0 2726 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1f7d18fa 2727 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
4b0932b6
DO
2728 $ret[$row['id']][$cname] = $row[$cname];
2729 $result->closeCursor();
2730 return $ret;
2731}
2732
2733// Return the list of all currently configured load balancers with their pool count.
2734function getLBList ()
2735{
4b0932b6
DO
2736 $query = "select object_id, count(rspool_id) as poolcount " .
2737 "from IPLoadBalancer group by object_id order by object_id";
065eeb52 2738 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6
DO
2739 $ret = array ();
2740 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2741 $ret[$row['object_id']] = $row['poolcount'];
8253d9f0 2742 $result->closeCursor();
4b0932b6 2743 return $ret;
8253d9f0
DO
2744}
2745
9e677cbd
DO
2746// For the given object return: it vsconfig/rsconfig; the list of RS pools
2747// attached (each with vsconfig/rsconfig in turn), each with the list of
2748// virtual services terminating the pool. Each pool also lists all real
2749// servers with rsconfig.
2987fc1f 2750function getSLBConfig ($object_id)
9e677cbd
DO
2751{
2752 if ($object_id <= 0)
2753 {
2754 showError ('Invalid arg', __FUNCTION__);
2755 return NULL;
2756 }
9e677cbd 2757 $ret = array();
d91f08f3
DO
2758 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2759 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2760 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
9e677cbd 2761 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
d91f08f3
DO
2762 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
2763 'IPLoadBalancer as lb inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2764 'inner join IPVirtualService as vs on lb.vs_id = vs.id ' .
9e677cbd 2765 'inner join IPRealServer as rs on lb.rspool_id = rs.rspool_id ' .
1f7d18fa
DO
2766 "where lb.object_id = ${object_id} and rs.inservice = 'yes' " .
2767 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport";
065eeb52 2768 $result = useSelectBlade ($query, __FUNCTION__);
9e677cbd
DO
2769 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2770 {
d91f08f3
DO
2771 $vs_id = $row['vs_id'];
2772 if (!isset ($ret[$vs_id]))
2773 {
2774 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)
2775 $ret[$vs_id][$c] = $row[$c];
2776 $ret[$vs_id]['rslist'] = array();
2777 }
2778 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2779 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
9e677cbd
DO
2780 }
2781 $result->closeCursor();
2782 return $ret;
2783}
1f7d18fa
DO
2784
2785function commitSetInService ($rs_id = 0, $inservice = '')
2786{
2787 if ($rs_id <= 0 or empty ($inservice))
2788 {
2789 showError ('Invalid args', __FUNCTION__);
2790 return NULL;
2791 }
2792 global $dbxlink;
2793 $query = "update IPRealServer set inservice = '${inservice}' where id = ${rs_id} limit 1";
2794 $result = $dbxlink->exec ($query);
2795 if ($result === NULL)
2796 return FALSE;
2797 elseif ($result != 1)
2798 return FALSE;
2799 else
2800 return TRUE;
2801}
2802
ad0e4754
DO
2803function executeAutoPorts ($object_id = 0, $type_id = 0)
2804{
2805 if ($object_id == 0 or $type_id == 0)
2806 {
2807 showError ('Invalid arguments', __FUNCTION__);
2808 die;
2809 }
f3f0161f 2810 $ret = TRUE;
118e4c38 2811 foreach (getAutoPorts ($type_id) as $autoport)
f3f0161f
DO
2812 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2813 return $ret;
ad0e4754
DO
2814}
2815
6e49bd1f 2816// Return only implicitly listed tags, the rest of the chain will be
a6e8d544 2817// generated/deducted later at higher levels.
aab37bc0 2818// Result is a chain: randomly indexed taginfo list.
f9bc186f 2819function loadEntityTags ($entity_realm = '', $entity_id = 0)
5967b83d 2820{
f9bc186f
DO
2821 if ($entity_realm == '' or $entity_id <= 0)
2822 {
2823 showError ('Invalid or missing arguments', __FUNCTION__);
2824 return NULL;
2825 }
a6e8d544 2826 $ret = array();
edf0993c
DO
2827 $query = "select tt.id, tag from " .
2828 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
2829 "where target_realm = '${entity_realm}' and target_id = ${entity_id} " .
2830 "order by tt.tag";
2831 $result = useSelectBlade ($query, __FUNCTION__);
5967b83d 2832 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2fb24351 2833 $ret[$row['id']] = $row;
a6e8d544 2834 $result->closeCursor();
aab37bc0 2835 return getExplicitTagsOnly ($ret);
5967b83d
DO
2836}
2837
e1ae3fb4
AD
2838function loadFileTags ($id)
2839{
2840 return loadEntityTags ('file', $id);
2841}
2842
f9bc186f
DO
2843function loadRackObjectTags ($id)
2844{
2845 return loadEntityTags ('object', $id);
2846}
2847
2848function loadIPv4PrefixTags ($id)
2849{
2850 return loadEntityTags ('ipv4net', $id);
2851}
2852
41bd8c87
DO
2853function loadRackTags ($id)
2854{
2855 return loadEntityTags ('rack', $id);
2856}
2857
d817ba03
DO
2858function loadIPv4VSTags ($id)
2859{
2860 return loadEntityTags ('ipv4vs', $id);
2861}
2862
2863function loadIPv4RSPoolTags ($id)
2864{
2865 return loadEntityTags ('ipv4rspool', $id);
2866}
2867
ebae41b3
DO
2868function loadUserTags ($user_id)
2869{
2870 return loadEntityTags ('user', $user_id);
2871}
2872
351c0966 2873// Return a tag chain with all DB tags on it.
5967b83d
DO
2874function getTagList ()
2875{
20c901a7 2876 $ret = array();
5b7bd02e
DO
2877 $query = "select id, parent_id, tag, target_realm as realm, count(target_id) as refcnt " .
2878 "from TagTree left join TagStorage on id = tag_id " .
2879 "group by id, target_realm order by tag";
065eeb52 2880 $result = useSelectBlade ($query, __FUNCTION__);
fb7a4967
DO
2881 $ci = 0; // Collation index. The resulting rows are ordered according to default collation,
2882 // which is utf8_general_ci for UTF-8.
5967b83d 2883 while ($row = $result->fetch (PDO::FETCH_ASSOC))
5b7bd02e 2884 {
7cc02fc1 2885 if (!isset ($ret[$row['id']]))
20c901a7 2886 $ret[$row['id']] = array
5b7bd02e
DO
2887 (
2888 'id' => $row['id'],
2889 'tag' => $row['tag'],
fb7a4967 2890 'ci' => $ci++,
5b7bd02e
DO
2891 'parent_id' => $row['parent_id'],
2892 'refcnt' => array()
2893 );
2894 if ($row['realm'])
20c901a7 2895 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
5b7bd02e 2896 }
5967b83d 2897 $result->closeCursor();
20c901a7 2898 return $ret;
5967b83d
DO
2899}
2900
fe7044ad
DO
2901function commitCreateTag ($tagname = '', $parent_id = 0)
2902{
2903 if ($tagname == '' or $parent_id === 0)
2904 return "Invalid args to " . __FUNCTION__;
2905 $result = useInsertBlade
2906 (
2907 'TagTree',
2908 array
2909 (
2910 'tag' => "'${tagname}'",
2911 'parent_id' => $parent_id
2912 )
2913 );
2914 if ($result)
2915 return '';
2916 else
2917 return "SQL query failed in " . __FUNCTION__;
2918}
2919
2920function commitDestroyTag ($tagid = 0)
2921{
2922 if ($tagid == 0)
2923 return 'Invalid arg to ' . __FUNCTION__;
f5575f12 2924 if (useDeleteBlade ('TagTree', 'id', $tagid))
fe7044ad
DO
2925 return '';
2926 else
2927 return 'useDeleteBlade() failed in ' . __FUNCTION__;
2928}
f9bc186f 2929
49fb1027 2930function commitUpdateTag ($tag_id, $tag_name, $parent_id)
f9bc186f 2931{
49fb1027
DO
2932 if ($parent_id == 0)
2933 $parent_id = 'NULL';
f9bc186f 2934 global $dbxlink;
49fb1027
DO
2935 $query = "update TagTree set tag = '${tag_name}', parent_id = ${parent_id} " .
2936 "where id = ${tag_id} limit 1";
f9bc186f
DO
2937 $result = $dbxlink->exec ($query);
2938 if ($result === NULL)
49fb1027
DO
2939 return 'SQL query failed in ' . __FUNCTION__;
2940 return '';
f9bc186f
DO
2941}
2942
01b6b4d6
DO
2943// Drop the whole chain stored.
2944function destroyTagsForEntity ($entity_realm, $entity_id)
aedf18af
DO
2945{
2946 global $dbxlink;
2947 $query = "delete from TagStorage where target_realm = '${entity_realm}' and target_id = ${entity_id}";
2948 $result = $dbxlink->exec ($query);
2949 if ($result === NULL)
2950 return FALSE;
2951 else
2952 return TRUE;
2953}
2954
01b6b4d6
DO
2955// Drop only one record. This operation doesn't involve retossing other tags, unlike when adding.
2956function deleteTagForEntity ($entity_realm, $entity_id, $tag_id)
2957{
2958 global $dbxlink;
2959 $query = "delete from TagStorage where target_realm = '${entity_realm}' and target_id = ${entity_id} and tag_id = ${tag_id}";
2960 $result = $dbxlink->exec ($query);
2961 if ($result === NULL)
2962 return FALSE;
2963 else
2964 return TRUE;
2965}
2966
351c0966 2967// Push a record into TagStorage unconditionally.
3355ca56 2968function addTagForEntity ($realm = '', $entity_id, $tag_id)
eb6ea26f 2969{
3355ca56
DO
2970 if (empty ($realm))
2971 return FALSE;
eb6ea26f
DO
2972 return useInsertBlade
2973 (
2974 'TagStorage',
2975 array
2976 (
2977 'target_realm' => "'${realm}'",
2978 'target_id' => $entity_id,
2979 'tag_id' => $tag_id,
2980 )
2981 );
2982}
2983
351c0966 2984// Add records into TagStorage, if this makes sense (IOW, they don't appear
abef7149
DO
2985// on the implicit list already). Then remove any other records, which
2986// appear on the "implicit" side of the chain. This will make sure,
351c0966
DO
2987// that both the tag base is still minimal and all requested tags appear on
2988// the resulting tag chain.
abef7149
DO
2989// Return TRUE, if any changes were committed.
2990function rebuildTagChainForEntity ($realm, $entity_id, $extrachain = array())
2991{
2992 // Put the current explicit sub-chain into a buffer and merge all tags from
2993 // the extra chain, which aren't there yet.
2994 $newchain = $oldchain = loadEntityTags ($realm, $entity_id);
2995 foreach ($extrachain as $extratag)
2996 if (!tagOnChain ($extratag, $newchain))
2997 $newchain[] = $extratag;
2998 // Then minimize the working buffer and check if it differs from the original
2999 // chain we started with. If it is so, save the work and signal the upper layer.
3000 $newchain = getExplicitTagsOnly ($newchain);
3001 if (tagChainCmp ($oldchain, $newchain))
3002 {
01b6b4d6 3003 destroyTagsForEntity ($realm, $entity_id);
abef7149
DO
3004 foreach ($newchain as $taginfo)
3005 addTagForEntity ($realm, $entity_id, $taginfo['id']);
3006 return TRUE;
3007 }
3008 return FALSE;
351c0966
DO
3009}
3010
3011// Presume, that the target record has no tags attached.
3012function produceTagsForLastRecord ($realm, $tagidlist, $last_insert_id = 0)
3013{
3014 if (!count ($tagidlist))
c63a8d6e
DO
3015 return '';
3016 if (!$last_insert_id)
3017 $last_insert_id = lastInsertID();
3018 $errcount = 0;
abef7149 3019 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagidlist)) as $taginfo)
cdb7e75d 3020 if (addTagForEntity ($realm, $last_insert_id, $taginfo['id']) == FALSE)
c63a8d6e
DO
3021 $errcount++;
3022 if (!$errcount)
3023 return '';
3024 else
3025 return "Experienced ${errcount} errors adding tags in realm '${realm}' for entity ID == ${last_insert_id}";
3026}
3027
42023f03
DO
3028function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
3029{
3030 // $range is in x.x.x.x/x format, split into ip/mask vars
3031 $rangeArray = explode('/', $range);
3032 if (count ($rangeArray) != 2)
3033 return "Invalid IPv4 prefix '${range}'";
3034 $ip = $rangeArray[0];
3035 $mask = $rangeArray[1];
3036
3037 if (empty ($ip) or empty ($mask))
3038 return "Invalid IPv4 prefix '${range}'";
3039 $ipL = ip2long($ip);
3040 $maskL = ip2long($mask);
3041 if ($ipL == -1 || $ipL === FALSE)
3042 return 'Bad IPv4 address';
3043 if ($mask < 32 && $mask > 0)
3044 $maskL = $mask;
3045 else
3046 {
3047 $maskB = decbin($maskL);
3048 if (strlen($maskB)!=32)
3049 return 'Invalid netmask';
3050 $ones=0;
3051 $zeroes=FALSE;
3052 foreach( str_split ($maskB) as $digit)
3053 {
3054 if ($digit == '0')
3055 $zeroes = TRUE;
3056 if ($digit == '1')
3057 {
3058 $ones++;
3059 if ($zeroes == TRUE)
3060 return 'Invalid netmask';
3061 }
3062 }
3063 $maskL = $ones;
3064 }
3065 $binmask = binMaskFromDec($maskL);
3066 $ipL = $ipL & $binmask;
42023f03
DO
3067 $result = useInsertBlade
3068 (
3069 'IPRanges',
3070 array
3071 (
3072 'ip' => sprintf ('%u', $ipL),
3073 'mask' => "'${maskL}'",
3074 'name' => "'${name}'"
3075 )
3076 );
3077
3078 if ($is_bcast and $maskL < 31)
3079 {
3080 $network_addr = long2ip ($ipL);
3081 $broadcast_addr = long2ip ($ipL | binInvMaskFromDec ($maskL));
3082 updateAddress ($network_addr, 'network', 'yes');
3083 updateAddress ($broadcast_addr, 'broadcast', 'yes');
3084 }
351c0966 3085 return produceTagsForLastRecord ('ipv4net', $taglist);
42023f03
DO
3086}
3087
3088// FIXME: This function doesn't wipe relevant records from IPAddress table.
3089function destroyIPv4Prefix ($id = 0)
3090{
3091 if ($id <= 0)
3092 return __FUNCTION__ . ': Invalid IPv4 prefix ID';
f5575f12 3093 if (!useDeleteBlade ('IPRanges', 'id', $id))
42023f03 3094 return __FUNCTION__ . ': SQL query #1 failed';
01b6b4d6 3095 if (!destroyTagsForEntity ('ipv4net', $id))
42023f03
DO
3096 return __FUNCTION__ . ': SQL query #2 failed';
3097 return '';
3098}
3099
ebae41b3
DO
3100function loadScript ($name)
3101{
3102 $result = useSelectBlade ("select script_text from Script where script_name = '${name}'");
3103 $row = $result->fetch (PDO::FETCH_NUM);
4a6a28f1
DO
3104 if ($row !== FALSE)
3105 return $row[0];
3106 else
3107 return NULL;
ebae41b3
DO
3108}
3109
3110function saveScript ($name, $text)
3111{
3112 if (empty ($name))
3113 {
3114 showError ('Invalid argument');
3115 return FALSE;
3116 }
4a6a28f1 3117 // delete regardless of existence
f5575f12 3118 useDeleteBlade ('Script', 'script_name', "'${name}'");
4a6a28f1 3119 return useInsertBlade
ebae41b3
DO
3120 (
3121 'Script',
3122 array
3123 (
3124 'script_name' => "'${name}'",
3125 'script_text' => "'${text}'"
3126 )
3127 );
3128}
3129
3130function saveUserPassword ($user_id, $newp)
bcd37231 3131{
ebae41b3
DO
3132 $newhash = hash (PASSWORD_HASH, $newp);
3133 $query = "update UserAccount set user_password_hash = ${newhash} where user_id = ${user_id} limit 1";
bcd37231
DO
3134}
3135
cf6c472b
DO
3136function objectIsPortless ($id = 0)
3137{
3138 if ($id <= 0)
3139 {
3140 showError ('Invalid argument', __FUNCTION__);
3141 return;
3142 }
3143 if (($result = useSelectBlade ("select count(id) from Port where object_id = ${id}", __FUNCTION__)) == NULL)
3144 {
3145 showError ('SQL query failed', __FUNCTION__);
3146 return;
3147 }
3148 $row = $result->fetch (PDO::FETCH_NUM);
3149 $count = $row[0];
3150 $result->closeCursor();
3151 unset ($result);
81736ac1 3152 return $count === '0';
cf6c472b
DO
3153}
3154
15555995
DO
3155function recordExists ($id = 0, $realm = 'object')
3156{
3157 if ($id <= 0)
3158 return FALSE;
3159 $table = array
3160 (
3161 'object' => 'RackObject',
1a315491
DO
3162 'ipv4net' => 'IPRanges',
3163 'user' => 'UserAccount',
15555995
DO
3164 );
3165 $idcol = array
3166 (
3167 'object' => 'id',
1a315491
DO
3168 'ipv4net' => 'id',
3169 'user' => 'user_id',
15555995
DO
3170 );
3171 $query = 'select count(*) from ' . $table[$realm] . ' where ' . $idcol[$realm] . ' = ' . $id;
3172 if (($result = useSelectBlade ($query, __FUNCTION__)) == NULL)
3173 {
3174 showError ('SQL query failed', __FUNCTION__);
3175 return FALSE;
3176 }
3177 $row = $result->fetch (PDO::FETCH_NUM);
3178 $count = $row[0];
3179 $result->closeCursor();
3180 unset ($result);
3181 return $count === '1';
3182}
3183
0f3c6639
DO
3184function tagExistsInDatabase ($tname)
3185{
3186 $result = useSelectBlade ("select count(*) from TagTree where lower(tag) = lower('${tname}')");
3187 $row = $result->fetch (PDO::FETCH_NUM);
3188 $count = $row[0];
3189 $result->closeCursor();
3190 unset ($result);
3191 return $count !== '0';
3192}
3193
d983f70a
DO
3194function newPortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3195{
3196 if (NULL === getIPv4AddressNetworkId ($localip))
3197 return "$localip: Non existant ip";
3198 if (NULL === getIPv4AddressNetworkId ($localip))
3199 return "$remoteip: Non existant ip";
3200 if ( ($localport <= 0) or ($localport >= 65536) )
3201 return "$localport: invaild port";
3202 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
3203 return "$remoteport: invaild port";
3204
3205 $result = useInsertBlade
3206 (
3207 'PortForwarding',
3208 array
3209 (
3210 'object_id' => $object_id,
3211 'localip' => "INET_ATON('${localip}')",
3212 'remoteip' => "INET_ATON('$remoteip')",
3213 'localport' => $localport,
3214 'remoteport' => $remoteport,
3215 'proto' => "'${proto}'",
3216 'description' => "'${description}'",
3217 )
3218 );
3219 if ($result)
3220 return '';
3221 else
3222 return __FUNCTION__ . ': Failed to insert the rule.';
3223}
3224
3225function deletePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
3226{
3227 global $dbxlink;
3228
3229 $query =
3230 "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'";
3231 $result = $dbxlink->exec ($query);
3232 return '';
3233}
3234
3235function updatePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3236{
3237 global $dbxlink;
3238
3239 $query =
3240 "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'";
3241 $result = $dbxlink->exec ($query);
3242 return '';
3243}
3244
3245function getNATv4ForObject ($object_id)
3246{
3247 $ret = array();
3248 $ret['out'] = array();
3249 $ret['in'] = array();
3250 $query =
3251 "select ".
3252 "proto, ".
3253 "INET_NTOA(localip) as localip, ".
3254 "localport, ".
3255 "INET_NTOA(remoteip) as remoteip, ".
3256 "remoteport, ".
3257 "ipa1.name as local_addr_name, " .
3258 "ipa2.name as remote_addr_name, " .
3259 "description ".
3260 "from PortForwarding ".
3261 "left join IPAddress as ipa1 on PortForwarding.localip = ipa1.ip " .
3262 "left join IPAddress as ipa2 on PortForwarding.remoteip = ipa2.ip " .
3263 "where object_id='$object_id' ".
3264 "order by localip, localport, proto, remoteip, remoteport";
3265 $result = useSelectBlade ($query, __FUNCTION__);
3266 $count=0;
3267 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3268 {
3269 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
3270 $ret['out'][$count][$cname] = $row[$cname];
3271 $count++;
3272 }
3273 $result->closeCursor();
3274 unset ($result);
3275
3276 $query =
3277 "select ".
3278 "proto, ".
3279 "INET_NTOA(localip) as localip, ".
3280 "localport, ".
3281 "INET_NTOA(remoteip) as remoteip, ".
3282 "remoteport, ".
3283 "PortForwarding.object_id as object_id, ".
3284 "RackObject.name as object_name, ".
3285 "description ".
3286 "from ((PortForwarding join IPBonds on remoteip=IPBonds.ip) join RackObject on PortForwarding.object_id=RackObject.id) ".
3287 "where IPBonds.object_id='$object_id' ".
3288 "order by remoteip, remoteport, proto, localip, localport";
3289 $result = useSelectBlade ($query, __FUNCTION__);
3290 $count=0;
3291 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3292 {
3293 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
3294 $ret['in'][$count][$cname] = $row[$cname];
3295 $count++;
3296 }
3297 $result->closeCursor();
3298
3299 return $ret;
3300}
3301
3302// This function performs search and then calculates score for each result.
3303// Given previous search results in $objects argument, it adds new results
3304// to the array and updates score for existing results, if it is greater than
3305// existing score.
3306function mergeSearchResults (&$objects, $terms, $fieldname)
3307{
3308 global $dbxlink;
3309 $query =
3310 "select name, label, asset_no, barcode, ro.id, dict_key as objtype_id, " .
3311 "dict_value as objtype_name, asset_no from RackObject as ro inner join Dictionary " .
3312 "on objtype_id = dict_key natural join Chapter where chapter_name = 'RackObjectType' and ";
3313 $count = 0;
3314 foreach (explode (' ', $terms) as $term)
3315 {
3316 if ($count) $query .= ' or ';
3317 $query .= "${fieldname} like '%$term%'";
3318 $count++;
3319 }
3320 $query .= " order by ${fieldname}";
3321 $result = useSelectBlade ($query, __FUNCTION__);
3322// FIXME: this dead call was executed 4 times per 1 object search!
3323// $typeList = getObjectTypeList();
3324 $clist = array ('id', 'name', 'label', 'asset_no', 'barcode', 'objtype_id', 'objtype_name');
3325 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3326 {
3327 foreach ($clist as $cname)
3328 $object[$cname] = $row[$cname];
3329 $object['score'] = 0;
3330 $object['dname'] = displayedName ($object);
3331 unset ($object['objtype_id']);
3332 foreach (explode (' ', $terms) as $term)
3333 if (strstr ($object['name'], $term))
3334 $object['score'] += 1;
3335 unset ($object['name']);
3336 if (!isset ($objects[$row['id']]))
3337 $objects[$row['id']] = $object;
3338 elseif ($objects[$row['id']]['score'] < $object['score'])
3339 $objects[$row['id']]['score'] = $object['score'];
3340 }
3341 return $objects;
3342}
3343
09620506
DO
3344function getLostIPv4Addresses ()
3345{
f7414fa5 3346 dragon();
09620506
DO
3347}
3348
e1ae3fb4
AD
3349// File-related functions
3350function getAllFiles ()
3351{
3352 $query = "SELECT id, name, type, size, ctime, mtime, atime, comment FROM File ORDER BY name";
3353 $result = useSelectBlade ($query, __FUNCTION__);
3354 $ret=array();
3355 $count=0;
3356 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3357 {
3358 $ret[$count]['id'] = $row['id'];
3359 $ret[$count]['name'] = $row['name'];
3360 $ret[$count]['type'] = $row['type'];
3361 $ret[$count]['size'] = $row['size'];
3362 $ret[$count]['ctime'] = $row['ctime'];
3363 $ret[$count]['mtime'] = $row['mtime'];
3364 $ret[$count]['atime'] = $row['atime'];
3365 $ret[$count]['comment'] = $row['comment'];
3366 $count++;
3367 }
3368 $result->closeCursor();
3369 return $ret;
3370}
3371
3372// Return a list of files which are not linked to the specified record
3373function getAllUnlinkedFiles ($entity_type = NULL, $entity_id = 0)
3374{
3375 if ($entity_type == NULL || $entity_id == 0)
3376 {
3377 showError ('Invalid parameters', __FUNCTION__);
3378 return NULL;
3379 }
3380 global $dbxlink;
3381 $sql =
3382 'SELECT id, name, type, size, ctime, mtime, atime, comment FROM File ' .
3383 'WHERE id NOT IN (SELECT file_id FROM FileLink WHERE entity_type = ? AND entity_id = ?) ' .
3384 'ORDER BY name';
3385 $query = $dbxlink->prepare($sql);
3386 $query->bindParam(1, $entity_type);
3387 $query->bindParam(2, $entity_id);
3388 $query->execute();
3389 $ret=array();
3390 $count=0;
3391 while ($row = $query->fetch (PDO::FETCH_ASSOC))
3392 {
3393 $ret[$count]['id'] = $row['id'];
3394 $ret[$count]['name'] = $row['name'];
3395 $ret[$count]['type'] = $row['type'];
3396 $ret[$count]['size'] = $row['size'];
3397 $ret[$count]['ctime'] = $row['ctime'];
3398 $ret[$count]['mtime'] = $row['mtime'];
3399 $ret[$count]['atime'] = $row['atime'];
3400 $ret[$count]['comment'] = $row['comment'];
3401 $count++;
3402 }
3403 return $ret;
3404}
3405
3406// Return a filtered, detailed file list. Used on the main Files listing page.
3407function getFileList ($entity_type = NULL, $tagfilter = array(), $tfmode = 'any')
3408{
3409 $whereclause = getWhereClause ($tagfilter);
3410
3411 if ($entity_type == 'no_links')
3412 $whereclause .= 'AND File.id NOT IN (SELECT file_id FROM FileLink) ';
3413 elseif ($entity_type != 'all')
3414 $whereclause .= "AND entity_type = '${entity_type}' ";
3415
3416 $query =
3417 'SELECT File.id, name, type, size, ctime, mtime, atime, comment ' .
3418 'FROM File ' .
3419 'LEFT JOIN FileLink ' .
3420 'ON File.id = FileLink.file_id ' .
3421 'LEFT JOIN TagStorage ' .
3422 "ON File.id = TagStorage.target_id AND target_realm = 'file' " .
3423 'WHERE size >= 0 ' .
3424 $whereclause .
3425 'ORDER BY name';
3426
3427 $result = useSelectBlade ($query, __FUNCTION__);
3428 $ret = array();
3429 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3430 {
3431 foreach (array (
3432 'id',
3433 'name',
3434 'type',
3435 'size',
3436 'ctime',
3437 'mtime',
3438 'atime',
3439 'comment'
3440 ) as $cname)
3441 $ret[$row['id']][$cname] = $row[$cname];
3442 }
3443 $result->closeCursor();
3444 return $ret;
3445}
3446
3447function getFilesOfEntity ($entity_type = NULL, $entity_id = 0)
3448{
3449 if ($entity_type == NULL || $entity_id == 0)
3450 {
3451 showError ('Invalid parameters', __FUNCTION__);
3452 return NULL;
3453 }
3454 global $dbxlink;
3455 $sql =
3456 'SELECT FileLink.file_id, FileLink.id AS link_id, name, type, size, ctime, mtime, atime, comment ' .
3457 'FROM FileLink LEFT JOIN File ON FileLink.file_id = File.id ' .
3458 'WHERE FileLink.entity_type = ? AND FileLink.entity_id = ? ORDER BY name';
3459 $query = $dbxlink->prepare($sql);
3460 $query->bindParam(1, $entity_type);
3461 $query->bindParam(2, $entity_id);
3462 $query->execute();
3463 $ret = array();
3464 while ($row = $query->fetch (PDO::FETCH_ASSOC))
3465 $ret[$row['file_id']] = array (
3466 'link_id' => $row['link_id'],
3467 'name' => $row['name'],
3468 'type' => $row['type'],
3469 'size' => $row['size'],
3470 'ctime' => $row['ctime'],
3471 'mtime' => $row['mtime'],
3472 'atime' => $row['atime'],
3473 'comment' => $row['comment'],
3474 );
3475 return $ret;
3476}
3477
3478function getFile ($file_id = 0)
3479{
3480 if ($file_id == 0)
3481 {
3482 showError ('Invalid file_id', __FUNCTION__);
3483 return NULL;
3484 }
3485 global $dbxlink;
3486 $query = $dbxlink->prepare('SELECT * FROM File WHERE id = ?');
3487 $query->bindParam(1, $file_id);
3488 $query->execute();
3489 if (($row = $query->fetch (PDO::FETCH_ASSOC)) == NULL)
3490 {
3491 showError ('Query succeeded, but returned no data', __FUNCTION__);
3492 $ret = NULL;
3493 }
3494 else
3495 {
3496 $ret = array();
3497 $ret['id'] = $row['id'];
3498 $ret['name'] = $row['name'];
3499 $ret['type'] = $row['type'];
3500 $ret['size'] = $row['size'];
3501 $ret['ctime'] = $row['ctime'];
3502 $ret['mtime'] = $row['mtime'];
3503 $ret['atime'] = $row['atime'];
3504 $ret['contents'] = $row['contents'];
3505 $ret['comment'] = $row['comment'];
3506
3507 // Someone accessed this file,date('YmdHis'); update atime
3508 $q_atime = $dbxlink->prepare('UPDATE File SET atime = ? WHERE id = ?');
3509 $q_atime->bindParam(1, date('YmdHis'));
3510 $q_atime->bindParam(2, $file_id);
3511 $q_atime->execute();
3512 }
3513 unset ($query);
3514 return $ret;
3515}
3516
3517function getFileInfo ($file_id = 0)
3518{
3519 if ($file_id == 0)
3520 {
3521 showError ('Invalid file_id', __FUNCTION__);
3522 return NULL;
3523 }
3524 global $dbxlink;
3525 $query = $dbxlink->prepare('SELECT id, name, type, size, ctime, mtime, atime, comment FROM File WHERE id = ?');
3526 $query->bindParam(1, $file_id);
3527 $query->execute();
3528 if (($row = $query->fetch (PDO::FETCH_ASSOC)) == NULL)
3529 {
3530 showError ('Query succeeded, but returned no data', __FUNCTION__);
3531 $ret = NULL;
3532 }
3533 else
3534 {
3535 $ret = array();
3536 $ret['id'] = $row['id'];
3537 $ret['name'] = $row['name'];
3538 $ret['type'] = $row['type'];
3539 $ret['size'] = $row['size'];
3540 $ret['ctime'] = $row['ctime'];
3541 $ret['mtime'] = $row['mtime'];
3542 $ret['atime'] = $row['atime'];
3543 $ret['comment'] = $row['comment'];
3544 }
3545 unset ($query);
3546 return $ret;
3547}
3548
3549function getFileLinks ($file_id = 0)
3550{
3551 if ($file_id <= 0)
3552 {
3553 showError ('Invalid file_id', __FUNCTION__);
3554 return NULL;
3555 }
3556
3557 global $dbxlink;
3558 $query = $dbxlink->prepare('SELECT * FROM FileLink WHERE file_id = ?');
3559 $query->bindParam(1, $file_id);
3560 $query->execute();
3561 $ret = array();
3562 while ($row = $query->fetch (PDO::FETCH_ASSOC))
3563 {
3564 // get info of the parent
3565 switch ($row['entity_type'])
3566 {
3567 case 'ipv4net':
3568 $page = 'ipv4net';
3569 $id_name = 'id';
3570 $parent = getIPv4NetworkInfo($row['entity_id']);
3571 $name = sprintf("%s (%s/%s)", $parent['name'], $parent['ip'], $parent['mask']);
3572 break;
3573 case 'ipv4rspool':
3854af78 3574 $page = 'ipv4rspool';
e1ae3fb4
AD
3575 $id_name = 'pool_id';
3576 $parent = getRSPoolInfo($row['entity_id']);
3577 $name = $parent['name'];
3578 break;
3579 case 'ipv4vs':
3580 $page = 'ipv4vs';
3581 $id_name = 'vs_id';
3582 $parent = getVServiceInfo($row['entity_id']);
3583 $name = $parent['name'];
3584 break;
3585 case 'object':
3586 $page = 'object';
3587 $id_name = 'object_id';
3588 $parent = getObjectInfo($row['entity_id']);
3589 $name = $parent['name'];
3590 break;
3591 case 'rack':
3592 $page = 'rack';
3593 $id_name = 'rack_id';
3594 $parent = getRackData($row['entity_id']);
3595 $name = $parent['name'];
3596 break;
3597 case 'user':
3598 $page = 'user';
3599 $id_name = 'user_id';
3600 global $accounts;
3601 foreach ($accounts as $account)
3602 if ($account['user_id'] == $row['entity_id'])
3603 $name = $account['user_name'];
3604 break;
3605 }
3606
3607 $ret[$row['id']] = array(
3608 'page' => $page,
3609 'id_name' => $id_name,
3610 'entity_type' => $row['entity_type'],
3611 'entity_id' => $row['entity_id'],
3612 'name' => $name
3613 );
3614 }
3615 return $ret;
3616}
3617
3618// Return list of possible file parents along with the number of children.
3619// Used on main Files listing page.
3620function getFileLinkInfo ()
3621{
3622 global $dbxlink;
3623 $query = 'SELECT entity_type, COUNT(*) AS count FROM FileLink GROUP BY entity_type';
3624
3625 $result = useSelectBlade ($query, __FUNCTION__);
3626 $ret = array();
3627 $ret[0] = array ('entity_type' => 'all', 'name' => 'ALL files');
3628 $clist = array ('entity_type', 'name', 'count');
3629 $total = 0;
3630 $i=2;
3631 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3632 if ($row['count'] > 0)
3633 {
3634 $total += $row['count'];
3635 $row['name'] = formatEntityName ($row['entity_type']);
3636 foreach ($clist as $cname)
3637 $ret[$i][$cname] = $row[$cname];
3638 $i++;
3639 }
3640 $result->closeCursor();
3641
3642 // Find number of files without any linkage
3643 $linkless_sql =
3644 'SELECT COUNT(*) ' .
3645 'FROM File ' .
3646 'WHERE id NOT IN (SELECT file_id FROM FileLink)';
3647 $q_linkless = useSelectBlade ($linkless_sql, __FUNCTION__);
3648 $ret[1] = array ('entity_type' => 'no_links', 'name' => 'Files w/no links', 'count' => $q_linkless->fetchColumn ());
3649 $q_linkless->closeCursor();
3650
3651 // Find total number of files
3652 $total_sql = 'SELECT COUNT(*) FROM File';
3653 $q_total = useSelectBlade ($total_sql, __FUNCTION__);
3654 $ret[0]['count'] = $q_total->fetchColumn ();
3655 $q_total->closeCursor();
3656
3657 ksort($ret);
3658 return $ret;
3659}
3660
3661function commitAddFile ($name, $type, $size, $contents, $comment)
3662{
3663 $now = date('YmdHis');
3664
3665 global $dbxlink;
3666 $query = $dbxlink->prepare('INSERT INTO File (name, type, size, ctime, mtime, atime, contents, comment) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
3667 $query->bindParam(1, $name);
3668 $query->bindParam(2, $type);
3669 $query->bindParam(3, $size);
3670 $query->bindParam(4, $now);
3671 $query->bindParam(5, $now);
3672 $query->bindParam(6, $now);
3673 $query->bindParam(7, $contents, PDO::PARAM_LOB);
3674 $query->bindParam(8, $comment);
3675
3676 $result = $query->execute();
3677
3678
3679 if ($result)
3680 return '';
3681 else
3682 return 'commitAddFile: SQL query failed';
3683}
3684
3685function commitLinkFile ($file_id, $parent_type, $parent_id)
3686{
3687 global $dbxlink;
3688 $query = $dbxlink->prepare('INSERT INTO FileLink (file_id, entity_type, entity_id) VALUES (?, ?, ?)');
3689 $query->bindParam(1, $file_id);
3690 $query->bindParam(2, $parent_type);
3691 $query->bindParam(3, $parent_id);
3692
3693 $result = $query->execute();
3694
3695 if ($result)
3696 return '';
3697 else
3698 return 'commitLinkFile: SQL query failed';
3699}
3700
3701function commitUpdateFile ($file_id = 0, $new_comment = '')
3702{
3703 if ($file_id == 0)
3704 {
3705 showError ('Not all required args are present.', __FUNCTION__);
3706 return FALSE;
3707 }
3708 global $dbxlink;
3709 $query = $dbxlink->prepare('UPDATE File SET comment = ? WHERE id = ?');
3710 $query->bindParam(1, $new_comment);
3711 $query->bindParam(2, $file_id);
3712
3713 $result = $query->execute();
3714 if (!$result)
3715 {
3716 showError ('commitUpdateFile: SQL query failed', __FUNCTION__);
3717 return FALSE;
3718 }
3719 return '';
3720}
3721
3722function commitUnlinkFile ($link_id)
3723{
3724 if (useDeleteBlade ('FileLink', 'id', $link_id) != TRUE)
3725 return __FUNCTION__ . ': useDeleteBlade() failed';
3726 return '';
3727}
3728
3729function commitDeleteFile ($file_id)
3730{
3731 if (useDeleteBlade ('File', 'id', $file_id) != TRUE)
3732 return __FUNCTION__ . ': useDeleteBlade() failed';
3733 return '';
3734}
3735
e673ee24 3736?>