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