r2709 - adjust context to the current navigation and split it for two helpers
[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 " .
aa9a0fb4 128 "where Chapter.name = 'RackObjectType' " .
c6bc0ac5
DO
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 " .
aa9a0fb4 355 "where Rack.id='${rack_id}'";
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 " .
aa9a0fb4 410 "where RackObject.id = '${object_id}' and Chapter.name = 'RackObjectType'";
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.
c4d0dc30
DO
1640// FIXME: there's a lot of excess legacy code in this function, it's reasonable
1641// to merge it with readChapter().
2dd59b15 1642function getDict ($parse_links = FALSE)
e673ee24 1643{
6bb8e41d 1644 $query1 =
10bac82a 1645 "select Chapter.name as chapter_name, Chapter.id as chapter_no, dict_key, dict_value, sticky from " .
6530f34e 1646 "Chapter left join Dictionary on Chapter.id = Dictionary.chapter_id order by Chapter.name, dict_value";
065eeb52 1647 $result = useSelectBlade ($query1, __FUNCTION__);
e673ee24 1648 $dict = array();
89fa639f 1649 while ($row = $result->fetch (PDO::FETCH_ASSOC))
e673ee24
DO
1650 {
1651 $chapter_no = $row['chapter_no'];
1652 if (!isset ($dict[$chapter_no]))
1653 {
1654 $dict[$chapter_no]['no'] = $chapter_no;
1655 $dict[$chapter_no]['name'] = $row['chapter_name'];
1656 $dict[$chapter_no]['sticky'] = $row['sticky'] == 'yes' ? TRUE : FALSE;
1657 $dict[$chapter_no]['word'] = array();
1658 }
1659 if ($row['dict_key'] != NULL)
6bb8e41d 1660 {
c2e29d4f 1661 $dict[$chapter_no]['word'][$row['dict_key']] = ($parse_links or $row['dict_key'] <= MAX_DICT_KEY) ?
2dd59b15 1662 parseWikiLink ($row['dict_value'], 'a') : $row['dict_value'];
6bb8e41d
DO
1663 $dict[$chapter_no]['refcnt'][$row['dict_key']] = 0;
1664 }
e673ee24 1665 }
89fa639f
DO
1666 $result->closeCursor();
1667 unset ($result);
6bb8e41d
DO
1668// Find the list of all assigned values of dictionary-addressed attributes, each with
1669// chapter/word keyed reference counters. Use the structure to adjust reference counters
1670// of the returned disctionary words.
10bac82a
DY
1671 $query2 = "select a.id as attr_id, am.chapter_id as chapter_no, uint_value, count(object_id) as refcnt " .
1672 "from Attribute as a inner join AttributeMap as am on a.id = am.attr_id " .
1673 "inner join AttributeValue as av on a.id = av.attr_id " .
1674 "inner join Dictionary as d on am.chapter_id = d.chapter_id and av.uint_value = d.dict_key " .
1675 "where a.type = 'dict' group by a.id, am.chapter_id, uint_value " .
1676 "order by a.id, am.chapter_id, uint_value";
065eeb52 1677 $result = useSelectBlade ($query2, __FUNCTION__);
89fa639f 1678 while ($row = $result->fetch (PDO::FETCH_ASSOC))
6bb8e41d 1679 $dict[$row['chapter_no']]['refcnt'][$row['uint_value']] = $row['refcnt'];
89fa639f 1680 $result->closeCursor();
e673ee24
DO
1681 return $dict;
1682}
1683
da95280e
DO
1684function getDictStats ()
1685{
590e1281 1686 $stock_chapters = array (1, 2, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25);
da95280e 1687 $query =
10bac82a 1688 "select Chapter.id as chapter_no, Chapter.name as chapter_name, count(dict_key) as wc from " .
6530f34e 1689 "Chapter left join Dictionary on Chapter.id = Dictionary.chapter_id group by Chapter.id";
065eeb52 1690 $result = useSelectBlade ($query, __FUNCTION__);
da95280e 1691 $tc = $tw = $uc = $uw = 0;
89fa639f 1692 while ($row = $result->fetch (PDO::FETCH_ASSOC))
da95280e
DO
1693 {
1694 $tc++;
1695 $tw += $row['wc'];;
1696 if (in_array ($row['chapter_no'], $stock_chapters))
1697 continue;
1698 $uc++;
1699 $uw += $row['wc'];;
1700 }
89fa639f
DO
1701 $result->closeCursor();
1702 unset ($result);
10bac82a 1703 $query = "select count(id) as attrc from RackObject as ro left join " .
08b4cb24 1704 "AttributeValue as av on ro.id = av.object_id group by ro.id";
065eeb52 1705 $result = useSelectBlade ($query, __FUNCTION__);
08b4cb24 1706 $to = $ta = $so = 0;
89fa639f 1707 while ($row = $result->fetch (PDO::FETCH_ASSOC))
08b4cb24
DO
1708 {
1709 $to++;
1710 if ($row['attrc'] != 0)
1711 {
1712 $so++;
1713 $ta += $row['attrc'];
1714 }
1715 }
89fa639f 1716 $result->closeCursor();
da95280e
DO
1717 $ret = array();
1718 $ret['Total chapters in dictionary'] = $tc;
1719 $ret['Total words in dictionary'] = $tw;
1720 $ret['User chapters'] = $uc;
1721 $ret['Words in user chapters'] = $uw;
08b4cb24
DO
1722 $ret['Total objects'] = $to;
1723 $ret['Objects with stickers'] = $so;
1724 $ret['Total stickers attached'] = $ta;
da95280e
DO
1725 return $ret;
1726}
1727
6807f0be 1728function getIPv4Stats ()
9ec5fdf1 1729{
9ec5fdf1
DO
1730 $ret = array();
1731 $subject = array();
706ce117
DO
1732 $subject[] = array ('q' => 'select count(id) from IPv4Network', 'txt' => 'Networks');
1733 $subject[] = array ('q' => 'select count(ip) from IPv4Address', 'txt' => 'Addresses commented/reserved');
1734 $subject[] = array ('q' => 'select count(ip) from IPv4Allocation', 'txt' => 'Addresses allocated');
1735 $subject[] = array ('q' => 'select count(*) from IPv4NAT', 'txt' => 'NAT rules');
1736 $subject[] = array ('q' => 'select count(id) from IPv4VS', 'txt' => 'Virtual services');
1737 $subject[] = array ('q' => 'select count(id) from IPv4RSPool', 'txt' => 'Real server pools');
1738 $subject[] = array ('q' => 'select count(id) from IPv4RS', 'txt' => 'Real servers');
1739 $subject[] = array ('q' => 'select count(distinct object_id) from IPv4LB', 'txt' => 'Load balancers');
9ec5fdf1
DO
1740
1741 foreach ($subject as $item)
1742 {
065eeb52 1743 $result = useSelectBlade ($item['q'], __FUNCTION__);
9ec5fdf1
DO
1744 $row = $result->fetch (PDO::FETCH_NUM);
1745 $ret[$item['txt']] = $row[0];
1746 $result->closeCursor();
1747 unset ($result);
1748 }
1749 return $ret;
1750}
1751
6807f0be 1752function getRackspaceStats ()
9ec5fdf1 1753{
9ec5fdf1
DO
1754 $ret = array();
1755 $subject = array();
10bac82a 1756 $subject[] = array ('q' => 'select count(*) from RackRow', 'txt' => 'Rack rows');
9ec5fdf1
DO
1757 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
1758 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
1759 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
1760
1761 foreach ($subject as $item)
1762 {
065eeb52 1763 $result = useSelectBlade ($item['q'], __FUNCTION__);
9ec5fdf1 1764 $row = $result->fetch (PDO::FETCH_NUM);
82f7e2e8 1765 $ret[$item['txt']] = empty ($row[0]) ? 0 : $row[0];
9ec5fdf1
DO
1766 $result->closeCursor();
1767 unset ($result);
1768 }
1769 return $ret;
1770}
1771
e9b9a095 1772function renderTagStats ()
5bbbeaa2 1773{
e9b9a095
DO
1774 global $taglist, $root;
1775 $query = "select id, tag, count(tag_id) as refcnt from " .
5bbbeaa2 1776 "TagTree inner join TagStorage on TagTree.id = TagStorage.tag_id " .
e9b9a095
DO
1777 "group by tag_id order by refcnt desc limit 50";
1778 // The same data is already present in pre-loaded tag list, but not in
1779 // the form we need. So let's ask the DB server for cooked top list and
1780 // use the cooked tag list to break it down.
065eeb52 1781 $result = useSelectBlade ($query, __FUNCTION__);
e9b9a095
DO
1782 $refc = $result->fetchAll (PDO::FETCH_ASSOC);
1783 echo '<table border=1><tr><th>tag</th><th>total</th><th>objects</th><th>IPv4 nets</th><th>racks</th>';
19ea3ebf 1784 echo '<th>IPv4 VS</th><th>IPv4 RS pools</th><th>users</th><th>files</th></tr>';
e9b9a095
DO
1785 $pagebyrealm = array
1786 (
939f9b03 1787 'file' => 'files&tab=default',
e9b9a095 1788 'ipv4net' => 'ipv4space&tab=default',
e9b9a095
DO
1789 'ipv4vs' => 'ipv4vslist&tab=default',
1790 'ipv4rspool' => 'ipv4rsplist&tab=default',
939f9b03 1791 'object' => 'depot&tab=default',
e1ae3fb4 1792 'rack' => 'rackspace&tab=default',
e9b9a095
DO
1793 'user' => 'userlist&tab=default'
1794 );
1795 foreach ($refc as $ref)
1796 {
1797 echo "<tr><td>${ref['tag']}</td><td>${ref['refcnt']}</td>";
19ea3ebf 1798 foreach (array ('object', 'ipv4net', 'rack', 'ipv4vs', 'ipv4rspool', 'user', 'file') as $realm)
e9b9a095
DO
1799 {
1800 echo '<td>';
1801 if (!isset ($taglist[$ref['id']]['refcnt'][$realm]))
1802 echo '&nbsp;';
1803 else
1804 {
a8efc03e 1805 echo "<a href='${root}?page=" . $pagebyrealm[$realm] . "&cft[]=${ref['id']}'>";
e9b9a095
DO
1806 echo $taglist[$ref['id']]['refcnt'][$realm] . '</a>';
1807 }
1808 echo '</td>';
1809 }
1810 echo '</tr>';
1811 }
1812 echo '</table>';
5bbbeaa2
DO
1813}
1814
6807f0be
DO
1815/*
1816
1817The following allows figuring out records in TagStorage, which refer to non-existing entities:
1818
120e9ddd
DO
1819mysql> select entity_id from TagStorage left join Files on entity_id = id where entity_realm = 'file' and id is null;
1820mysql> select entity_id from TagStorage left join IPv4Network on entity_id = id where entity_realm = 'ipv4net' and id is null;
1821mysql> select entity_id from TagStorage left join RackObject on entity_id = id where entity_realm = 'object' and id is null;
1822mysql> select entity_id from TagStorage left join Rack on entity_id = id where entity_realm = 'rack' and id is null;
1823mysql> select entity_id from TagStorage left join IPv4VS on entity_id = id where entity_realm = 'ipv4vs' and id is null;
1824mysql> select entity_id from TagStorage left join IPv4RSPool on entity_id = id where entity_realm = 'ipv4rspool' and id is null;
1825mysql> select entity_id from TagStorage left join UserAccount on entity_id = user_id where entity_realm = 'user' and user_id is null;
6807f0be
DO
1826
1827Accordingly, these are the records, which refer to non-existent tags:
1828
1829mysql> select tag_id from TagStorage left join TagTree on tag_id = id where id is null;
1830
1831*/
1832
e673ee24
DO
1833function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1834{
1835 if ($chapter_no <= 0 or $dict_key <= 0 or empty ($dict_value))
1836 {
f41b492f 1837 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1838 die;
1839 }
1840 global $dbxlink;
1841 $query =
10bac82a 1842 "update Dictionary set dict_value = '${dict_value}' where chapter_id=${chapter_no} " .
e673ee24
DO
1843 "and dict_key=${dict_key} limit 1";
1844 $result = $dbxlink->query ($query);
1845 if ($result == NULL)
1846 {
f41b492f 1847 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1848 die;
1849 }
1850 return TRUE;
1851}
1852
1853function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1854{
1855 if ($chapter_no <= 0 or empty ($dict_value))
1856 {
f41b492f 1857 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1858 die;
1859 }
1860 return useInsertBlade
1861 (
1862 'Dictionary',
10bac82a 1863 array ('chapter_id' => $chapter_no, 'dict_value' => "'${dict_value}'")
e673ee24
DO
1864 );
1865}
1866
1867function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1868{
1869 if ($chapter_no <= 0 or $dict_key <= 0)
1870 {
f41b492f 1871 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1872 die;
1873 }
1874 global $dbxlink;
1875 $query =
10bac82a 1876 "delete from Dictionary where chapter_id=${chapter_no} " .
e673ee24
DO
1877 "and dict_key=${dict_key} limit 1";
1878 $result = $dbxlink->query ($query);
1879 if ($result == NULL)
1880 {
f41b492f 1881 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1882 die;
1883 }
1884 return TRUE;
1885}
1886
1887function commitAddChapter ($chapter_name = '')
1888{
1889 if (empty ($chapter_name))
1890 {
f41b492f 1891 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1892 die;
1893 }
1894 return useInsertBlade
1895 (
1896 'Chapter',
10bac82a 1897 array ('name' => "'${chapter_name}'")
e673ee24
DO
1898 );
1899}
1900
1901function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
1902{
1903 if ($chapter_no <= 0 or empty ($chapter_name))
1904 {
f41b492f 1905 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1906 die;
1907 }
1908 global $dbxlink;
1909 $query =
10bac82a 1910 "update Chapter set name = '${chapter_name}' where id = ${chapter_no} " .
e673ee24
DO
1911 "and sticky = 'no' limit 1";
1912 $result = $dbxlink->query ($query);
1913 if ($result == NULL)
1914 {
f41b492f 1915 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1916 die;
1917 }
1918 return TRUE;
1919}
1920
1921function commitDeleteChapter ($chapter_no = 0)
1922{
1923 if ($chapter_no <= 0)
1924 {
f41b492f 1925 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
1926 die;
1927 }
1928 global $dbxlink;
1929 $query =
10bac82a 1930 "delete from Chapter where id = ${chapter_no} and sticky = 'no' limit 1";
e673ee24
DO
1931 $result = $dbxlink->query ($query);
1932 if ($result == NULL)
1933 {
f41b492f 1934 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
1935 die;
1936 }
1937 return TRUE;
1938}
1939
4c330a14
DO
1940// This is a dictionary accessor. We perform link rendering, so the user sees
1941// nice <select> drop-downs.
e673ee24
DO
1942function readChapter ($chapter_name = '')
1943{
1944 if (empty ($chapter_name))
1945 {
f41b492f 1946 showError ('invalid argument', __FUNCTION__);
e673ee24
DO
1947 return NULL;
1948 }
e673ee24 1949 $query =
10bac82a
DY
1950 "select dict_key, dict_value from Dictionary join Chapter on Chapter.id = Dictionary.chapter_id " .
1951 "where Chapter.name = '${chapter_name}'";
065eeb52 1952 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1953 $chapter = array();
1954 while ($row = $result->fetch (PDO::FETCH_ASSOC))
4c330a14 1955 $chapter[$row['dict_key']] = parseWikiLink ($row['dict_value'], 'o');
e673ee24 1956 $result->closeCursor();
4aa8609b
DO
1957 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
1958 asort ($chapter);
e673ee24
DO
1959 return $chapter;
1960}
1961
1962function getAttrMap ()
1963{
e673ee24 1964 $query =
10bac82a
DY
1965 "select a.id as attr_id, a.type as attr_type, a.name as attr_name, am.objtype_id, " .
1966 "d.dict_value as objtype_name, am.chapter_id, c2.name as chapter_name from " .
1967 "Attribute as a left join AttributeMap as am on a.id = am.attr_id " .
e673ee24 1968 "left join Dictionary as d on am.objtype_id = d.dict_key " .
10bac82a 1969 "left join Chapter as c1 on d.chapter_id = c1.id " .
291115e4 1970 "left join Chapter as c2 on am.chapter_id = c2.id " .
10bac82a
DY
1971 "where c1.name = 'RackObjectType' or c1.name is null " .
1972 "order by a.name";
065eeb52 1973 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
1974 $ret = array();
1975 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1976 {
1977 $attr_id = $row['attr_id'];
1978 if (!isset ($ret[$attr_id]))
1979 {
1980 $ret[$attr_id]['id'] = $attr_id;
1981 $ret[$attr_id]['type'] = $row['attr_type'];
1982 $ret[$attr_id]['name'] = $row['attr_name'];
1983 $ret[$attr_id]['application'] = array();
1984 }
1985 if ($row['objtype_id'] == '')
1986 continue;
1987 $application['objtype_id'] = $row['objtype_id'];
1988 $application['objtype_name'] = $row['objtype_name'];
1989 if ($row['attr_type'] == 'dict')
1990 {
50393983 1991 $application['chapter_no'] = $row['chapter_id'];
e673ee24
DO
1992 $application['chapter_name'] = $row['chapter_name'];
1993 }
1994 $ret[$attr_id]['application'][] = $application;
1995 }
1996 $result->closeCursor();
1997 return $ret;
1998}
1999
2000function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
2001{
2002 if ($attr_id <= 0 or empty ($attr_name))
2003 {
f41b492f 2004 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
2005 die;
2006 }
2007 global $dbxlink;
2008 $query =
10bac82a
DY
2009 "update Attribute set name = '${attr_name}' " .
2010 "where id = ${attr_id} limit 1";
e673ee24
DO
2011 $result = $dbxlink->query ($query);
2012 if ($result == NULL)
2013 {
f41b492f 2014 showError ("SQL query '${query}' failed", __FUNCTION__);
e673ee24
DO
2015 die;
2016 }
2017 return TRUE;
2018}
2019
2020function commitAddAttribute ($attr_name = '', $attr_type = '')
2021{
2022 if (empty ($attr_name))
2023 {
f41b492f 2024 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
2025 die;
2026 }
2027 switch ($attr_type)
2028 {
2029 case 'uint':
2030 case 'float':
2031 case 'string':
2032 case 'dict':
2033 break;
2034 default:
f41b492f 2035 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
2036 die;
2037 }
2038 return useInsertBlade
2039 (
2040 'Attribute',
10bac82a 2041 array ('name' => "'${attr_name}'", 'type' => "'${attr_type}'")
e673ee24
DO
2042 );
2043}
2044
2045function commitDeleteAttribute ($attr_id = 0)
2046{
2047 if ($attr_id <= 0)
2048 {
f41b492f 2049 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
2050 die;
2051 }
10bac82a 2052 return useDeleteBlade ('Attribute', 'id', $attr_id);
e673ee24
DO
2053}
2054
2055// FIXME: don't store garbage in chapter_no for non-dictionary types.
2056function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
2057{
2058 if ($attr_id <= 0 or $objtype_id <= 0 or $chapter_no <= 0)
2059 {
f41b492f 2060 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
2061 die;
2062 }
2063 return useInsertBlade
2064 (
2065 'AttributeMap',
2066 array
2067 (
2068 'attr_id' => $attr_id,
2069 'objtype_id' => $objtype_id,
10bac82a 2070 'chapter_id' => $chapter_no
e673ee24
DO
2071 )
2072 );
2073}
2074
2075function commitReduceAttrMap ($attr_id = 0, $objtype_id)
2076{
2077 if ($attr_id <= 0 or $objtype_id <= 0)
2078 {
f41b492f 2079 showError ('Invalid args', __FUNCTION__);
e673ee24
DO
2080 die;
2081 }
2082 global $dbxlink;
2083 $query =
2084 "delete from AttributeMap where attr_id=${attr_id} " .
2085 "and objtype_id=${objtype_id} limit 1";
2086 $result = $dbxlink->query ($query);
2087 if ($result == NULL)
2088 {
f41b492f 2089 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
2090 die;
2091 }
2092 return TRUE;
2093}
2094
2095// This function returns all optional attributes for requested object
2096// as an array of records. NULL is returned on error and empty array
2097// is returned, if there are no attributes found.
24cbe8af 2098function getAttrValues ($object_id, $strip_optgroup = FALSE)
e673ee24
DO
2099{
2100 if ($object_id <= 0)
2101 {
f41b492f 2102 showError ('Invalid argument', __FUNCTION__);
e673ee24
DO
2103 return NULL;
2104 }
e673ee24
DO
2105 $ret = array();
2106 $query =
10bac82a 2107 "select A.id as attr_id, A.name as attr_name, A.type as attr_type, C.name as chapter_name, " .
e673ee24
DO
2108 "AV.uint_value, AV.float_value, AV.string_value, D.dict_value from " .
2109 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
10bac82a 2110 "inner join Attribute as A on AM.attr_id = A.id " .
e673ee24 2111 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
10bac82a
DY
2112 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_id = D.chapter_id " .
2113 "left join Chapter as C on AM.chapter_id = C.id " .
2114 "where RO.id = ${object_id} order by A.type, A.name";
065eeb52 2115 $result = useSelectBlade ($query, __FUNCTION__);
e673ee24
DO
2116 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2117 {
2118 $record = array();
2119 $record['id'] = $row['attr_id'];
2120 $record['name'] = $row['attr_name'];
2121 $record['type'] = $row['attr_type'];
2122 switch ($row['attr_type'])
2123 {
2124 case 'uint':
2125 case 'float':
2126 case 'string':
24cbe8af
DO
2127 $record['value'] = $row[$row['attr_type'] . '_value'];
2128 $record['a_value'] = parseWikiLink ($record['value'], 'a');
2129 break;
e673ee24 2130 case 'dict':
24cbe8af
DO
2131 $record['value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'o', $strip_optgroup);
2132 $record['a_value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'a', $strip_optgroup);
e673ee24
DO
2133 $record['chapter_name'] = $row['chapter_name'];
2134 $record['key'] = $row['uint_value'];
2135 break;
2136 default:
2137 $record['value'] = NULL;
2138 break;
2139 }
2140 $ret[$row['attr_id']] = $record;
2141 }
2142 $result->closeCursor();
2143 return $ret;
2144}
2145
2146function commitResetAttrValue ($object_id = 0, $attr_id = 0)
2147{
2148 if ($object_id <= 0 or $attr_id <= 0)
2149 {
f41b492f 2150 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
2151 die;
2152 }
2153 global $dbxlink;
2154 $query = "delete from AttributeValue where object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2155 $result = $dbxlink->query ($query);
2156 if ($result == NULL)
2157 {
f41b492f 2158 showError ('SQL query failed', __FUNCTION__);
e673ee24
DO
2159 die;
2160 }
2161 return TRUE;
2162}
2163
2164// FIXME: don't share common code with use commitResetAttrValue()
2165function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
2166{
2167 if ($object_id <= 0 or $attr_id <= 0)
2168 {
f41b492f 2169 showError ('Invalid arguments', __FUNCTION__);
e673ee24
DO
2170 die;
2171 }
2172 if (empty ($value))
2173 return commitResetAttrValue ($object_id, $attr_id);
2174 global $dbxlink;
10bac82a 2175 $query1 = "select type as attr_type from Attribute where id = ${attr_id}";
e673ee24
DO
2176 $result = $dbxlink->query ($query1);
2177 if ($result == NULL)
2178 {
f41b492f 2179 showError ('SQL query #1 failed', __FUNCTION__);
e673ee24
DO
2180 die;
2181 }
2182 $row = $result->fetch (PDO::FETCH_NUM);
2183 if ($row == NULL)
2184 {
f41b492f 2185 showError ('SQL query #1 returned no results', __FUNCTION__);
e673ee24
DO
2186 die;
2187 }
2188 $attr_type = $row[0];
2189 $result->closeCursor();
2190 switch ($attr_type)
2191 {
2192 case 'uint':
2193 case 'float':
2194 case 'string':
2195 $column = $attr_type . '_value';
2196 break;
2197 case 'dict':
2198 $column = 'uint_value';
2199 break;
2200 default:
f41b492f 2201 showError ("Unknown attribute type '${attr_type}' met", __FUNCTION__);
e673ee24
DO
2202 die;
2203 }
2204 $query2 =
2205 "delete from AttributeValue where " .
2206 "object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2207 $result = $dbxlink->query ($query2);
2208 if ($result == NULL)
2209 {
f41b492f 2210 showError ('SQL query #2 failed', __FUNCTION__);
e673ee24
DO
2211 die;
2212 }
2213 // We know $value isn't empty here.
2214 $query3 =
2215 "insert into AttributeValue set ${column} = '${value}', " .
2216 "object_id = ${object_id}, attr_id = ${attr_id} ";
2217 $result = $dbxlink->query ($query3);
2218 if ($result == NULL)
2219 {
f41b492f 2220 showError ('SQL query #3 failed', __FUNCTION__);
e673ee24
DO
2221 die;
2222 }
2223 return TRUE;
2224}
2225
2226function commitUseupPort ($port_id = 0)
2227{
2228 if ($port_id <= 0)
2229 {
f41b492f 2230 showError ("Invalid argument", __FUNCTION__);
e673ee24
DO
2231 die;
2232 }
2233 global $dbxlink;
2234 $query = "update Port set reservation_comment = NULL where id = ${port_id} limit 1";
2235 $result = $dbxlink->exec ($query);
2236 if ($result == NULL)
2237 {
f41b492f 2238 showError ("SQL query failed", __FUNCTION__);
e673ee24
DO
2239 die;
2240 }
2241 return TRUE;
2242
2243}
2244
2245// This is a swiss-knife blade to insert a record into a table.
2246// The first argument is table name.
2247// The second argument is an array of "name" => "value" pairs.
2248// The function returns either TRUE or FALSE (we expect one row
2249// to be inserted).
2250function useInsertBlade ($tablename, $values)
2251{
2252 global $dbxlink;
2253 $namelist = $valuelist = '';
2254 foreach ($values as $name => $value)
2255 {
2256 $namelist = $namelist . ($namelist == '' ? "(${name}" : ", ${name}");
2257 $valuelist = $valuelist . ($valuelist == '' ? "(${value}" : ", ${value}");
2258 }
2259 $query = "insert into ${tablename} ${namelist}) values ${valuelist})";
2260 $result = $dbxlink->exec ($query);
2261 if ($result != 1)
2262 return FALSE;
2263 return TRUE;
2264}
2265
2266// This swiss-knife blade deletes one record from the specified table
2267// using the specified key name and value.
f5575f12 2268function useDeleteBlade ($tablename, $keyname, $keyvalue)
e673ee24
DO
2269{
2270 global $dbxlink;
f5575f12 2271 return 1 === $dbxlink->exec ("delete from ${tablename} where ${keyname}=${keyvalue} limit 1");
e673ee24
DO
2272}
2273
5967b83d
DO
2274function useSelectBlade ($query, $caller = 'N/A')
2275{
2276 global $dbxlink;
2277 $result = $dbxlink->query ($query);
2278 if ($result == NULL)
2279 {
2280 $ei = $dbxlink->errorInfo();
105a3bc8 2281 showError ("SQL query '${query}'\n failed in useSelectBlade with error ${ei[1]} (${ei[2]})", $caller);
5967b83d
DO
2282 return NULL;
2283 }
2284 return $result;
2285}
2286
9c0b0016
DO
2287function loadConfigCache ()
2288{
4fe32e78 2289 $query = 'SELECT varname, varvalue, vartype, is_hidden, emptyok, description FROM Config ORDER BY varname';
065eeb52 2290 $result = useSelectBlade ($query, __FUNCTION__);
9c0b0016
DO
2291 $cache = array();
2292 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2293 $cache[$row['varname']] = $row;
2294 $result->closeCursor();
2295 return $cache;
2296}
2297
2298// setConfigVar() is expected to perform all necessary filtering
2299function storeConfigVar ($varname = NULL, $varvalue = NULL)
2300{
c461c579 2301 global $dbxlink;
bb6b9880 2302 if (empty ($varname) || $varvalue === NULL)
9c0b0016 2303 {
f41b492f 2304 showError ('Invalid arguments', __FUNCTION__);
9c0b0016
DO
2305 return FALSE;
2306 }
2307 $query = "update Config set varvalue='${varvalue}' where varname='${varname}' limit 1";
2308 $result = $dbxlink->query ($query);
2309 if ($result == NULL)
2310 {
f41b492f 2311 showError ("SQL query '${query}' failed", __FUNCTION__);
9c0b0016
DO
2312 return FALSE;
2313 }
2314 $rc = $result->rowCount();
2315 $result->closeCursor();
f7ee57a1 2316 if ($rc == 0 or $rc == 1)
9c0b0016 2317 return TRUE;
f41b492f 2318 showError ("Something went wrong for args '${varname}', '${varvalue}'", __FUNCTION__);
9c0b0016
DO
2319 return FALSE;
2320}
2321
fbbb74fb
DO
2322// Database version detector. Should behave corretly on any
2323// working dataset a user might have.
2324function getDatabaseVersion ()
2325{
2326 global $dbxlink;
2327 $query = "select varvalue from Config where varname = 'DB_VERSION' and vartype = 'string'";
2328 $result = $dbxlink->query ($query);
2329 if ($result == NULL)
2330 {
2331 $errorInfo = $dbxlink->errorInfo();
2332 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
2333 return '0.14.4';
4d2e93f2 2334 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
fbbb74fb
DO
2335 }
2336 $rows = $result->fetchAll (PDO::FETCH_NUM);
2337 if (count ($rows) != 1 || empty ($rows[0][0]))
2338 {
2339 $result->closeCursor();
4d2e93f2 2340 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
fbbb74fb
DO
2341 }
2342 $ret = $rows[0][0];
2343 $result->closeCursor();
2344 return $ret;
2345}
2346
da04825a
DO
2347// Return an array of virtual services. For each of them list real server pools
2348// with their load balancers and other stats.
62a1dcb5
DO
2349function getSLBSummary ()
2350{
6fec9f39
DO
2351 $query = 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
2352 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
706ce117
DO
2353 'from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id ' .
2354 'inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2355 'left join IPv4RS as rs on rs.rspool_id = lb.rspool_id ' .
6fec9f39 2356 'group by vs.id, object_id order by vs.vip, object_id';
065eeb52 2357 $result = useSelectBlade ($query, __FUNCTION__);
c3bdc503
DO
2358 $ret = array();
2359 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2360 {
4cadac8f 2361 $vsid = $row['vsid'];
da04825a 2362 $object_id = $row['object_id'];
4cadac8f
DO
2363 if (!isset ($ret[$vsid]))
2364 {
2365 $ret[$vsid] = array();
13bffb29 2366 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
4cadac8f 2367 $ret[$vsid][$cname] = $row[$cname];
da04825a 2368 $ret[$vsid]['lblist'] = array();
4cadac8f 2369 }
6fec9f39
DO
2370 // There's only one assigned RS pool possible for each LB-VS combination.
2371 $ret[$vsid]['lblist'][$row['object_id']] = array
2372 (
2373 'id' => $row['rspool_id'],
2374 'size' => $row['rscount'],
2375 'name' => $row['pool_name']
2376 );
c3bdc503 2377 }
060ba26e 2378 $result->closeCursor();
c3bdc503 2379 return $ret;
62a1dcb5
DO
2380}
2381
da04825a
DO
2382// Get the detailed composition of a particular virtual service, namely the list
2383// of all pools, each shown with the list of objects servicing it. VS/RS configs
2384// will be returned as well.
060ba26e
DO
2385function getVServiceInfo ($vsid = 0)
2386{
8128c257 2387 $query1 = "select id, inet_ntoa(vip) as vip, vport, proto, name, vsconfig, rsconfig " .
706ce117 2388 "from IPv4VS where id = ${vsid}";
065eeb52 2389 $result = useSelectBlade ($query1, __FUNCTION__);
060ba26e 2390 $vsinfo = array ();
89fa639f 2391 $row = $result->fetch (PDO::FETCH_ASSOC);
2b4eee17
DO
2392 if (!$row)
2393 return NULL;
8128c257 2394 foreach (array ('id', 'vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig') as $cname)
2b4eee17
DO
2395 $vsinfo[$cname] = $row[$cname];
2396 $vsinfo['rspool'] = array();
89fa639f
DO
2397 $result->closeCursor();
2398 unset ($result);
2b4eee17
DO
2399 $query2 = "select pool.id, name, pool.vsconfig, pool.rsconfig, object_id, " .
2400 "lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig from " .
706ce117 2401 "IPv4RSPool as pool left join IPv4LB as lb on pool.id = lb.rspool_id " .
2b4eee17 2402 "where vs_id = ${vsid} order by pool.name, object_id";
065eeb52 2403 $result = useSelectBlade ($query2, __FUNCTION__);
89fa639f 2404 while ($row = $result->fetch (PDO::FETCH_ASSOC))
060ba26e 2405 {
2b4eee17 2406 if (!isset ($vsinfo['rspool'][$row['id']]))
060ba26e 2407 {
2b4eee17
DO
2408 $vsinfo['rspool'][$row['id']]['name'] = $row['name'];
2409 $vsinfo['rspool'][$row['id']]['vsconfig'] = $row['vsconfig'];
2410 $vsinfo['rspool'][$row['id']]['rsconfig'] = $row['rsconfig'];
2411 $vsinfo['rspool'][$row['id']]['lblist'] = array();
060ba26e 2412 }
2b4eee17
DO
2413 if ($row['object_id'] == NULL)
2414 continue;
2415 $vsinfo['rspool'][$row['id']]['lblist'][$row['object_id']] = array
2416 (
2417 'vsconfig' => $row['lb_vsconfig'],
2418 'rsconfig' => $row['lb_rsconfig']
2419 );
060ba26e 2420 }
89fa639f 2421 $result->closeCursor();
060ba26e
DO
2422 return $vsinfo;
2423}
2424
71b8bda1
DO
2425// Collect and return the following info about the given real server pool:
2426// basic information
2427// parent virtual service information
c1ca768c 2428// load balancers list (each with a list of VSes)
71b8bda1
DO
2429// real servers list
2430
2431function getRSPoolInfo ($id = 0)
2432{
c1ca768c 2433 $query1 = "select id, name, vsconfig, rsconfig from " .
706ce117 2434 "IPv4RSPool where id = ${id}";
065eeb52 2435 $result = useSelectBlade ($query1, __FUNCTION__);
71b8bda1 2436 $ret = array();
89fa639f 2437 $row = $result->fetch (PDO::FETCH_ASSOC);
71b8bda1
DO
2438 if (!$row)
2439 return NULL;
70c24883 2440 foreach (array ('id', 'name', 'vsconfig', 'rsconfig') as $c)
71b8bda1 2441 $ret[$c] = $row[$c];
89fa639f
DO
2442 $result->closeCursor();
2443 unset ($result);
71b8bda1
DO
2444 $ret['lblist'] = array();
2445 $ret['rslist'] = array();
e7959acb 2446 $query2 = "select object_id, vs_id, lb.vsconfig, lb.rsconfig from " .
706ce117 2447 "IPv4LB as lb inner join IPv4VS as vs on lb.vs_id = vs.id " .
e7959acb 2448 "where rspool_id = ${id} order by object_id, vip, vport";
065eeb52 2449 $result = useSelectBlade ($query2, __FUNCTION__);
89fa639f 2450 while ($row = $result->fetch (PDO::FETCH_ASSOC))
71b8bda1 2451 foreach (array ('vsconfig', 'rsconfig') as $c)
c1ca768c 2452 $ret['lblist'][$row['object_id']][$row['vs_id']][$c] = $row[$c];
89fa639f
DO
2453 $result->closeCursor();
2454 unset ($result);
1f7d18fa 2455 $query3 = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rsconfig from " .
706ce117 2456 "IPv4RS where rspool_id = ${id} order by IPv4RS.rsip, rsport";
065eeb52 2457 $result = useSelectBlade ($query3, __FUNCTION__);
89fa639f 2458 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1f7d18fa 2459 foreach (array ('inservice', 'rsip', 'rsport', 'rsconfig') as $c)
71b8bda1 2460 $ret['rslist'][$row['id']][$c] = $row[$c];
89fa639f 2461 $result->closeCursor();
71b8bda1
DO
2462 return $ret;
2463}
2464
7e7a8387 2465function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
ca461127 2466{
79a9edb4 2467 if ($pool_id <= 0)
ca461127
DO
2468 {
2469 showError ('Invalid arguments', __FUNCTION__);
2470 die;
2471 }
79a9edb4
DO
2472 if (empty ($rsport) or $rsport == 0)
2473 $rsport = 'NULL';
ca461127
DO
2474 return useInsertBlade
2475 (
706ce117 2476 'IPv4RS',
ca461127
DO
2477 array
2478 (
2479 'rsip' => "inet_aton('${rsip}')",
2480 'rsport' => $rsport,
2481 'rspool_id' => $pool_id,
bcbeadb4 2482 'inservice' => ($inservice == 'yes' ? "'yes'" : "'no'"),
3241551e
DO
2483 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2484 )
2485 );
2486}
2487
c63a8d6e 2488function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig, $taglist = array())
d6517a21
DO
2489{
2490 if (empty ($vip) or $vport <= 0 or empty ($proto))
c63a8d6e
DO
2491 return __FUNCTION__ . ': invalid arguments';
2492 if (!useInsertBlade
d6517a21 2493 (
706ce117 2494 'IPv4VS',
d6517a21
DO
2495 array
2496 (
2497 'vip' => "inet_aton('${vip}')",
2498 'vport' => $vport,
2499 'proto' => "'${proto}'",
2500 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2501 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2502 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2503 )
c63a8d6e
DO
2504 ))
2505 return __FUNCTION__ . ': SQL insertion failed';
351c0966 2506 return produceTagsForLastRecord ('ipv4vs', $taglist);
d6517a21
DO
2507}
2508
c1ca768c 2509function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2510{
c1ca768c 2511 if ($pool_id <= 0 or $object_id <= 0 or $vs_id <= 0)
3241551e
DO
2512 {
2513 showError ('Invalid arguments', __FUNCTION__);
2514 die;
2515 }
2516 return useInsertBlade
2517 (
706ce117 2518 'IPv4LB',
3241551e
DO
2519 array
2520 (
2521 'object_id' => $object_id,
2522 'rspool_id' => $pool_id,
c1ca768c 2523 'vs_id' => $vs_id,
3241551e
DO
2524 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2525 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2526 )
ca461127
DO
2527 );
2528}
2529
fb1c4a54
DO
2530function commitDeleteRS ($id = 0)
2531{
2532 if ($id <= 0)
2533 return FALSE;
706ce117 2534 return useDeleteBlade ('IPv4RS', 'id', $id);
fb1c4a54
DO
2535}
2536
d6517a21
DO
2537function commitDeleteVS ($id = 0)
2538{
2539 if ($id <= 0)
2540 return FALSE;
706ce117 2541 return useDeleteBlade ('IPv4VS', 'id', $id) && destroyTagsForEntity ('ipv4vs', $id);
d6517a21
DO
2542}
2543
c1ca768c 2544function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
3241551e
DO
2545{
2546 global $dbxlink;
c4d85fd1 2547 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
3241551e 2548 return FALSE;
706ce117 2549 $query = "delete from IPv4LB where object_id = ${object_id} and " .
c1ca768c 2550 "rspool_id = ${pool_id} and vs_id = ${vs_id} limit 1";
3241551e
DO
2551 $result = $dbxlink->exec ($query);
2552 if ($result === NULL)
2553 return FALSE;
2554 elseif ($result != 1)
2555 return FALSE;
2556 else
2557 return TRUE;
2558}
2559
fb1c4a54
DO
2560function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2561{
79a9edb4 2562 if ($rsid <= 0)
fb1c4a54
DO
2563 {
2564 showError ('Invalid args', __FUNCTION__);
2565 die;
2566 }
2567 if (long2ip (ip2long ($rsip)) !== $rsip)
2568 {
2569 showError ("Invalid IP address '${rsip}'", __FUNCTION__);
2570 die;
2571 }
79a9edb4
DO
2572 if (empty ($rsport) or $rsport == 0)
2573 $rsport = 'NULL';
fb1c4a54
DO
2574 global $dbxlink;
2575 $query =
706ce117 2576 "update IPv4RS set rsip = inet_aton('${rsip}'), rsport = ${rsport}, rsconfig = " .
3241551e 2577 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
fb1c4a54
DO
2578 " where id = ${rsid} limit 1";
2579 $result = $dbxlink->query ($query);
2580 if ($result == NULL)
2581 {
2582 showError ("SQL query '${query}' failed", __FUNCTION__);
2583 die;
2584 }
2585 return TRUE;
2586}
2587
c1ca768c 2588function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
3241551e 2589{
c1ca768c 2590 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
3241551e
DO
2591 {
2592 showError ('Invalid args', __FUNCTION__);
2593 die;
2594 }
2595 global $dbxlink;
2596 $query =
706ce117 2597 "update IPv4LB set vsconfig = " .
3241551e
DO
2598 (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'") .
2599 ', rsconfig = ' .
2600 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
c1ca768c
DO
2601 " where object_id = ${object_id} and rspool_id = ${pool_id} " .
2602 "and vs_id = ${vs_id} limit 1";
3241551e
DO
2603 $result = $dbxlink->exec ($query);
2604 if ($result === NULL)
2605 return FALSE;
3241551e
DO
2606 else
2607 return TRUE;
2608}
2609
d6517a21
DO
2610function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2611{
2612 if ($vsid <= 0 or empty ($vip) or $vport <= 0 or empty ($proto))
2613 {
2614 showError ('Invalid args', __FUNCTION__);
2615 die;
2616 }
2617 global $dbxlink;
706ce117 2618 $query = "update IPv4VS set " .
d6517a21
DO
2619 "vip = inet_aton('${vip}'), " .
2620 "vport = ${vport}, " .
2621 "proto = '${proto}', " .
2622 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2623 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
5ad76f01
DO
2624 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2625 " where id = ${vsid} limit 1";
d6517a21
DO
2626 $result = $dbxlink->exec ($query);
2627 if ($result === NULL)
2628 return FALSE;
d6517a21
DO
2629 else
2630 return TRUE;
2631}
2632
5a1680d2
DO
2633function loadThumbCache ($rack_id = 0)
2634{
5a1680d2
DO
2635 $ret = NULL;
2636 $query = "select thumb_data from Rack where id = ${rack_id} and thumb_data is not null limit 1";
065eeb52 2637 $result = useSelectBlade ($query, __FUNCTION__);
5a1680d2
DO
2638 $row = $result->fetch (PDO::FETCH_ASSOC);
2639 if ($row)
2640 $ret = base64_decode ($row['thumb_data']);
2641 $result->closeCursor();
2642 return $ret;
2643}
2644
2645function saveThumbCache ($rack_id = 0, $cache = NULL)
2646{
2647 global $dbxlink;
2648 if ($rack_id == 0 or $cache == NULL)
2649 {
2650 showError ('Invalid arguments', __FUNCTION__);
2651 return;
2652 }
2653 $data = base64_encode ($cache);
2654 $query = "update Rack set thumb_data = '${data}' where id = ${rack_id} limit 1";
2655 $result = $dbxlink->exec ($query);
2656}
9a81d416 2657
c7fe33be
DO
2658function resetThumbCache ($rack_id = 0)
2659{
2660 global $dbxlink;
2661 if ($rack_id == 0)
2662 {
2663 showError ('Invalid argument', __FUNCTION__);
2664 return;
2665 }
2666 $query = "update Rack set thumb_data = NULL where id = ${rack_id} limit 1";
2667 $result = $dbxlink->exec ($query);
2668}
2669
748805bf 2670// Return the list of attached RS pools for the given object. As long as we have
706ce117 2671// the LB-VS UNIQUE in IPv4LB table, it is Ok to key returned records
748805bf
DO
2672// by vs_id, because there will be only one RS pool listed for each VS of the
2673// current object.
78e7b769
DO
2674function getRSPoolsForObject ($object_id = 0)
2675{
2676 if ($object_id <= 0)
2677 {
2678 showError ('Invalid object_id', __FUNCTION__);
2679 return NULL;
2680 }
748805bf 2681 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
732e4578 2682 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
706ce117
DO
2683 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2684 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2685 'left join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
748805bf
DO
2686 "where lb.object_id = ${object_id} " .
2687 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name';
065eeb52 2688 $result = useSelectBlade ($query, __FUNCTION__);
748805bf 2689 $ret = array ();
78e7b769 2690 while ($row = $result->fetch (PDO::FETCH_ASSOC))
732e4578 2691 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
748805bf 2692 $ret[$row['vs_id']][$cname] = $row[$cname];
78e7b769 2693 $result->closeCursor();
748805bf 2694 return $ret;
78e7b769
DO
2695}
2696
c63a8d6e 2697function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
5ad76f01 2698{
c63a8d6e
DO
2699 if (empty ($name))
2700 return __FUNCTION__ . ': invalid arguments';
2701 if (!useInsertBlade
5ad76f01 2702 (
706ce117 2703 'IPv4RSPool',
5ad76f01
DO
2704 array
2705 (
5ad76f01
DO
2706 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2707 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2708 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2709 )
c63a8d6e
DO
2710 ))
2711 return __FUNCTION__ . ': SQL insertion failed';
351c0966 2712 return produceTagsForLastRecord ('ipv4rspool', $taglist);
5ad76f01
DO
2713}
2714
2715function commitDeleteRSPool ($pool_id = 0)
2716{
2717 global $dbxlink;
2718 if ($pool_id <= 0)
2719 return FALSE;
706ce117 2720 return useDeleteBlade ('IPv4RSPool', 'id', $pool_id) && destroyTagsForEntity ('ipv4rspool', $pool_id);
5ad76f01
DO
2721}
2722
2723function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2724{
2725 if ($pool_id <= 0)
2726 {
2727 showError ('Invalid arg', __FUNCTION__);
2728 die;
2729 }
2730 global $dbxlink;
706ce117 2731 $query = "update IPv4RSPool set " .
5ad76f01
DO
2732 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2733 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2734 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2735 " where id = ${pool_id} limit 1";
2736 $result = $dbxlink->exec ($query);
2737 if ($result === NULL)
2738 return FALSE;
2739 elseif ($result != 1)
2740 return FALSE;
2741 else
2742 return TRUE;
2743}
2744
8253d9f0
DO
2745function getRSList ()
2746{
1f7d18fa 2747 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
706ce117 2748 "from IPv4RS order by rspool_id, IPv4RS.rsip, rsport";
065eeb52 2749 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6 2750 $ret = array ();
8253d9f0 2751 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1f7d18fa 2752 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
4b0932b6
DO
2753 $ret[$row['id']][$cname] = $row[$cname];
2754 $result->closeCursor();
2755 return $ret;
2756}
2757
2758// Return the list of all currently configured load balancers with their pool count.
2759function getLBList ()
2760{
4b0932b6 2761 $query = "select object_id, count(rspool_id) as poolcount " .
706ce117 2762 "from IPv4LB group by object_id order by object_id";
065eeb52 2763 $result = useSelectBlade ($query, __FUNCTION__);
4b0932b6
DO
2764 $ret = array ();
2765 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2766 $ret[$row['object_id']] = $row['poolcount'];
8253d9f0 2767 $result->closeCursor();
4b0932b6 2768 return $ret;
8253d9f0
DO
2769}
2770
9e677cbd
DO
2771// For the given object return: it vsconfig/rsconfig; the list of RS pools
2772// attached (each with vsconfig/rsconfig in turn), each with the list of
2773// virtual services terminating the pool. Each pool also lists all real
2774// servers with rsconfig.
2987fc1f 2775function getSLBConfig ($object_id)
9e677cbd
DO
2776{
2777 if ($object_id <= 0)
2778 {
2779 showError ('Invalid arg', __FUNCTION__);
2780 return NULL;
2781 }
9e677cbd 2782 $ret = array();
d91f08f3
DO
2783 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2784 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2785 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
9e677cbd 2786 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
d91f08f3 2787 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
706ce117
DO
2788 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2789 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2790 'inner join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
1f7d18fa
DO
2791 "where lb.object_id = ${object_id} and rs.inservice = 'yes' " .
2792 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport";
065eeb52 2793 $result = useSelectBlade ($query, __FUNCTION__);
9e677cbd
DO
2794 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2795 {
d91f08f3
DO
2796 $vs_id = $row['vs_id'];
2797 if (!isset ($ret[$vs_id]))
2798 {
2799 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)
2800 $ret[$vs_id][$c] = $row[$c];
2801 $ret[$vs_id]['rslist'] = array();
2802 }
2803 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2804 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
9e677cbd
DO
2805 }
2806 $result->closeCursor();
2807 return $ret;
2808}
1f7d18fa
DO
2809
2810function commitSetInService ($rs_id = 0, $inservice = '')
2811{
2812 if ($rs_id <= 0 or empty ($inservice))
2813 {
2814 showError ('Invalid args', __FUNCTION__);
2815 return NULL;
2816 }
2817 global $dbxlink;
706ce117 2818 $query = "update IPv4RS set inservice = '${inservice}' where id = ${rs_id} limit 1";
1f7d18fa
DO
2819 $result = $dbxlink->exec ($query);
2820 if ($result === NULL)
2821 return FALSE;
2822 elseif ($result != 1)
2823 return FALSE;
2824 else
2825 return TRUE;
2826}
2827
ad0e4754
DO
2828function executeAutoPorts ($object_id = 0, $type_id = 0)
2829{
2830 if ($object_id == 0 or $type_id == 0)
2831 {
2832 showError ('Invalid arguments', __FUNCTION__);
2833 die;
2834 }
f3f0161f 2835 $ret = TRUE;
118e4c38 2836 foreach (getAutoPorts ($type_id) as $autoport)
f3f0161f
DO
2837 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2838 return $ret;
ad0e4754
DO
2839}
2840
6e49bd1f 2841// Return only implicitly listed tags, the rest of the chain will be
a6e8d544 2842// generated/deducted later at higher levels.
aab37bc0 2843// Result is a chain: randomly indexed taginfo list.
f9bc186f 2844function loadEntityTags ($entity_realm = '', $entity_id = 0)
5967b83d 2845{
a6e8d544 2846 $ret = array();
2c21a10c
DO
2847 if (!in_array ($entity_realm, array ('file', 'ipv4net', 'ipv4vs', 'ipv4rspool', 'object', 'rack', 'user')))
2848 return $ret;
edf0993c
DO
2849 $query = "select tt.id, tag from " .
2850 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
120e9ddd 2851 "where entity_realm = '${entity_realm}' and entity_id = ${entity_id} " .
edf0993c
DO
2852 "order by tt.tag";
2853 $result = useSelectBlade ($query, __FUNCTION__);
5967b83d 2854 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2fb24351 2855 $ret[$row['id']] = $row;
a6e8d544 2856 $result->closeCursor();
aab37bc0 2857 return getExplicitTagsOnly ($ret);
5967b83d
DO
2858}
2859
351c0966 2860// Return a tag chain with all DB tags on it.
5967b83d
DO
2861function getTagList ()
2862{
20c901a7 2863 $ret = array();
120e9ddd 2864 $query = "select id, parent_id, tag, entity_realm as realm, count(entity_id) as refcnt " .
5b7bd02e 2865 "from TagTree left join TagStorage on id = tag_id " .
120e9ddd 2866 "group by id, entity_realm order by tag";
065eeb52 2867 $result = useSelectBlade ($query, __FUNCTION__);
fb7a4967
DO
2868 $ci = 0; // Collation index. The resulting rows are ordered according to default collation,
2869 // which is utf8_general_ci for UTF-8.
5967b83d 2870 while ($row = $result->fetch (PDO::FETCH_ASSOC))
5b7bd02e 2871 {
7cc02fc1 2872 if (!isset ($ret[$row['id']]))
20c901a7 2873 $ret[$row['id']] = array
5b7bd02e
DO
2874 (
2875 'id' => $row['id'],
2876 'tag' => $row['tag'],
fb7a4967 2877 'ci' => $ci++,
5b7bd02e
DO
2878 'parent_id' => $row['parent_id'],
2879 'refcnt' => array()
2880 );
2881 if ($row['realm'])
20c901a7 2882 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
5b7bd02e 2883 }
5967b83d 2884 $result->closeCursor();
20c901a7 2885 return $ret;
5967b83d
DO
2886}
2887
fe7044ad
DO
2888function commitCreateTag ($tagname = '', $parent_id = 0)
2889{
2890 if ($tagname == '' or $parent_id === 0)
2891 return "Invalid args to " . __FUNCTION__;
2892 $result = useInsertBlade
2893 (
2894 'TagTree',
2895 array
2896 (
2897 'tag' => "'${tagname}'",
2898 'parent_id' => $parent_id
2899 )
2900 );
590e1281 2901 global $dbxlink;
fe7044ad
DO
2902 if ($result)
2903 return '';
590e1281
DO
2904 elseif ($dbxlink->errorCode() == 23000)
2905 return "name '${tag_name}' is already used";
fe7044ad
DO
2906 else
2907 return "SQL query failed in " . __FUNCTION__;
2908}
2909
2910function commitDestroyTag ($tagid = 0)
2911{
2912 if ($tagid == 0)
2913 return 'Invalid arg to ' . __FUNCTION__;
f5575f12 2914 if (useDeleteBlade ('TagTree', 'id', $tagid))
fe7044ad
DO
2915 return '';
2916 else
2917 return 'useDeleteBlade() failed in ' . __FUNCTION__;
2918}
f9bc186f 2919
49fb1027 2920function commitUpdateTag ($tag_id, $tag_name, $parent_id)
f9bc186f 2921{
49fb1027
DO
2922 if ($parent_id == 0)
2923 $parent_id = 'NULL';
f9bc186f 2924 global $dbxlink;
49fb1027
DO
2925 $query = "update TagTree set tag = '${tag_name}', parent_id = ${parent_id} " .
2926 "where id = ${tag_id} limit 1";
f9bc186f 2927 $result = $dbxlink->exec ($query);
590e1281
DO
2928 if ($result !== FALSE)
2929 return '';
2930 elseif ($dbxlink->errorCode() == 23000)
2931 return "name '${tag_name}' is already used";
2932 else
49fb1027 2933 return 'SQL query failed in ' . __FUNCTION__;
f9bc186f
DO
2934}
2935
01b6b4d6
DO
2936// Drop the whole chain stored.
2937function destroyTagsForEntity ($entity_realm, $entity_id)
aedf18af
DO
2938{
2939 global $dbxlink;
120e9ddd 2940 $query = "delete from TagStorage where entity_realm = '${entity_realm}' and entity_id = ${entity_id}";
aedf18af
DO
2941 $result = $dbxlink->exec ($query);
2942 if ($result === NULL)
2943 return FALSE;
2944 else
2945 return TRUE;
2946}
2947
01b6b4d6
DO
2948// Drop only one record. This operation doesn't involve retossing other tags, unlike when adding.
2949function deleteTagForEntity ($entity_realm, $entity_id, $tag_id)
2950{
2951 global $dbxlink;
120e9ddd 2952 $query = "delete from TagStorage where entity_realm = '${entity_realm}' and entity_id = ${entity_id} and tag_id = ${tag_id}";
01b6b4d6
DO
2953 $result = $dbxlink->exec ($query);
2954 if ($result === NULL)
2955 return FALSE;
2956 else
2957 return TRUE;
2958}
2959
351c0966 2960// Push a record into TagStorage unconditionally.
3355ca56 2961function addTagForEntity ($realm = '', $entity_id, $tag_id)
eb6ea26f 2962{
3355ca56
DO
2963 if (empty ($realm))
2964 return FALSE;
eb6ea26f
DO
2965 return useInsertBlade
2966 (
2967 'TagStorage',
2968 array
2969 (
120e9ddd
DO
2970 'entity_realm' => "'${realm}'",
2971 'entity_id' => $entity_id,
eb6ea26f
DO
2972 'tag_id' => $tag_id,
2973 )
2974 );
2975}
2976
351c0966 2977// Add records into TagStorage, if this makes sense (IOW, they don't appear
abef7149
DO
2978// on the implicit list already). Then remove any other records, which
2979// appear on the "implicit" side of the chain. This will make sure,
351c0966
DO
2980// that both the tag base is still minimal and all requested tags appear on
2981// the resulting tag chain.
abef7149
DO
2982// Return TRUE, if any changes were committed.
2983function rebuildTagChainForEntity ($realm, $entity_id, $extrachain = array())
2984{
2985 // Put the current explicit sub-chain into a buffer and merge all tags from
2986 // the extra chain, which aren't there yet.
2987 $newchain = $oldchain = loadEntityTags ($realm, $entity_id);
2988 foreach ($extrachain as $extratag)
2989 if (!tagOnChain ($extratag, $newchain))
2990 $newchain[] = $extratag;
2991 // Then minimize the working buffer and check if it differs from the original
2992 // chain we started with. If it is so, save the work and signal the upper layer.
2993 $newchain = getExplicitTagsOnly ($newchain);
2994 if (tagChainCmp ($oldchain, $newchain))
2995 {
01b6b4d6 2996 destroyTagsForEntity ($realm, $entity_id);
abef7149
DO
2997 foreach ($newchain as $taginfo)
2998 addTagForEntity ($realm, $entity_id, $taginfo['id']);
2999 return TRUE;
3000 }
3001 return FALSE;
351c0966
DO
3002}
3003
3004// Presume, that the target record has no tags attached.
3005function produceTagsForLastRecord ($realm, $tagidlist, $last_insert_id = 0)
3006{
3007 if (!count ($tagidlist))
c63a8d6e
DO
3008 return '';
3009 if (!$last_insert_id)
3010 $last_insert_id = lastInsertID();
3011 $errcount = 0;
abef7149 3012 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagidlist)) as $taginfo)
cdb7e75d 3013 if (addTagForEntity ($realm, $last_insert_id, $taginfo['id']) == FALSE)
c63a8d6e
DO
3014 $errcount++;
3015 if (!$errcount)
3016 return '';
3017 else
3018 return "Experienced ${errcount} errors adding tags in realm '${realm}' for entity ID == ${last_insert_id}";
3019}
3020
42023f03
DO
3021function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
3022{
3023 // $range is in x.x.x.x/x format, split into ip/mask vars
3024 $rangeArray = explode('/', $range);
3025 if (count ($rangeArray) != 2)
3026 return "Invalid IPv4 prefix '${range}'";
3027 $ip = $rangeArray[0];
3028 $mask = $rangeArray[1];
3029
3030 if (empty ($ip) or empty ($mask))
3031 return "Invalid IPv4 prefix '${range}'";
3032 $ipL = ip2long($ip);
3033 $maskL = ip2long($mask);
3034 if ($ipL == -1 || $ipL === FALSE)
3035 return 'Bad IPv4 address';
3036 if ($mask < 32 && $mask > 0)
3037 $maskL = $mask;
3038 else
3039 {
3040 $maskB = decbin($maskL);
3041 if (strlen($maskB)!=32)
3042 return 'Invalid netmask';
3043 $ones=0;
3044 $zeroes=FALSE;
3045 foreach( str_split ($maskB) as $digit)
3046 {
3047 if ($digit == '0')
3048 $zeroes = TRUE;
3049 if ($digit == '1')
3050 {
3051 $ones++;
3052 if ($zeroes == TRUE)
3053 return 'Invalid netmask';
3054 }
3055 }
3056 $maskL = $ones;
3057 }
3058 $binmask = binMaskFromDec($maskL);
3059 $ipL = $ipL & $binmask;
42023f03
DO
3060 $result = useInsertBlade
3061 (
706ce117 3062 'IPv4Network',
42023f03
DO
3063 array
3064 (
3065 'ip' => sprintf ('%u', $ipL),
3066 'mask' => "'${maskL}'",
3067 'name' => "'${name}'"
3068 )
3069 );
e782fca4
DO
3070 if ($result != TRUE)
3071 return "Could not add ${range} (already exists?).";
42023f03
DO
3072
3073 if ($is_bcast and $maskL < 31)
3074 {
3075 $network_addr = long2ip ($ipL);
3076 $broadcast_addr = long2ip ($ipL | binInvMaskFromDec ($maskL));
3077 updateAddress ($network_addr, 'network', 'yes');
3078 updateAddress ($broadcast_addr, 'broadcast', 'yes');
3079 }
351c0966 3080 return produceTagsForLastRecord ('ipv4net', $taglist);
42023f03
DO
3081}
3082
706ce117 3083// FIXME: This function doesn't wipe relevant records from IPv4Address table.
42023f03
DO
3084function destroyIPv4Prefix ($id = 0)
3085{
3086 if ($id <= 0)
3087 return __FUNCTION__ . ': Invalid IPv4 prefix ID';
706ce117 3088 if (!useDeleteBlade ('IPv4Network', 'id', $id))
42023f03 3089 return __FUNCTION__ . ': SQL query #1 failed';
01b6b4d6 3090 if (!destroyTagsForEntity ('ipv4net', $id))
42023f03
DO
3091 return __FUNCTION__ . ': SQL query #2 failed';
3092 return '';
3093}
3094
ebae41b3
DO
3095function loadScript ($name)
3096{
3097 $result = useSelectBlade ("select script_text from Script where script_name = '${name}'");
3098 $row = $result->fetch (PDO::FETCH_NUM);
4a6a28f1
DO
3099 if ($row !== FALSE)
3100 return $row[0];
3101 else
3102 return NULL;
ebae41b3
DO
3103}
3104
3105function saveScript ($name, $text)
3106{
3107 if (empty ($name))
3108 {
3109 showError ('Invalid argument');
3110 return FALSE;
3111 }
4a6a28f1 3112 // delete regardless of existence
f5575f12 3113 useDeleteBlade ('Script', 'script_name', "'${name}'");
4a6a28f1 3114 return useInsertBlade
ebae41b3
DO
3115 (
3116 'Script',
3117 array
3118 (
3119 'script_name' => "'${name}'",
3120 'script_text' => "'${text}'"
3121 )
3122 );
3123}
3124
3125function saveUserPassword ($user_id, $newp)
bcd37231 3126{
93bdb7ba 3127 $newhash = sha1 ($newp);
ebae41b3 3128 $query = "update UserAccount set user_password_hash = ${newhash} where user_id = ${user_id} limit 1";
bcd37231
DO
3129}
3130
cf6c472b
DO
3131function objectIsPortless ($id = 0)
3132{
3133 if ($id <= 0)
3134 {
3135 showError ('Invalid argument', __FUNCTION__);
3136 return;
3137 }
3138 if (($result = useSelectBlade ("select count(id) from Port where object_id = ${id}", __FUNCTION__)) == NULL)
3139 {
3140 showError ('SQL query failed', __FUNCTION__);
3141 return;
3142 }
3143 $row = $result->fetch (PDO::FETCH_NUM);
3144 $count = $row[0];
3145 $result->closeCursor();
3146 unset ($result);
81736ac1 3147 return $count === '0';
cf6c472b
DO
3148}
3149
15555995
DO
3150function recordExists ($id = 0, $realm = 'object')
3151{
3152 if ($id <= 0)
3153 return FALSE;
3154 $table = array
3155 (
3156 'object' => 'RackObject',
706ce117 3157 'ipv4net' => 'IPv4Network',
1a315491 3158 'user' => 'UserAccount',
15555995
DO
3159 );
3160 $idcol = array
3161 (
3162 'object' => 'id',
1a315491
DO
3163 'ipv4net' => 'id',
3164 'user' => 'user_id',
15555995
DO
3165 );
3166 $query = 'select count(*) from ' . $table[$realm] . ' where ' . $idcol[$realm] . ' = ' . $id;
3167 if (($result = useSelectBlade ($query, __FUNCTION__)) == NULL)
3168 {
3169 showError ('SQL query failed', __FUNCTION__);
3170 return FALSE;
3171 }
3172 $row = $result->fetch (PDO::FETCH_NUM);
3173 $count = $row[0];
3174 $result->closeCursor();
3175 unset ($result);
3176 return $count === '1';
3177}
3178
d983f70a
DO
3179function newPortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3180{
3181 if (NULL === getIPv4AddressNetworkId ($localip))
3182 return "$localip: Non existant ip";
3183 if (NULL === getIPv4AddressNetworkId ($localip))
3184 return "$remoteip: Non existant ip";
3185 if ( ($localport <= 0) or ($localport >= 65536) )
3186 return "$localport: invaild port";
3187 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
3188 return "$remoteport: invaild port";
3189
3190 $result = useInsertBlade
3191 (
706ce117 3192 'IPv4NAT',
d983f70a
DO
3193 array
3194 (
3195 'object_id' => $object_id,
3196 'localip' => "INET_ATON('${localip}')",
3197 'remoteip' => "INET_ATON('$remoteip')",
3198 'localport' => $localport,
3199 'remoteport' => $remoteport,
3200 'proto' => "'${proto}'",
3201 'description' => "'${description}'",
3202 )
3203 );
3204 if ($result)
3205 return '';
3206 else
3207 return __FUNCTION__ . ': Failed to insert the rule.';
3208}
3209
3210function deletePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
3211{
3212 global $dbxlink;
3213
3214 $query =
706ce117 3215 "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
3216 $result = $dbxlink->exec ($query);
3217 return '';
3218}
3219
3220function updatePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3221{
3222 global $dbxlink;
3223
3224 $query =
706ce117 3225 "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
3226 $result = $dbxlink->exec ($query);
3227 return '';
3228}
3229
3230function getNATv4ForObject ($object_id)
3231{
3232 $ret = array();
3233 $ret['out'] = array();
3234 $ret['in'] = array();
3235 $query =
3236 "select ".
3237 "proto, ".
3238 "INET_NTOA(localip) as localip, ".
3239 "localport, ".
3240 "INET_NTOA(remoteip) as remoteip, ".
3241 "remoteport, ".
3242 "ipa1.name as local_addr_name, " .
3243 "ipa2.name as remote_addr_name, " .
3244 "description ".
706ce117
DO
3245 "from IPv4NAT ".
3246 "left join IPv4Address as ipa1 on IPv4NAT.localip = ipa1.ip " .
3247 "left join IPv4Address as ipa2 on IPv4NAT.remoteip = ipa2.ip " .
d983f70a
DO
3248 "where object_id='$object_id' ".
3249 "order by localip, localport, proto, remoteip, remoteport";
3250 $result = useSelectBlade ($query, __FUNCTION__);
3251 $count=0;
3252 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3253 {
3254 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
3255 $ret['out'][$count][$cname] = $row[$cname];
3256 $count++;
3257 }
3258 $result->closeCursor();
3259 unset ($result);
3260
3261 $query =
3262 "select ".
3263 "proto, ".
3264 "INET_NTOA(localip) as localip, ".
3265 "localport, ".
3266 "INET_NTOA(remoteip) as remoteip, ".
3267 "remoteport, ".
706ce117 3268 "IPv4NAT.object_id as object_id, ".
d983f70a
DO
3269 "RackObject.name as object_name, ".
3270 "description ".
706ce117
DO
3271 "from ((IPv4NAT join IPv4Allocation on remoteip=IPv4Allocation.ip) join RackObject on IPv4NAT.object_id=RackObject.id) ".
3272 "where IPv4Allocation.object_id='$object_id' ".
d983f70a
DO
3273 "order by remoteip, remoteport, proto, localip, localport";
3274 $result = useSelectBlade ($query, __FUNCTION__);
3275 $count=0;
3276 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3277 {
3278 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
3279 $ret['in'][$count][$cname] = $row[$cname];
3280 $count++;
3281 }
3282 $result->closeCursor();
3283
3284 return $ret;
3285}
3286
3287// This function performs search and then calculates score for each result.
3288// Given previous search results in $objects argument, it adds new results
3289// to the array and updates score for existing results, if it is greater than
3290// existing score.
3291function mergeSearchResults (&$objects, $terms, $fieldname)
3292{
3293 global $dbxlink;
3294 $query =
b89ba713 3295 "select ro.name, label, asset_no, barcode, ro.id, dict_key as objtype_id, " .
d983f70a 3296 "dict_value as objtype_name, asset_no from RackObject as ro inner join Dictionary " .
10bac82a 3297 "on objtype_id = dict_key join Chapter on Chapter.id = Dictionary.chapter_id where Chapter.name = 'RackObjectType' and ";
d983f70a
DO
3298 $count = 0;
3299 foreach (explode (' ', $terms) as $term)
3300 {
3301 if ($count) $query .= ' or ';
b89ba713 3302 $query .= "ro.${fieldname} like '%$term%'";
d983f70a
DO
3303 $count++;
3304 }
3305 $query .= " order by ${fieldname}";
3306 $result = useSelectBlade ($query, __FUNCTION__);
d983f70a
DO
3307 $clist = array ('id', 'name', 'label', 'asset_no', 'barcode', 'objtype_id', 'objtype_name');
3308 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3309 {
3310 foreach ($clist as $cname)
3311 $object[$cname] = $row[$cname];
3312 $object['score'] = 0;
3313 $object['dname'] = displayedName ($object);
3314 unset ($object['objtype_id']);
3315 foreach (explode (' ', $terms) as $term)
3316 if (strstr ($object['name'], $term))
3317 $object['score'] += 1;
3318 unset ($object['name']);
3319 if (!isset ($objects[$row['id']]))
3320 $objects[$row['id']] = $object;
3321 elseif ($objects[$row['id']]['score'] < $object['score'])
3322 $objects[$row['id']]['score'] = $object['score'];
3323 }
3324 return $objects;
3325}
3326
09620506
DO
3327function getLostIPv4Addresses ()
3328{
f7414fa5 3329 dragon();
09620506
DO
3330}
3331
121496b6
DO
3332// Return a list of files which are not linked to the specified record. This list
3333// will be used by printSelect().
e1ae3fb4
AD
3334function getAllUnlinkedFiles ($entity_type = NULL, $entity_id = 0)
3335{
3336 if ($entity_type == NULL || $entity_id == 0)
3337 {
3338 showError ('Invalid parameters', __FUNCTION__);
3339 return NULL;
3340 }
3341 global $dbxlink;
3342 $sql =
121496b6 3343 'SELECT id, name FROM File ' .
e1ae3fb4 3344 'WHERE id NOT IN (SELECT file_id FROM FileLink WHERE entity_type = ? AND entity_id = ?) ' .
121496b6 3345 'ORDER BY name, id';
e1ae3fb4
AD
3346 $query = $dbxlink->prepare($sql);
3347 $query->bindParam(1, $entity_type);
3348 $query->bindParam(2, $entity_id);
3349 $query->execute();
3350 $ret=array();
e1ae3fb4 3351 while ($row = $query->fetch (PDO::FETCH_ASSOC))
121496b6 3352 $ret[$row['id']] = $row['name'];
e1ae3fb4
AD
3353 return $ret;
3354}
3355
e1ae3fb4
AD
3356function getFilesOfEntity ($entity_type = NULL, $entity_id = 0)
3357{
3358 if ($entity_type == NULL || $entity_id == 0)
3359 {
3360 showError ('Invalid parameters', __FUNCTION__);
3361 return NULL;
3362 }
3363 global $dbxlink;
3364 $sql =
3365 'SELECT FileLink.file_id, FileLink.id AS link_id, name, type, size, ctime, mtime, atime, comment ' .
3366 'FROM FileLink LEFT JOIN File ON FileLink.file_id = File.id ' .
3367 'WHERE FileLink.entity_type = ? AND FileLink.entity_id = ? ORDER BY name';
3368 $query = $dbxlink->prepare($sql);
3369 $query->bindParam(1, $entity_type);
3370 $query->bindParam(2, $entity_id);
3371 $query->execute();
3372 $ret = array();
3373 while ($row = $query->fetch (PDO::FETCH_ASSOC))
3374 $ret[$row['file_id']] = array (
b3567368 3375 'id' => $row['file_id'],
e1ae3fb4
AD
3376 'link_id' => $row['link_id'],
3377 'name' => $row['name'],
3378 'type' => $row['type'],
3379 'size' => $row['size'],
3380 'ctime' => $row['ctime'],
3381 'mtime' => $row['mtime'],
3382 'atime' => $row['atime'],
3383 'comment' => $row['comment'],
3384 );
3385 return $ret;
3386}
3387
3388function getFile ($file_id = 0)
3389{
3390 if ($file_id == 0)
3391 {
3392 showError ('Invalid file_id', __FUNCTION__);
3393 return NULL;
3394 }
3395 global $dbxlink;
3396 $query = $dbxlink->prepare('SELECT * FROM File WHERE id = ?');
3397 $query->bindParam(1, $file_id);
3398 $query->execute();
3399 if (($row = $query->fetch (PDO::FETCH_ASSOC)) == NULL)
3400 {
3401 showError ('Query succeeded, but returned no data', __FUNCTION__);
3402 $ret = NULL;
3403 }
3404 else
3405 {
3406 $ret = array();
3407 $ret['id'] = $row['id'];
3408 $ret['name'] = $row['name'];
3409 $ret['type'] = $row['type'];
3410 $ret['size'] = $row['size'];
3411 $ret['ctime'] = $row['ctime'];
3412 $ret['mtime'] = $row['mtime'];
3413 $ret['atime'] = $row['atime'];
3414 $ret['contents'] = $row['contents'];
3415 $ret['comment'] = $row['comment'];
bed9cd76 3416 $query->closeCursor();
e1ae3fb4 3417
deb3da1b 3418 // Someone accessed this file, update atime
e1ae3fb4
AD
3419 $q_atime = $dbxlink->prepare('UPDATE File SET atime = ? WHERE id = ?');
3420 $q_atime->bindParam(1, date('YmdHis'));
3421 $q_atime->bindParam(2, $file_id);
3422 $q_atime->execute();
3423 }
e1ae3fb4
AD
3424 return $ret;
3425}
3426
3427function getFileInfo ($file_id = 0)
3428{
3429 if ($file_id == 0)
3430 {
3431 showError ('Invalid file_id', __FUNCTION__);
3432 return NULL;
3433 }
3434 global $dbxlink;
3435 $query = $dbxlink->prepare('SELECT id, name, type, size, ctime, mtime, atime, comment FROM File WHERE id = ?');
3436 $query->bindParam(1, $file_id);
3437 $query->execute();
3438 if (($row = $query->fetch (PDO::FETCH_ASSOC)) == NULL)
3439 {
3440 showError ('Query succeeded, but returned no data', __FUNCTION__);
3441 $ret = NULL;
3442 }
3443 else
3444 {
3445 $ret = array();
3446 $ret['id'] = $row['id'];
3447 $ret['name'] = $row['name'];
3448 $ret['type'] = $row['type'];
3449 $ret['size'] = $row['size'];
3450 $ret['ctime'] = $row['ctime'];
3451 $ret['mtime'] = $row['mtime'];
3452 $ret['atime'] = $row['atime'];
3453 $ret['comment'] = $row['comment'];
da3302ab 3454 $query->closeCursor();
e1ae3fb4 3455 }
e1ae3fb4
AD
3456 return $ret;
3457}
3458
3459function getFileLinks ($file_id = 0)
3460{
3461 if ($file_id <= 0)
3462 {
3463 showError ('Invalid file_id', __FUNCTION__);
3464 return NULL;
3465 }
3466
3467 global $dbxlink;
8bc5d1e4 3468 $query = $dbxlink->prepare('SELECT * FROM FileLink WHERE file_id = ? ORDER BY entity_type, entity_id');
e1ae3fb4
AD
3469 $query->bindParam(1, $file_id);
3470 $query->execute();
da3302ab 3471 $rows = $query->fetchAll (PDO::FETCH_ASSOC);
e1ae3fb4 3472 $ret = array();
da3302ab 3473 foreach ($rows as $row)
e1ae3fb4
AD
3474 {
3475 // get info of the parent
3476 switch ($row['entity_type'])
3477 {
3478 case 'ipv4net':
3479 $page = 'ipv4net';
3480 $id_name = 'id';
3481 $parent = getIPv4NetworkInfo($row['entity_id']);
3482 $name = sprintf("%s (%s/%s)", $parent['name'], $parent['ip'], $parent['mask']);
3483 break;
3484 case 'ipv4rspool':
3854af78 3485 $page = 'ipv4rspool';
e1ae3fb4
AD
3486 $id_name = 'pool_id';
3487 $parent = getRSPoolInfo($row['entity_id']);
3488 $name = $parent['name'];
3489 break;
3490 case 'ipv4vs':
3491 $page = 'ipv4vs';
3492 $id_name = 'vs_id';
3493 $parent = getVServiceInfo($row['entity_id']);
3494 $name = $parent['name'];
3495 break;
3496 case 'object':
3497 $page = 'object';
3498 $id_name = 'object_id';
3499 $parent = getObjectInfo($row['entity_id']);
7ddbcf59 3500 $name = $parent['dname'];
e1ae3fb4
AD
3501 break;
3502 case 'rack':
3503 $page = 'rack';
3504 $id_name = 'rack_id';
3505 $parent = getRackData($row['entity_id']);
3506 $name = $parent['name'];
3507 break;
3508 case 'user':
3509 $page = 'user';
3510 $id_name = 'user_id';
b82cce3f
DO
3511 $userinfo = getUserInfo ($row['entity_id']);
3512 $name = $userinfo['user_name'];
e1ae3fb4
AD
3513 break;
3514 }
3515
17d95c32
AD
3516 // name needs to have some value for hrefs to work
3517 if (empty($name))
3518 $name = sprintf("[Unnamed %s]", formatEntityName($row['entity_type']));
3519
e1ae3fb4
AD
3520 $ret[$row['id']] = array(
3521 'page' => $page,
3522 'id_name' => $id_name,
3523 'entity_type' => $row['entity_type'],
3524 'entity_id' => $row['entity_id'],
3525 'name' => $name
3526 );
3527 }
3528 return $ret;
3529}
3530
3531// Return list of possible file parents along with the number of children.
3532// Used on main Files listing page.
3533function getFileLinkInfo ()
3534{
3535 global $dbxlink;
3536 $query = 'SELECT entity_type, COUNT(*) AS count FROM FileLink GROUP BY entity_type';
3537
3538 $result = useSelectBlade ($query, __FUNCTION__);
3539 $ret = array();
3540 $ret[0] = array ('entity_type' => 'all', 'name' => 'ALL files');
3541 $clist = array ('entity_type', 'name', 'count');
3542 $total = 0;
3543 $i=2;
3544 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3545 if ($row['count'] > 0)
3546 {
3547 $total += $row['count'];
3548 $row['name'] = formatEntityName ($row['entity_type']);
3549 foreach ($clist as $cname)
3550 $ret[$i][$cname] = $row[$cname];
3551 $i++;
3552 }
3553 $result->closeCursor();
3554
3555 // Find number of files without any linkage
3556 $linkless_sql =
3557 'SELECT COUNT(*) ' .
3558 'FROM File ' .
3559 'WHERE id NOT IN (SELECT file_id FROM FileLink)';
3560 $q_linkless = useSelectBlade ($linkless_sql, __FUNCTION__);
3561 $ret[1] = array ('entity_type' => 'no_links', 'name' => 'Files w/no links', 'count' => $q_linkless->fetchColumn ());
3562 $q_linkless->closeCursor();
3563
3564 // Find total number of files
3565 $total_sql = 'SELECT COUNT(*) FROM File';
3566 $q_total = useSelectBlade ($total_sql, __FUNCTION__);
3567 $ret[0]['count'] = $q_total->fetchColumn ();
3568 $q_total->closeCursor();
3569
3570 ksort($ret);
3571 return $ret;
3572}
3573
3574function commitAddFile ($name, $type, $size, $contents, $comment)
3575{
3576 $now = date('YmdHis');
3577
3578 global $dbxlink;
3579 $query = $dbxlink->prepare('INSERT INTO File (name, type, size, ctime, mtime, atime, contents, comment) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
3580 $query->bindParam(1, $name);
3581 $query->bindParam(2, $type);
3582 $query->bindParam(3, $size);
3583 $query->bindParam(4, $now);
3584 $query->bindParam(5, $now);
3585 $query->bindParam(6, $now);
3586 $query->bindParam(7, $contents, PDO::PARAM_LOB);
3587 $query->bindParam(8, $comment);
3588
3589 $result = $query->execute();
3590
3591
3592 if ($result)
3593 return '';
590e1281 3594 elseif ($query->errorCode() == 23000)
13edfa1c 3595 return "commitAddFile: File named '${name}' already exists";
e1ae3fb4
AD
3596 else
3597 return 'commitAddFile: SQL query failed';
3598}
3599
4a2c6c6b 3600function commitLinkFile ($file_id, $entity_type, $entity_id)
e1ae3fb4
AD
3601{
3602 global $dbxlink;
3603 $query = $dbxlink->prepare('INSERT INTO FileLink (file_id, entity_type, entity_id) VALUES (?, ?, ?)');
3604 $query->bindParam(1, $file_id);
4a2c6c6b
AD
3605 $query->bindParam(2, $entity_type);
3606 $query->bindParam(3, $entity_id);
e1ae3fb4
AD
3607
3608 $result = $query->execute();
3609
3610 if ($result)
3611 return '';
3612 else
3613 return 'commitLinkFile: SQL query failed';
3614}
3615
f8874cdb 3616function commitReplaceFile ($file_id = 0, $contents)
fd1fb420
AD
3617{
3618 if ($file_id == 0)
3619 {
3620 showError ('Not all required args are present.', __FUNCTION__);
3621 return FALSE;
3622 }