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