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