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