Update for racktables 0.20.7
[racktables-contribs] / local_copy_object.php
1 <?php
2
3
4 // I need this in local.php
5 define ('TABLE_BORDER', 1);
6 // require_once "local_copy_object.php";
7 // (c)2011 Manon Goo <manon@dg-i.net>
8
9 $tab['object']['objectcopier'] = 'Object Copier ';
10 $tabhandler['object']['objectcopier'] = 'localfunc_ObjectCopier';
11 // $ophandler['object']['objectcopier']['updateobjectcopier'] = 'updateconfig_ObjectCopier';
12 $ophandler['object']['objectcopier']['copyLotOfObjects'] = 'copyLotOfObjects';
13
14 function amplifyCell_object_Backend_Port (&$record, $dummy = NULL)
15 {
16 switch ($record['realm'])
17 {
18 case 'object':
19 $record['BackendPorts'] = getObjectBackendPortsAndLinks ($record['id']);
20 break;
21 default:
22 }
23 }
24
25 function getObjectBackendPortsAndLinks ($object_id)
26 {
27 $ret = fetchBackendPortList ("Port.object_id = ?", array ($object_id));
28 return sortPortList ($ret, TRUE);
29 }
30
31 function fetchBackendPortList ($sql_where_clause, $query_params = array())
32 {
33 $query = <<<END
34 SELECT
35 Port.id,
36 Port.name,
37 Port.object_id,
38 Object.name AS object_name,
39 Port.l2address,
40 Port.label,
41 Port.reservation_comment,
42 Port.iif_id,
43 Port.type AS oif_id,
44 (SELECT PortInnerInterface.iif_name FROM PortInnerInterface WHERE PortInnerInterface.id = Port.iif_id) AS iif_name,
45 (SELECT Dictionary.dict_value FROM Dictionary WHERE Dictionary.dict_key = Port.type) AS oif_name,
46 IF(lba.porta, lba.cable, lbb.cable) AS cableid,
47 IF(lba.porta, pa.id, pb.id) AS remote_id,
48 IF(lba.porta, pa.name, pb.name) AS remote_name,
49 IF(lba.porta, pa.object_id, pb.object_id) AS remote_object_id,
50 IF(lba.porta, oa.name, ob.name) AS remote_object_name,
51 (SELECT COUNT(*) FROM PortLog WHERE PortLog.port_id = Port.id) AS log_count,
52 PortLog.user,
53 UNIX_TIMESTAMP(PortLog.date) as time
54 FROM
55 Port
56 INNER JOIN Object ON Port.object_id = Object.id
57 LEFT JOIN LinkBackend AS lba ON lba.porta = Port.id
58 LEFT JOIN Port AS pa ON pa.id = lba.portb
59 LEFT JOIN Object AS oa ON pa.object_id = oa.id
60 LEFT JOIN LinkBackend AS lbb on lbb.portb = Port.id
61 LEFT JOIN Port AS pb ON pb.id = lbb.porta
62 LEFT JOIN Object AS ob ON pb.object_id = ob.id
63 LEFT JOIN PortLog ON PortLog.id = (SELECT id FROM PortLog WHERE PortLog.port_id = Port.id ORDER BY date DESC LIMIT 1)
64 WHERE
65 $sql_where_clause
66 END;
67
68 $result = usePreparedSelectBlade ($query, $query_params);
69 $ret = array();
70 while ($row = $result->fetch (PDO::FETCH_ASSOC))
71 {
72 $row['l2address'] = l2addressFromDatabase ($row['l2address']);
73 $row['linked'] = isset ($row['remote_id']) ? 1 : 0;
74
75 // last changed log
76 $row['last_log'] = array();
77 if ($row['log_count'])
78 {
79 $row['last_log']['user'] = $row['user'];
80 $row['last_log']['time'] = $row['time'];
81 }
82 unset ($row['user']);
83 unset ($row['time']);
84
85 $ret[] = $row;
86 }
87 return $ret;
88 }
89
90
91 function varDumpToString ($var)
92 {
93 ob_start();
94 var_dump($var);
95 $result = ob_get_clean();
96 return $result;
97 }
98
99 function localfunc_ObjectCopier($object_id)
100 {
101 $object = spotEntity ('object', $object_id );
102 amplifyCell($object);
103 global $virtual_obj_types, $tagtree, $taglist, $target_given_tags;
104 $typelist = readChapter (CHAP_OBJTYPE, 'o');
105 $typelist[0] = 'select type...';
106 $typelist = cookOptgroups ($typelist);
107 $max = getConfigVar ('MASSCOUNT');
108 $tabindex = 100;
109
110 echo "\n";
111 echo "\n<!-- printOpFormIntro ('copyLotOfObjects') -->\n";
112 printOpFormIntro ('copyLotOfObjects');
113 echo "\n";
114 startPortlet ('Make many copies of this object');
115 echo "\n" . sprintf('<table border=%s align=center>', TABLE_BORDER);
116 echo "\n" . '<tr><th align=left>name or "name","label","asset_no" (no csv escaping)<br><br>';
117 echo 'Example:<br> "server.example.com","server.example.com","12345"<br>www.example.com<br>testmachine<br>';
118 echo '</th><th>Copy Tags</th></tr>';
119 //echo "<tr><td><input type=submit name=got_very_fast_data value='Go!'></td><td></td></tr>\n";
120 echo "\n" . "<tr><td valign=top ><textarea name=namelist cols=60 rows=35>\n</textarea></td>";
121 echo "<td valign=top>";
122 printf ("<input type=hidden name=global_type_id value='%s'>\n", $object['objtype_id']);
123 //renderCopyEntityTagsPortlet ('Tag tree', $tagtree, $target_given_tags, $etype_by_pageno[$pageno]);
124 renderCopyEntityTags($object);
125 echo "</td></tr>";
126 echo "<tr><td colspan=2><input type=submit name=got_very_fast_data value='Go!'></td></tr></table>\n";
127 echo "</form>\n";
128 finishPortlet();
129
130 }
131
132 function copyLotOfObjects()//$template_object)
133 {
134 global $dbxlink;
135 $dbrollback = 0;
136 if (! $dbxlink->beginTransaction() )
137 throw new RTDatabaseError ("can not start transaction");
138 // do we need this ?
139 $log = emptyLog();
140 $taglist = isset ($_REQUEST['taglist']) ? $_REQUEST['taglist'] : array();
141 assertUIntArg ('global_type_id', TRUE);
142 assertStringArg ('namelist', TRUE);
143 $global_type_id = $_REQUEST['global_type_id'];
144 $source_object_id = $_REQUEST['object_id'];
145 $source_object = spotEntity ('object', $source_object_id);
146 amplifyCell($source_object);
147 if ( function_exists ( 'amplifyCell_object_Backend_Port' ) )
148 {
149 amplifyCell_object_Backend_Port($source_object);
150 }
151 if ($global_type_id == 0 or !strlen ($_REQUEST['namelist']))
152 {
153 // Log something reasonable with showError Here
154 // We do not have names to copy our object to !
155 // Pls check what makes $global_type_id == 0 an error
156 $log = mergeLogs ($log, oneLiner (186));
157 return ;
158 }
159 // The name extractor below was stolen from ophandlers.php:addMultiPorts()
160 $names1 = explode ("\n", $_REQUEST['namelist']);
161 $names2 = array();
162 foreach ($names1 as $line)
163 {
164 $parts = explode ('\r', $line);
165 reset ($parts);
166 if (!strlen ($parts[0]))
167 continue;
168 else
169 $names2[] = rtrim ($parts[0]);
170 }
171 foreach ($names2 as $name_or_csv)
172 {
173 $label = '';
174 $asset_no = '';
175 $object_name = '';
176 $regexp='/^\"([^\"]*)\","([^\"]*)\","([^\"]*)\"/';
177 $object_name_or_csv = htmlspecialchars_decode($name_or_csv, ENT_QUOTES);
178 // error_log( "$regexp $object_name" );
179 if (preg_match($regexp, $object_name_or_csv, $matches) )
180 {
181 $object_name = $matches[1];
182 $label = $matches[2];
183 $asset_no = $matches[3];
184 }
185 else
186 $object_name = $name_or_csv;
187 try
188 {
189 $object_id = commitAddObject ($object_name, $label, $global_type_id, $asset_no, $taglist);
190 if (!$object_id)
191 throw new RTDatabaseError("could not create $object_name");
192 $info = spotEntity ('object', $object_id);
193 amplifyCell ($info);
194 foreach ($source_object['ports'] as $source_port)
195 {
196 $update_port=0;
197 foreach ($info['ports'] as $new_port)
198 {
199 if ($new_port['name'] == $source_port['name'] )
200 {
201 commitUpdatePort ($object_id, $new_port['id'], $new_port['name'], $new_port['oif_id'], $source_port['label'], "" );
202 $update_port=1;
203 }
204 }
205 if ($update_port)
206 true;
207 else
208 commitAddPort ( $object_id, $source_port['name'], sprintf("%s-%s", $source_port['iif_id'], $source_port['oif_id']), $source_port['label'], "" );
209 }
210 // Copy Backendlinks only start if we ghave function linkmgmt_linkPorts from linkmgmt.php
211 if ( function_exists ( 'amplifyCell_object_Backend_Port' ) && function_exists ('linkmgmt_linkPorts') )
212 {
213 $info = spotEntity ('object', $object_id);
214 amplifyCell ($info);
215 amplifyCell_object_Backend_Port($info);
216
217 /* showError( '<div align="left"><pre>\n===== Source Object ======\n\n' .
218 varDumpToString ( $source_object ) .
219 '\n\n===== New Object ======\n\n' .
220 varDumpToString ( $info ) . '</pre></div>' );
221 */
222 $name_by_id = array();
223 foreach ($info['BackendPorts'] as $new_be_port)
224 {
225 $name_by_id[$new_be_port['name']] = $new_be_port['id'];
226 }
227
228 $linked_ports = array();
229 foreach ($source_object['BackendPorts'] as $source_be_port)
230 {
231 if ( $source_be_port['object_id'] == $source_be_port['remote_object_id'] )
232 {
233 // We have a Port that has the own object as remote object we want to copy this type of Linko
234 // We have backend Links
235 $new_be_port_a = $name_by_id[$source_be_port['name']] ;
236 $new_be_port_b = $name_by_id[$source_be_port['remote_name']] ;
237 if ( $new_be_port_a && $new_be_port_b && ! array_key_exists($new_be_port_a, $linked_ports ) && ! array_key_exists($new_be_port_b, $linked_ports ) )
238 {
239 // error_log ( sprintf ('new_be_port_a %s // new_be_port_b %s // cableid %s', $new_be_port_a , $new_be_port_b, $source_be_port['cableid'] ));
240 $ret_val = linkmgmt_linkPorts( $new_be_port_a , $new_be_port_b , 'back', $source_be_port['cableid'] );
241 // error_log ( sprintf (' linkmgmt_linkPorts ret val: "%s" ', $ret_val)) ;
242 if ($ret_val)
243 {
244 throw new RTDatabaseError("could not copy Backend Links for $object_name because: $ret_val");
245 }
246 else
247 {
248 $linked_ports[$new_be_port_a] = True;
249 $linked_ports[$new_be_port_b] = True;
250 }
251 }
252 }
253 }
254 }
255 // Copy attributes
256 foreach (getAttrValues ($source_object_id) as $record)
257 {
258 $value = $record['value'];
259 switch ($record['type'])
260 {
261 case 'uint':
262 case 'float':
263 case 'string':
264 $value = $record['value'];
265 break;
266 case 'dict':
267 $value = $record['key'];
268 break;
269 default:
270 }
271
272 if (permitted (NULL, NULL, NULL, array (array ('tag' => '$attr_' . $record['id'] ))))
273 if (empty($value))
274 commitUpdateAttrValue ($object_id, $record['id'] );
275 else
276 commitUpdateAttrValue ($object_id, $record['id'], $value ) ;
277 else
278 showError ('Permission denied, "' . $record['id'] . '"can not be set');
279
280 }
281
282 //$log = mergeLogs ($log, oneLiner (5, array ('<a href="' .
283 // makeHref (array ('page' => 'object', 'tab' => 'default', 'object_id' => $object_id)) .
284 // '">' . $info['dname'] . '</a>'))
285 //);
286 showSuccess (sprintf ("Copied Object %s ; new Object: %s", $source_object['name'] , formatPortLink($object_id, $info['dname'], 1, '', '')) );
287 }
288 catch (RTDatabaseError $e)
289 {
290 error_log("rolling back DB");
291 $dbrollback = 1;
292 $dbxlink->rollBack();
293 $log = mergeLogs ($log, oneLiner (147, array ($object_name)));
294 throw new RTDatabaseError ( $e->getMessage() . sprintf(' (%s)', $name_or_csv ));
295 }
296 }
297 if (! $dbrollback )
298 $dbxlink->commit();
299 // return buildWideRedirectURL ($log);
300 }
301
302 //MOD
303 //MOD
304 //MOD
305 function renderCopyEntityTagsPortlet ($title, $tags, $preselect, $realm)
306 {
307 startPortlet ($title);
308 echo '<a class="toggleTreeMode" style="display:none" href="#"></a>';
309 echo '<table border=0 cellspacing=0 cellpadding=1 align=center class="tagtree">';
310 printTagCheckboxTable ('taglist', $preselect, array(), $tags, $realm);
311 echo '<tr><td class=tdleft>';
312 //echo "</form></td><td class=tdright>";
313 echo '</td></tr></table>';
314 finishPortlet();
315 }
316
317 function renderCopyEntityTags ($entity_id)
318 {
319 global $tagtree, $taglist, $target_given_tags, $pageno, $etype_by_pageno;
320 echo '<table border=0 width="10%"><tr>';
321
322 if (count ($taglist) > getConfigVar ('TAGS_QUICKLIST_THRESHOLD'))
323 {
324 $minilist = getTagChart (getConfigVar ('TAGS_QUICKLIST_SIZE'), $etype_by_pageno[$pageno], $target_given_tags);
325 // It could happen, that none of existing tags have been used in the current realm.
326 if (count ($minilist))
327 {
328 $js_code = "tag_cb.setTagShortList ({";
329 $is_first = TRUE;
330 foreach ($minilist as $tag)
331 {
332 if (! $is_first)
333 $js_code .= ",";
334 $is_first = FALSE;
335 $js_code .= "\n\t${tag['id']} : 1";
336 }
337 $js_code .= "\n});\n$(document).ready(tag_cb.compactTreeMode);";
338 addJS ('js/tag-cb.js');
339 addJS ($js_code, TRUE);
340 }
341 }
342
343 // do not do anything about empty tree, trigger function ought to work this out
344 echo '<td class=pcright>';
345 renderCopyEntityTagsPortlet ('', $tagtree, $target_given_tags, $etype_by_pageno[$pageno]);
346 echo '</td>';
347
348 echo '</tr></table>';
349 }
350 function mergeLogs ($log1, $log2)
351 {
352 $ret = emptyLog();
353 $ret['m'] = array_merge ($log1['m'], $log2['m']);
354 return $ret;
355 }
356
357
358
359 function emptyLog ()
360 {
361 return array
362 (
363 'v' => 2,
364 'm' => array()
365 );
366 }
367 function oneLiner ($code, $args = array())
368 {
369 $ret = emptyLog();
370 $ret['m'][] = count ($args) ? array ('c' => $code, 'a' => $args) : array ('c' => $code);
371 return $ret;
372 }
373 ?>