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