Code

Don't copy over subobjects in subreleases if their
[gosa.git] / trunk / gosa-plugins / fai / admin / fai / class_FAI.inc
1 <?php
3 define("DEBUG_FAI_FUNC",FALSE);
6 class FAI
7 {
9   /* TEST PHASE .... */
11   static function get_all_objects_for_given_object($dn,$filter,$detailed = false)
12   {
13     $res  = FAI::get_all_objects_for_given_base($dn,$filter,$detailed);
14     $name = preg_replace("/,ou=.*$/","",$dn);
15     $entries = array();
16     foreach($res as $entry_dn => $data){
17       if(!preg_match("/,".$name.",/",$entry_dn)) continue;
18       $entries[$entry_dn] = $data; 
19     }
20     return($entries);
21   }
26   /* Returns all object for the given release.
27      This function resolves the releases  
28      from base up to the given dn.
29    */
30   static function get_all_objects_for_given_base($Current_DN,$filter,$detailed = false)
31   {
32     global $config;
33     $ldap = $config->get_ldap_link();
34     $ldap->cd($config->current['BASE']);
35     $res = array();
36     $tmp = array();
38     if(!FAI::is_release_department($Current_DN)) {
39 #      return($res);
40     }
42     /* Collect some basic informations and initialize some variables */ 
43     $base_release       = FAI::get_release_dn($Current_DN);
44     $previous_releases  = array_reverse(FAI::get_previous_releases_of_this_release($base_release,true));
46     $ldap->cat($base_release);
47     $attrs = $ldap->fetch();
48     $FAIstate = "branch";
49     if(isset($attrs['FAIstate'][0])){
50       $FAIstate = $attrs['FAIstate'][0];
51     }
53     /* We must also include the given release dn */
54     $previous_releases[] = $base_release;
56     /* Walk through all releases */
57     foreach($previous_releases as $release){
59       /* Get fai departments */
60       $deps_to_search = FAI::get_FAI_departments($release); 
62       /* For every single department  (ou=hoos,ou ..) */
63       foreach($deps_to_search as $fai_base){
65         /* Ldap search for fai classes specified in this release */
66         $attributes  = array("dn","objectClass","FAIstate","cn");
67         $res_tmp = get_list($filter,"fai",$fai_base,$attributes,GL_SUBSEARCH | GL_SIZELIMIT);
69         /* check the returned objects, and add/replace them in our return variable */
70         foreach($res_tmp as $attr){
72           $buffer = array();
73           $name = preg_replace("/".preg_quote($release, '/')."/i","",$attr['dn']);
75           if(isset($attr['FAIstate'][0])){
76             if(preg_match("/removed$/",$attr['FAIstate'][0])){
77               if(isset($res[$name])){
78                 unset($res[$name]);
79               }
80               continue;
81             }
82           }
84           /* Seems to be an inherited class, apply current FAIstate to this classes 
85            */
86           if(!preg_match("/".preg_quote($base_release, '/')."$/i",$attr['dn'])){
87             $buffer['FAIstate'] = $FAIstate; 
88           }else{
90             /* Seems to be created within this release department.
91                This indicates - it can't be of state "freeze"
92              */             
93             if(isset($attr['FAIstate'])){
94               $buffer['FAIstate'] = $attr['FAIstate'][0];
95             }else{
96               $buffer['FAIstate'] = "branch"; 
97             }
98           }
100           /* In detailed mode are some additonal informations visible */
101           if($detailed){
103             /* Create list of parents */
104             if(isset($res[$name])){
105               $buffer = $res[$name];
106               $buffer['parents'][] = $res[$name]['dn'];
107             }else{
108               $buffer['parents'] = array();
109             }
111             /* Append objectClass to resulsts */
112             foreach($attributes as $val){
113               if(isset($attr[$val])){
114                 $buffer[$val] = $attr[$val];
115               }
116             }
117             unset($buffer['objectClass']['count']);
118           }
120           /* Add this object to our list */
121           $buffer['dn']           = $attr['dn'];
122           $res[$name] = $buffer;
123         }
124       }
125     }
126     return($res);
127   }
130   /* Return all relevant FAI departments */
131   static function get_FAI_departments($suffix = "")
132   {
133     $arr = array("hooks","scripts","disk","packages","profiles","templates","variables");
134     $tmp = array();
135     if(preg_match("/^,/",$suffix)){
136       $suffix = preg_replace("/^,/","",$suffix);
137     }
138     foreach($arr as $name){
139       if(empty($suffix)){
140         $tmp[$name] = "ou=".$name;
141       }else{
142         $tmp[$name] = "ou=".$name.",".$suffix;
143       }
144     }
145     return($tmp);
146   }
149   /* Return all releases within the given base */
150   static function get_all_releases_from_base($dn,$appendedName=false)
151   {
152     global $config;
154     if(!preg_match("/".preg_quote(get_ou('faiBaseRDN'), '/')."/",$dn)){
155       $base = get_ou('faiBaseRDN').$dn;
156     }else{
157       $base = $dn;
158     }
159     $res = array();  
161     $ldap = $config->get_ldap_link();
162     $ldap->cd($base);
163     $ldap->search("(objectClass=FAIbranch)",array("ou","dn"));
164     while($attrs = $ldap->fetch()){
165       if($appendedName){
166         $res[$attrs['dn']] = convert_department_dn(preg_replace("/,".preg_quote(get_ou('faiBaseRDN'), '/').".*$/","",$attrs['dn']));
167       }else{
168         $res[$attrs['dn']] = $attrs['ou'][0];
169       }
170     }
171     return($res);
172   }
175   /* Add this object to list of objects, that must be checked for release saving */
176   static function prepare_to_save_FAI_object($Current_DN,$objectAttrs,$removed = false)
177   {
178     /* Get ldap object */  
179     global $config;
180     $addObj['Current_DN'] = $Current_DN;
181     $addObj['objectAttrs']= $objectAttrs;
182     $addObj['removed']    = $removed;
183     $addObj['diff']       = TRUE;
185     if(!$removed){
186       $ldap = $config->get_ldap_link();
187       $ldap->cd($config->current['BASE']);
188       $parent_dn = FAI::get_parent_object($Current_DN);
190       /* Get some basic informations */
191       $parent_obj   = FAI::get_parent_release_object($Current_DN);
192       /* Check whether parent object is removed, do not create object in this case */
193       if(!empty($parent_obj) && !FAI::parent_is_removed($Current_DN)){
194         $ldap->cat($parent_obj,array("*"));
195         $attrs = FAI::                           prepare_ldap_fetch_to_be_saved($ldap->fetch());
197         if(!FAI::array_diff_FAI( $attrs,$objectAttrs)){
198           $addObj['diff'] = FALSE;
199         }
200       } 
201     }else{
203       /* If this is the last CLASS of a specific name (e.g. DEPOTSERVER)
204           we have to remove this name from all profiles in this release.
205       */
206       $ldap = $config->get_ldap_link();
207       $ldap->cd($config->current['BASE']);
208       $obj_dn = FAI::get_parent_release_object($Current_DN,TRUE);
210       /* Dont't try to modify non FAIclasses  
211        */
212       if(!preg_match("/[^,]+,".preg_quote(get_ou("faiBaseRDN"), '/')."/",$obj_dn)){
213         trigger_error("PLEASE check fai class handling in ".__LINE__." -> ".__FILE__);        
214         echo "<br>-->".$Current_DN."<br>";
215         echo "<br>-->".$obj_dn."<br>";
216       }else{
218         /* Get source object and check if it is a base FAIclass
219          */
220         $ldap->cat($obj_dn);
221         $attrs = $ldap->fetch();
222         $classes = array("FAIprofile","FAIscript","FAIpackageList","FAIpartitionTable","FAIHook","FAIvariable","FAItemplate");
223         if(count(array_intersect($classes,$attrs['objectClass']))){
224           $cn    = $attrs['cn'][0];
226           /* Check if this is the last with this name in the current release.
227               In this case we have to remove the package name 
228               from all profiles in this release.
229            */
230           $classes = FAI::get_all_objects_for_given_base(FAI::get_release_dn($Current_DN),
231               "(&(objectClass=FAIclass)(cn=".$cn."))"); 
233           /* Check if this is the last class with this name.
234            */
235           if(count($classes) == 1){
237             /* Get all FAI Profiles 
238              */
239             $profiles = FAI::get_all_objects_for_given_base(FAI::get_release_dn($Current_DN),
240                 "(&(objectClass=FAIprofile)(FAIclass=*))"); 
242             /* Walk though all profiles and remove the source class name
243              */
244             foreach($profiles as $dn){
245               $ldap->cat($dn['dn']);
246               $attrs = $ldap->fetch();
248               $attrs = array('FAIclass' => $attrs['FAIclass'][0]);
250               /* Check if this Profile uses the source class ($cn)
251                */
252               if(preg_match("/".preg_quote($cn, '/')."/",$attrs['FAIclass'])){
253                 $attrs['FAIclass'] = preg_replace("/[ ]*".preg_quote($cn, '/')."[ ]*/i"," ",$attrs['FAIclass']);
254                 if(empty($attrs['FAIclass'])){
255                   $attrs['FAIclass'] = array();
256                 }
257                 $ldap->cd($dn['dn']);
258                 $ldap->modify($attrs);
260                 if (!$ldap->success()){
261                   msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_MOD, get_class()));
262                 }
263               }
264             }
265           }
266         }
267       }
268     }
272     $FAI_objects_to_save = session::get('FAI_objects_to_save') ;
273     $FAI_objects_to_save[$Current_DN] =  $addObj;
274     session::set('FAI_objects_to_save',$FAI_objects_to_save);
275   }
278   /* Detect differences in attribute arrays  */
279   static function array_diff_FAI($ar1,$ar2)
280   {
282     if((!isset($ar1['description'])) || (isset($ar1['description']) && (count($ar1['description']) == 0))){
283       $ar1['description'] = "";
284     }
285     if((!isset($ar2['description'])) || (isset($ar2['description']) && (count($ar2['description']) == 0))){
286       $ar2['description'] = "";
287     }
289     if(count($ar1) != count($ar2)) {
290       return (true);
291     }
293     foreach($ar1 as $key1 => $val1){
295       if((is_array($val1)) && (count($val1)==1)){
296         $ar1[$key1] = $val1[0];
297       }
299       if(isset($ar2[$key1])&&  (is_array($ar2[$key1])) && (count($ar2[$key1])==1)){
300         $val1 = $val1[0];
301         $ar2[$key1] = $ar2[$key1][0];
302       }
303     }
304     ksort($ar1);
305     ksort($ar2);
306     if(count( array_diff($ar1,$ar2)) || FAI::arr_diff($ar1,$ar2)){
307       return(true);
308     }else{
309       return(false);
310     }
311   }
314   static function arr_diff($ar1,$ar2)
315   {
316     foreach($ar1 as $ak1 => $av1){
317       if(!isset($ar2[$ak1]) || (!($av1 === $ar2[$ak1]))){
318         return(TRUE);    
319       }elseif(is_array($av1)){
320         $ret = (FAI::arr_diff($av1,$ar2[$ak1]));
321         if($ret) {
322           return(TRUE);
323         }
324       }
325     }
326     return(FALSE);
327   }
332   /* check which objects must be saved, and save them */
333   static function save_release_changes_now()
334   {
335     global $config;
336     /* Variable init*/
337     $to_save = array();
338     
339     $reload_fai_classes = FALSE;
341     /* check which objects must be saved */
342     if(!session::is_set('FAI_objects_to_save')){
343       return;
344     }
345     $FAI_objects_to_save = session::get('FAI_objects_to_save');
346     if(!is_array($FAI_objects_to_save)) {
347       print_a(array(session::get('FAI_objects_to_save')));
348       trigger_error("Can't save FAI objects, no array given.");
349       return;
350     }
351   
352     foreach($FAI_objects_to_save as $Current_DN => $object){
353       if($object['diff']){
354         $sub_name = $Current_DN;
355         while(isset($FAI_objects_to_save[$sub_name])){
356           $to_save[strlen($sub_name)][$sub_name] = $FAI_objects_to_save[$sub_name]; 
357           unset($FAI_objects_to_save[$sub_name]);
358           $sub_name = preg_replace('/^[^,]+,/', '', $sub_name);
359         }
360       }
361     }
362     session::set('FAI_objects_to_save',$FAI_objects_to_save);
364     /* Sort list of objects that must be saved, and ensure that 
365        container   objects are safed, before their childs are saved */
366     ksort($to_save);
367     $tmp = array();
368     foreach($to_save as $SubObjects){
369       foreach($SubObjects as $object){
370         $tmp[] = $object;
371       }
372     }
373     $to_save = $tmp;
376     /* Save objects and manage the correct release behavior*/
377     foreach($to_save as $save){
379       $Current_DN = $save['Current_DN'];
380       $removed    = $save['removed'];
381       $objectAttrs= $save['objectAttrs'];
383       /* Get ldap object */ 
384       $ldap = $config->get_ldap_link();
385       $ldap->cd($config->current['BASE']);
387       /* Get some basic informations */
388       $base_release       = FAI::get_release_dn($Current_DN);
389       $sub_releases       = FAI::get_sub_releases_of_this_release($base_release,true);
390       $parent_obj         = FAI::get_parent_release_object($Current_DN);
391       $following_releases = $sub_releases;
393       /* Check if given dn exists or if is a new entry */
394       $ldap->cat($Current_DN);
395       if(!$ldap->count()){
396         $is_new = true;
397       }else{
398         $is_new = false;
399       }
401       /* if parameter removed is true, we have to add FAIstate to the current attrs 
402          FAIstate should end with ...|removed after this operation */  
403       if($removed ){
404         $ldap->cat($Current_DN);
406         /* Get current object, because we must add the FAIstate ...|removed */
407         if((!$ldap->count()) && !empty($parent_obj)){
408           $ldap->cat($parent_obj);
409         }
411         /* Check if we have found a suiteable object */ 
412         if(!$ldap->count()){
413           echo "Error can't remove this object ".$Current_DN;
414           return;
415         }else{
417           /* Set FAIstate to current objectAttrs */
418           $objectAttrs = FAI::                           prepare_ldap_fetch_to_be_saved($ldap->fetch());
419           if(isset($objectAttrs['FAIstate'][0])){
420             if(!preg_match("/removed$/",$objectAttrs['FAIstate'][0])){
421               $objectAttrs['FAIstate'][0] .= "|removed";
422             }
423           }else{
424             $objectAttrs['FAIstate'][0] = "|removed";
425           }
427           /* Force reload of FAI classes */
428           $classes = array("FAIprofile","FAIscript","FAIpackageList","FAIpartitionTable","FAIHook","FAIvariable","FAItemplate");
429           if(count(array_intersect($classes,$objectAttrs['objectClass']))){
430             $reload_fai_classes = TRUE;
431           }
432         }
433       }
435       /* Check if this a leaf release or not */ 
436       if(count($following_releases) == 0 ){
438         /* This is a leaf object. It isn't inherited by any other object */    
439         if(DEBUG_FAI_FUNC) { 
440           echo "<b>Saving directly, is a leaf object</b><br> ".$Current_DN;
441           print_a($objectAttrs);
442         }
443         FAI::save_FAI_object($Current_DN,$objectAttrs);
445         /* Force reload of FAI classes */
446         $classes = array("FAIprofile","FAIscript","FAIpackageList","FAIpartitionTable","FAIHook","FAIvariable","FAItemplate");
447         if(count(array_intersect($classes,$objectAttrs['objectClass']))){
448           $reload_fai_classes = TRUE;
449         }
451       }else{
453         /* This object is inherited by some sub releases */  
455         /* Get all releases, that inherit this object */ 
456         $r = FAI::get_following_releases_that_inherit_this_object($Current_DN);
458         /* Get parent object */
459         $ldap->cat($parent_obj);
460         $parent_attrs = FAI::prepare_ldap_fetch_to_be_saved($ldap->fetch());
462         /* New objects require special handling */
463         if($is_new){
465           /* Force reload of FAI classes */
466           $classes = array("FAIprofile","FAIscript","FAIpackageList","FAIpartitionTable","FAIHook","FAIvariable","FAItemplate");
467           if(count(array_intersect($classes,$objectAttrs['objectClass']))){
468             $reload_fai_classes = TRUE;
469           }
471           /* check if there is already an entry named like this,
472              in one of our parent releases */
473           if(!empty($parent_obj)){
474             if(DEBUG_FAI_FUNC) { 
475               echo "There is already an entry named like this.</b><br>";
477               echo "<b>Saving main object</b>".$Current_DN;
478               print_a($objectAttrs);
479             }    
480             FAI::save_FAI_object($Current_DN,$objectAttrs);
482             foreach($r as $key){
483               if(DEBUG_FAI_FUNC) { 
484                 echo "<b>Saving parent to following release</b> ".$key;
485                 print_a($parent_attrs);
486               }
487               FAI::save_FAI_object($key,$parent_attrs);
488             }
489           }else{
491             if(DEBUG_FAI_FUNC) { 
492               echo "<b>Saving main object</b>".$Current_DN;
493               print_a($objectAttrs);
494             }
495             FAI::save_FAI_object($Current_DN,$objectAttrs);
497             if(isset($objectAttrs['FAIstate'])){
498               $objectAttrs['FAIstate'] .= "|removed"; 
499             }else{
500               $objectAttrs['FAIstate'] = "|removed";
501             }
503             foreach($r as $key ){
504               /* Only save removed parent objects, not their children, unless
505                  they are a child of a copy-on-write parent in a subrelease */
506               if (FAI::is_parent_object($Current_DN) || FAI::is_child_of_cow_parent($key)){
507                 if(DEBUG_FAI_FUNC) { 
508                   echo "<b>Create an empty placeholder in follwing release</b> ".$key; 
509                   print_a($objectAttrs);
510                 }
511                 FAI::save_FAI_object($key,$objectAttrs);
512               }
513             }
514           }
515         }else{
517           /* check if we must patch the follwing release */
518           if(!empty($r)){
520             foreach($r as $key ){
521               /* Only update the freeze tag if the entry actually exists. */
522               $ldap->cat($key);
523               if($ldap->count()){
524                 /* Append FAIstate tag to ensure that freezed objects stay freezed
525                  */ 
526                 $rTag = FAI::get_release_tag(FAI::get_release_dn($key));
527                 $parent_attrs['FAIstate'] = $rTag;
528               }
529               /* Don't copy over subobjects in subreleases if their parent is in "removed" state */
530               if(!FAI::parent_is_removed($key)){
531                 if(DEBUG_FAI_FUNC) { 
532                   echo "<b>Copy current objects original attributes to next release</b> ".$key;
533                   print_a($parent_attrs);
534                 }
535                 FAI::save_FAI_object($key,$parent_attrs);
536               }
537             }
538           }
540           if(DEBUG_FAI_FUNC) { 
541             echo "<b>Saving current object</b>".$parent_obj;
542             print_a($objectAttrs);
543           }
544           FAI::save_FAI_object($parent_obj,$objectAttrs);
546           if(($parent_obj != $Current_DN)){
547             msg_dialog::display(_("Error"), sprintf(_("Error, following objects should be equal '%s' and '%s'"),$parent_obj,$Current_DN), ERROR_DIALOG);
548           }
549         }
550       }
551     }
553     /* Reload GOsa si FAI DB/cache
554      */
555     if($reload_fai_classes){
556       if( class_available("DaemonEvent") && class_available("gosaSupportDaemon")){
557         $events = DaemonEvent::get_event_types(SYSTEM_EVENT | HIDDEN_EVENT);        
558         if(isset($events['TRIGGERED']['DaemonEvent_recreate_fai_release_db'])){
559           $evt = $events['TRIGGERED']['DaemonEvent_recreate_fai_release_db']; 
560           $tmp = new $evt['CLASS_NAME']($config);
561           $tmp->set_type(TRIGGERED_EVENT);
562           $tmp->add_targets(array("GOSA"));
563           $o_queue = new gosaSupportDaemon();
564           if(!$o_queue->append($tmp)){
565             msg_dialog::display(_("Service infrastructure"),msgPool::siError($o_queue->get_error()),ERROR_DIALOG);
566           }
567         }
568       }
569     }
571     session::set('FAI_objects_to_save',array());
572   }
575   /* this function will remove all unused (deleted) objects,
576      that have no parent object */
577   static function clean_up_releases($Current_DN)
578   {
579     global $config;
580     $ldap = $config->get_ldap_link();
581     $ldap->cd($config->current['BASE']);
583     /* Collect some basic informations and initialize some variables */ 
584     $base_release       = FAI::get_release_dn($Current_DN);
585     $previous_releases  = array_reverse(FAI::             get_previous_releases_of_this_release($base_release,true));
586     $sub_releases       = array_keys(FAI::get_sub_releases_of_this_release($base_release,false));
587     $Kill = array();
588     $Skip = array();
590     /* We must also include the given release dn */
591     $previous_releases[] = $base_release;
593     /* Merge parent, current and child releases into one big release to 
594        iterate over */
595     $all_releases = $previous_releases;
596     foreach($sub_releases as $sub_release){
597       $all_releases[] = $sub_release;
598     }
600     /* Walk through all releases */
601     foreach($all_releases as $release){
603       /* Get fai departments */
604       $deps_to_search = FAI::get_FAI_departments($release); 
606       /* For every single department  (ou=hoos,ou ..) */
607       foreach($deps_to_search as $fai_base){
609         /* Ldap search for fai classes specified in this release */
610         $ldap->cd($fai_base);
611         $ldap->search("(objectClass=FAIclass)",array("dn","objectClass","FAIstate"));
613         /* check the returned objects, and add/replace them in our return variable */
614         while($attr = $ldap->fetch()){
616           $buffer = array();
617 #        $name = str_ireplace($release,"",$attr['dn']);
618           $name = preg_replace("/".preg_quote($release, '/')."/i","",$attr['dn']);
620           if(isset($attr['FAIstate'][0])&&(preg_match("/removed$/",$attr['FAIstate'][0]))){
622             /* Check if this object is required somehow */    
623             if(!isset($Skip[$name])){
624               $Kill[$attr['dn']] = $attr['dn'];
625             }
626           }else{
628             /* This object is required (not removed), so do not 
629                delete any following sub releases of this object */
630             $Skip[$name] = $attr['dn'];
631           }
632         }
633       }
634     }
635     return($Kill);
636   }
639   /* Remove numeric index and 'count' from ldap->fetch result */
640   static function prepare_ldap_fetch_to_be_saved($attrs)
641   {
642     foreach($attrs as $key => $value){
643       if(is_numeric($key) || ($key == "count") || ($key == "dn")){
644         unset($attrs[$key]);
645       }
646       if(is_array($value) && isset($value['count'])){
647         unset($attrs[$key]['count']);
648       }
649     }
650     return($attrs);
651   }
654   /* Save given attrs to specified dn*/
655   static function save_FAI_object($dn,$attrs)
656   {
657     global $config;
658     $ldap = $config->get_ldap_link();
659     $ldap->cd($config->current['BASE']);
660     $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $dn));
661     $ldap->cd($dn);
663     $ui= get_userinfo();
664     FAI::tag_attrs($attrs, $dn, $ui->gosaUnitTag);
666     $ldap->cat($dn,array("dn"));
667     if($ldap->count()){
669       /* Remove FAIstate*/
670       if(!isset($attrs['FAIstate'])){
671         $attrs['FAIstate'] = array();
672       }
674       $ldap->modify($attrs);
675     }else{
677       /* Unset description if empty  */
678       if(empty($attrs['description'])){
679         unset($attrs['description']);
680       }    
682       $ldap->add($attrs);
683     }
684     if (!$ldap->success()){
685       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, 0, get_class()));
686     }
687   }
690   /* Return FAIstate freeze branch or "" for specified release department */
691   static function get_release_tag($dn)
692   {
693     global $config;
694     $ldap = $config->get_ldap_link();
695     $ldap->cd($dn);
696     $ldap->cat($dn,array("FAIstate"));
698     if($ldap->count()){
700       $attr = $ldap->fetch();
701       if(isset($attr['FAIstate'][0])){
702         if(preg_match("/freeze/",$attr['FAIstate'][0])){
703           return("freeze");
704         }elseif(preg_match("/branch/",$attr['FAIstate'][0])){
705           return("branch");
706         }
707       }
708     }
709     return("");
710   }
713   static function get_following_releases_that_inherit_this_object($dn)
714   {
715     global $config;
716     $ldap = $config->get_ldap_link();
717     $ldap->cd($config->current['BASE']);
719     $ret = array();
721     /* Get base release */
722     $base_release = FAI::get_release_dn($dn);
724     /* Get previous release dns */
725     $sub_releases = FAI::                       get_sub_releases_of_this_release($base_release);
727     /* Get dn suffix. Example  "FAIvairableEntry=keksdose,FAIvariable=Keksregal," */
728 #  $dn_suffix = str_ireplace($base_release,"",$dn);
729     $dn_suffix = preg_replace("/".preg_quote($base_release, '/')."/i","",$dn);
731     /* Check if given object also exists whitin one of these releases */
732     foreach($sub_releases as $p_release => $name){
734       $check_dn = $dn_suffix.$p_release;
736       $ldap->cat($check_dn,array("dn","objectClass"));
738       if($ldap->count()){
739         //return($ret);
740       }else{
741         $ret[$check_dn]=$check_dn;
742       }
743     }
744     return($ret);
745   }
748   /* Get previous version of the object dn */
749   static function get_parent_release_object($dn,$include_myself=true)
750   {
751     global $config;
752     $ldap = $config->get_ldap_link();
753     $ldap->cd($config->current['BASE']);
754     $previous_releases= array();
756     /* Get base release */
757     $base_release = FAI::get_release_dn($dn);
758     if($include_myself){
759       $previous_releases[] = $base_release;  
760     }
762     /* Get previous release dns */
763     $tmp = FAI::             get_previous_releases_of_this_release($base_release,true);
764     foreach($tmp as $release){
765       $previous_releases[] = $release;
766     }
768     /* Get dn suffix. Example  "FAIvairableEntry=keksdose,FAIvariable=Keksregal," */
769 #  $dn_suffix = str_ireplace($base_release,"",$dn);
770     $dn_suffix = preg_replace("/".preg_quote($base_release, '/')."/i","",$dn);
772     /* Check if given object also exists whitin one of these releases */
773     foreach($previous_releases as $p_release){
774       $check_dn = $dn_suffix.$p_release;
775       $ldap->cat($check_dn,array("dn","objectClass"));
777       if($ldap->count()){
778         return($check_dn);
779       }
780     }
781     return("");
782   }
785   /* return release names of all parent releases */
786   static function get_previous_releases_of_this_release($dn,$flat)
787   {
788     global $config;
789     $ldap = $config->get_ldap_link();
790     $ldap->cd($config->current['BASE']);
791     $ret = array();
793     /* Explode dns into pieces, to be able to build parent dns */
794     $dns_to_check = gosa_ldap_explode_dn(preg_replace("/".preg_quote(",".$config->current['BASE'], '/')."/i","",$dn));
796     if(!is_array($dns_to_check)){
797       return;  
798     }
800     /* Unset first entry which represents the given dn */
801     unset($dns_to_check['count']); 
802     unset($dns_to_check[key($dns_to_check)]);
804     /* Create dns addresses and check if this dn is a release dn */
805     $id = 0;
806     while(count($dns_to_check)){
808       /* build parent dn */
809       $new_dn = "";
810       foreach($dns_to_check as $part){
811         $new_dn .= $part.",";
812       }
813       $new_dn .= $config->current['BASE'];
815       /* check if this dn is a release */
816       if(FAI::is_release_department($new_dn)){
817         if($flat){
818           $ret[$id] = $new_dn; 
819         }else{
820           $ret = array($new_dn=>$ret); 
821         }
822         $id ++;
823       }else{
824         return($ret);
825       }
826       reset($dns_to_check);
827       unset($dns_to_check[key($dns_to_check)]);
828     }
829     return($ret);
830   } 
833   /* This function returns all sub release names, recursivly  */
834   static function get_sub_releases_of_this_release($dn,$flat = false)
835   {
836     global $config;
837     $res  = array();
838     $ldap = $config->get_ldap_link();
839     $ldap->cd($config->current['BASE']);
840     $ldap->ls("(objectClass=FAIbranch)",$dn,array("objectClass","dn","ou"));
841     while($attr = $ldap->fetch()){
843       /* Append department name */
844       if($flat){
845         $res[$attr['dn']] = $attr['ou'][0];
846       }else{
847         $res[$attr['dn']] = array();
848       }
850       /* Get sub release departments of this department */
851       if(in_array("FAIbranch",$attr['objectClass'])) {
852         if($flat){
853           $tmp = FAI::                       get_sub_releases_of_this_release($attr['dn'],$flat);
854           foreach($tmp as $dn => $value){
855             $res[$dn]=$value;
856           }
857         }else{
858           $res[$attr['dn']] = FAI::                       get_sub_releases_of_this_release($attr['dn']);
859         }
860       }
861     }
862     return($res);
863   }
866   /* Check if the given department is a release department */
867   static function is_release_department($dn)
868   {
869     global $config;
870     $ldap = $config->get_ldap_link();
871     $ldap->cd($config->current['BASE']);
872     $ldap->cat($dn,array("objectClass","ou"));
874     /* Check objectClasses and name to check if this is a release department */
875     if($ldap->count()){
876       $attrs = $ldap->fetch();
878       $ou = "";
879       if(isset($attrs['ou'][0])){
880         $ou = $attrs['ou'][0];  
881       }
883       if((in_array("FAIbranch",$attrs['objectClass'])) || ($ou == "fai")){
884         return($attrs['dn']);
885       }
886     }
887     return(false);
888   }
891   static function copy_FAI_group_releases($source_release , $destination_name, $type ="" )
892   {
893     global $config;
894     $start = microtime(TRUE);
895     $source_release = trim($source_release,"/");
897     echo "<h2>".sprintf(_("Creating group application release for %s"),$destination_name)."</h2>";
899     $sub_releases = array();
900     $source_dn = "";
901     
902     $tmp = split("\/",$source_release);
903     foreach($tmp as $part){
904       if(empty($part)){
905         continue;
906       }
907       $source_dn            = "ou=".$part.",".$source_dn;
908       $sub_releases[$part]  = $source_dn;
909     }
911     /* Get all groups */
912     $ldap =$config->get_ldap_link();
913     $ldap->cd($config->current['BASE']);
914     $ldap->search("(objectClass=posixGroup)",array("dn"));
915     $groups = array();
916     while($attrs = $ldap->fetch()){
917       $groups[$attrs['dn']] = $attrs;
918     }
920     /* Get all FAI releases, to be able to create missing group application releases 
921         with the correct type of release (FAIstate=freeze/branch).
922      */
923     $f_releases = array();
924     $ldap->cd ($config->current['BASE']);
925     $ldap->search("(objectClass=FAIbranch)",array("ou","FAIstate"));
926     while($attrs = $ldap->fetch()){
927       foreach($sub_releases as $sub_rel){
928         if(preg_match("/^".preg_quote($sub_rel.get_ou('faiBaseRDN'), '/')."/",$attrs['dn'])){
929           $f_releases[$sub_rel.get_ou('faiBaseRDN')] = $attrs;
930         }
931       }
932     }
934     /* Get all group releases */
935     $g_releases = array();
936     foreach($groups as $dn => $data){
937       $ldap->cd($dn);
938       $ldap->search("(objectClass=FAIbranch)",array("ou","FAIstate"));
939       while($attrs = $ldap->fetch()){
940         $g_releases[$attrs['dn']] = $attrs;
941       }
942     }
944     /* Check if base releases exists.
945        If they do not exist, create them and adapt FAIstate attribute from FAI releases. 
946      */
947     foreach($sub_releases as $name => $sub_rel){
949       $FAIstate = "";
950       if(isset($f_releases[$sub_rel.get_ou('faiBaseRDN')]) && isset($f_releases[$sub_rel.get_ou('faiBaseRDN')]['FAIstate'])){
951         $FAIstate = $f_releases[$sub_rel.get_ou('faiBaseRDN')]['FAIstate'][0];
952       }
954       foreach($groups as $dn => $data){
955         if(!isset($g_releases[$sub_rel.$dn])){
956           $ldap->cd($dn);
957           $r_data = array();
958           $r_data['ou'] = $name;
959           $r_data['objectClass'] = array("top","organizationalUnit","FAIbranch");
960           if(!empty($FAIstate)) {
961             $r_data['FAIstate'] = $FAIstate;
962           }
963  
964           $ldap->cd($sub_rel.$dn) ;
965           $ldap->add($r_data);
966           echo "&nbsp;<b>"._("Object").":</b> ";
967           echo sprintf(_("Adding missing group application release container %s."),substr(LDAP::fix($sub_rel.$dn),0,96))."<br>";
968           flush();
969         }
970       }
971     } 
972  
973     /* Create new release container in each group.
974      */
975     $n_data = array();
976     $n_data = array();
977     $n_data['ou'] = $destination_name;
978     $n_data['objectClass'] = array("top","organizationalUnit","FAIbranch");
979     if(!empty($type)){
980       $n_data['FAIstate'] = $type."/cow";
981     }
983     foreach($groups as $dn => $att){
984       $n_dn = "ou=".$destination_name.",".$source_dn.$dn;
985       if(!isset($g_releases[$n_dn])){
986         $ldap->cd ($n_dn);
987         $ldap->add($n_data);
988         echo "&nbsp;<b>"._("Object").":</b> ";
989         echo sprintf(_("Adding group application release container %s."),substr(LDAP::fix($n_dn),0,96))."<br>";
990         flush();
991       }
992     }
994     /* If the source release is empty, then create a new release by copying 
995         all group application menus into a new ou=$destination_name release container.
996       
997        If the source release is not empty. 
998          We detect all releases which match the source release dn and copy the contents.
999      */
1000     if(empty($source_release)){
1001       $source_dns = $groups;
1002     }else{
1003       $source_dns = array();
1004       foreach($g_releases as $dn => $data){
1005         if(preg_match("/^".preg_quote($source_dn, '/')."/",$dn)){
1006           $source_dns[$dn] = $data; 
1007         }
1008       }
1009     }
1011     /* Detect all menu object we have to copy 
1012      */
1013     $to_copy = array();
1014     foreach($source_dns as $dn => $attrs){
1015       $ldap->cd($dn);
1016       $ldap->ls("(|(objectClass=gotoSubmenuEntry)(objectClass=gotoMenuEntry))",$dn,array("dn"));
1017       while($attrs = $ldap->fetch()){
1018         $destination = preg_replace("/".preg_quote($dn, '/')."$/","ou=".$destination_name.",".$dn,$attrs['dn']);
1019         $to_copy[$attrs['dn']] = $destination;
1020       }
1021     }
1022    
1023     /* At least create the menu objects object */
1024     $plug = new plugin($config);
1025     foreach($to_copy as $source => $destination){
1026       $ldap->cat($destination);
1027       if($ldap->count()){
1028         echo "&nbsp;<b>"._("Object").":</b> ";
1029         echo sprintf(_("Could not create menu entry %s. (Already exists)."),substr(LDAP::fix($destination),0,96))."<br>";
1030         flush();
1031       }else{
1032         $plug->copy($source,$destination);
1033         echo "&nbsp;<b>"._("Object").":</b> ";
1034         echo sprintf(_("Created group application menu entry for %s."),substr(LDAP::fix($destination),0,96))."<br>";
1035         flush();
1036       }
1037     }
1038   }
1041   /*! \brief Create a new FAI branch.
1042    *  @param $sourcedn          String  The source release dn
1043    *  @param $destinationdn     String  The destination dn
1044    *  @param $destinationName   String  The name of the new release
1045    *  @param $type              String  The release type (freeze/branch)
1046    *  @param $is_first          Boolean Use to identify the first func. call when recursivly called.
1047    *  @param $depth             Integer Current depth of recursion.
1048    */
1049   static function copy_FAI_resource_recursive($sourcedn,$destinationdn,$destinationName,$type="branch",$is_first = true,$depth=0)
1050   {
1051     global $config;
1052     error_reporting(E_ALL | E_STRICT);
1053     $ldap     = $config->get_ldap_link();
1054     $basedn   = $config->current['BASE'];
1055     $delarray = array();
1057     /* The following code will output a status string
1058      *  for each handled object, in a seperate iframe.
1059      */
1062     /* Display current action information.
1063      */
1064     if($is_first){
1065       echo "<h2>".sprintf(_("Creating copy of %s"),"<i>".LDAP::fix($sourcedn)."</i>")."</h2>";
1066     }else{
1067       if(preg_match("/^ou=/",$sourcedn)){
1068         echo "<h3>"._("Processing")." <i>".LDAP::fix($destinationdn)."</i></h3>";
1069       }else{
1070         $tmp = split(",",$sourcedn);
1071         echo "&nbsp;<b>"._("Object").":</b> ";
1072         $deststr = LDAP::fix($destinationdn);
1073         if(strlen($deststr) > 96){
1074           $deststr = substr($deststr,0,96)."...";
1075         }
1076         echo $deststr."<br>";
1077       }
1078     }
1079     /* .. immediately display infos */
1080     flush();
1082     /* Check if destination entry already exists
1083      */
1084     $ldap->cat($destinationdn);
1085     if($ldap->count()){
1086       echo _("Could not create new release, the destination dn is already in use.");
1087       return;
1088     }else{
1090       $ldap->clearResult();
1092       /* Get source entry
1093        *  if it does not exist, abort here.
1094        */
1095       $ldap->cd($basedn);
1096       $ldap->cat($sourcedn);
1097       $attr = $ldap->fetch();
1098       if((!$attr) || (count($attr)) ==0) {
1099         echo _("Error while fetching source dn - aborted!");
1100         return;
1101       }
1103       /* The current object we want to create is an department.
1104        * Create the department and add the FAIbranch tag.
1105        */
1106       if(in_array("organizationalUnit",$attr['objectClass'])){
1107         $attr['dn'] = LDAP::convert($destinationdn);
1108         $ldap->cd($basedn);
1109         $ldap->create_missing_trees($destinationdn);
1110         $ldap->cd($destinationdn);
1112         /* If is first entry, append FAIbranch to department entry */
1113         if($is_first){
1114           $ldap->cat($destinationdn);
1115           $attr= $ldap->fetch();
1116           /* Filter unneeded informations */
1117           foreach($attr as $key => $value){
1118             if(is_numeric($key)) unset($attr[$key]);
1119             if(isset($attr[$key]['count'])){
1120               if(is_array($attr[$key])){
1121                 unset($attr[$key]['count']);
1122               }
1123             }
1124           }
1126           unset($attr['count']);
1127           unset($attr['dn']);
1129           /* Add marking attribute */
1130           $attr['objectClass'][] = "FAIbranch";
1131           $attr['FAIstate'] = $type;
1133           /* Add this entry */
1134           $ldap->modify($attr);
1135         }
1136       }else{
1138         /* Replicate all relevant FAI objects here.
1139          * FAI objects, Apps and Mimetypes.
1140          * Get all attributes as binary value, to ensure that Icon, File template aso
1141          *  are created correctly.
1142          */
1143         foreach($attr as $key => $value){
1145           if(in_array($key ,array("gotoLogonScript", "gosaApplicationIcon","gotoMimeIcon"))){
1146             $sr= ldap_read($ldap->cid, LDAP::fix($sourcedn), "$key=*", array($key));
1147             $ei= ldap_first_entry($ldap->cid, $sr);
1148             if ($tmp= @ldap_get_values_len($ldap->cid, $ei,$key)){
1149               $attr[$key] = $tmp;
1150             }
1151           }
1153           if(is_numeric($key)) unset($attr[$key]);
1154           if(isset($attr[$key]['count'])){
1155             if(is_array($attr[$key])){
1156               unset($attr[$key]['count']);
1157             }
1158           }
1159         }
1160         unset($attr['count']);
1161         unset($attr['dn']);
1162         if(!in_array("FAIobject",$attr['objectClass'])){
1163           $attr['objectClass'][] = "FAIobject";
1164         }
1165         $attr['FAIstate'] = $type;
1167         /* Add entry
1168          */
1169         $ldap->cd($destinationdn);
1170         $ldap->cat($destinationdn);
1172         $a = $ldap->fetch();
1173         if(!count($a)){
1174           $ldap->add($attr);
1175         }
1177         if(!$ldap->success()){
1179           /* Some error occurred */
1180           msg_dialog::display(_("Fatal error"),
1181               sprintf(_("Release creation failed due to ldap errors. Additional informations '%s'."),
1182                 $ldap->get_error()."<br>".$sourcedn."<br>".$destinationdn."<br>"),FATAL_ERROR_DIALOG);
1183           exit();
1184         }
1185       }
1186     }
1188     echo "<script language=\"javascript\" type=\"text/javascript\">scrollDown2();</script>" ;
1190     /* Prepare for recursive copy.
1191      * Get all object within the source dn and
1192      *  call the recursive copy for each.
1193      */
1194     $ldap->ls ("(objectClass=*)",$sourcedn);
1195     while ($ldap->fetch()){
1196       $deldn= $ldap->getDN();
1197       $delarray[$deldn]= strlen($deldn);
1198     }
1199     asort ($delarray);
1200     reset ($delarray);
1201     $depth ++;
1202     foreach($delarray as $dn => $bla){
1203       if($dn != $destinationdn){
1204         $ldap->cd($basedn);
1205         $item = $ldap->fetch($ldap->cat($dn));
1206         if(!in_array("FAIbranch",$item['objectClass'])){
1207           FAI::copy_FAI_resource_recursive($dn,str_replace($sourcedn,$destinationdn,$dn),$destinationName,$type,false,$depth);
1208         }
1209       }
1210     }
1211     if($is_first){
1212       echo "<p class='seperator'>&nbsp;</p>";
1213     }
1214   }
1218   /* This function returns the dn of the object release */
1219   static function get_release_dn($Current_DN)
1220   {
1221     global $config;
1222     $ldap = $config->get_ldap_link();
1223     $ldap->cd($config->current['BASE']);
1225     /* Split dn into pices */ 
1226     $dns_to_check = gosa_ldap_explode_dn(preg_replace("/".preg_quote(",".$config->current['BASE'], '/')."/i","",$Current_DN));
1228     if(!is_array($dns_to_check)){
1229       return;  
1230     }
1232     /* Use dn pieces, to create sub dns like 
1233        ou=test,ou=1,ou=0...
1234        ou=1,ou=0...
1235        ou=0... 
1236        To check which dn is our release container.
1237      */
1238     unset($dns_to_check['count']); 
1239     while(count($dns_to_check)){
1241       /* Create dn */
1242       $new_dn = "";
1243       foreach($dns_to_check as $part){
1244         $new_dn .= $part.",";
1245       }
1246       $new_dn .= $config->current['BASE'];
1248       /* Check if this dn is a release dn */
1249       if(FAI::is_release_department($new_dn)){
1250         return($new_dn);
1251       }
1253       /* Remove first element of dn pieces */
1254       reset($dns_to_check);
1255       unset($dns_to_check[key($dns_to_check)]);
1256     }
1257     return("");
1258   }
1261   static function tag_attrs(&$at, $dn= "", $tag= "", $show= false)
1262   {                                                        
1263     /* Remove tags that may already be here... */                         
1264     remove_objectClass("gosaAdministrativeUnitTag", $at);                 
1265     if (isset($at['gosaUnitTag'])){                                       
1266         unset($at['gosaUnitTag']);                                        
1267     }                                                                     
1269     /* Set tag? */
1270     if ($tag != ""){
1271       add_objectClass("gosaAdministrativeUnitTag", $at);
1272       $at['gosaUnitTag']= $tag;                         
1273     }                                                   
1275     /* Initially this object was tagged. 
1276        - But now, it is no longer inside a tagged department. 
1277        So force the remove of the tag.                        
1278        (objectClass was already removed obove)                
1279      */                                                       
1280     if($tag == ""){                     
1281       $at['gosaUnitTag'] = array();                           
1282     }                                                         
1283   }                                                           
1285   /* Returns true if this is a parent object, e.g. FAIpartitionTable, not FAIpartitionDisk */
1286   static function is_parent_object($dn)
1287   {
1288     global $config;
1289     $Current_DN = $dn;
1291     /* special case partitions, as they don't start with cn= in their DN (schema bug?) */
1292     if (preg_match('/^FAIpartitionNr=/', $Current_DN)){
1293       return false;
1294     }
1296     $parent_dn = preg_replace('/^cn=[^,.]*,/', '', $Current_DN);
1297     if (preg_match('/^cn=/', $parent_dn)) {
1298       $ldap = $config->get_ldap_link();
1299       $ldap->cd($config->current['BASE']);
1300       $ldap->cat($parent_dn);
1301       if($ldap->count()){
1302         return false;
1303       }
1304     }else{
1305       return true;
1306     }
1307   }
1309   /* Return child objects, if there are any */
1310   static function get_child_objects($dn)
1311   {
1312     global $config;
1313     $Current_DN = $dn;
1314     $children= array();
1316     if (FAI::is_parent_object($Current_DN)){
1317       $ldap = $config->get_ldap_link();
1318       $ldap->cd($dn);
1319       $ldap->search("(objectClass=FAIclass)",array("dn"));
1320       while($attrs = $ldap->fetch()){
1321         if(preg_match("/".preg_quote($Current_DN, '/')."/",$attrs['dn']) && $attrs['dn'] != $Current_DN){
1322           $children[] = $attrs['dn'];
1323         }
1324       }
1325     }
1326     return $children;
1327   }
1329   /* Get the DN of the parent object; e.g. the FAIpartitionTable of a FAIpartitionDisk.
1330      If $check is false, do not check whether the parent actually exists in LDAP */
1331   static function get_parent_object($dn, $check=true)
1332   {
1333     global $config;
1334     $Current_DN = $dn;
1335     $i = 0;
1337     $tmp_dn = $Current_DN;
1338     $parent_dn = array();
1340     /* special case partitions, as they don't start with cn= in their DN (schema bug?) */
1341     $tmp_dn = preg_replace('/^FAIpartitionNr=/', 'cn=', $tmp_dn);
1343     $tmp_dn = gosa_ldap_explode_dn($tmp_dn);
1344     while(preg_match('/^cn=/', $tmp_dn[$i])) {
1345       $i++;
1346     }
1347     /* DN part does not start with cn= anymore, remove one from the counter to get the
1348        last CN element */
1349     $i--;
1351     for ($i;$i<$tmp_dn['count'];$i++) {
1352       $parent_dn[] = trim($tmp_dn[$i]);
1353     }
1354     $parent_dn = join($parent_dn, ',');
1356     if ($parent_dn != $Current_DN){
1357       if($check){
1358         $ldap = $config->get_ldap_link();
1359         $ldap->cd($config->current['BASE']);
1360         $ldap->cat($parent_dn);
1361         if(!$ldap->count()){
1362           return "";
1363         }
1364       }
1365       return $parent_dn;
1366     }
1367     return "";
1368   }
1370   /* Check whether parent object is removed */
1371   static function parent_is_removed($dn)
1372   {
1373     global $config;
1374     $Current_DN = $dn;
1376     $ldap = $config->get_ldap_link();
1377     $parent_dn = FAI::get_parent_object($Current_DN);
1378     if ($parent_dn) { 
1379       $ldap->cd($config->current['BASE']);
1380       $ldap->cat($parent_dn);
1381       $parentObjectAttrs = FAI::prepare_ldap_fetch_to_be_saved($ldap->fetch());
1382       if(isset($parentObjectAttrs['FAIstate'][0])){
1383         if(preg_match("/removed$/",$parentObjectAttrs['FAIstate'][0])){
1384           return true;
1385         }
1386       }
1387     } 
1388     return false;
1389   }
1391   /* Check whether this is a child object of a Copy-on-Write parent */
1392   static function is_child_of_cow_parent($dn)
1393   { 
1394     global $config;
1395     $Current_DN = $dn;
1396     $parent_dn = "";
1398     if (!FAI::is_parent_object($Current_DN)){
1400       /* This is a child object; check that the parent object is not 
1401          marked as removed */
1402       $cow_parent_dn = FAI::get_parent_object($Current_DN, false);
1403       if ($cow_parent_dn && !FAI::parent_is_removed($Current_DN)){
1405         /* This is a child object, check whether the parent object in 
1406            the main release exists */
1407         $main_parent_dn = FAI::get_parent_release_object($cow_parent_dn);
1408         $ldap = $config->get_ldap_link();
1409         $ldap->cd($config->current['BASE']);
1410         $ldap->cat($main_parent_dn);
1411         if($ldap->count()){
1412           return true;
1413         }
1414       }
1415     }
1416     return false;
1417   }
1424 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1425 ?>