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