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