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