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