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