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