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