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