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