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