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