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