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