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