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