Code

Make sure CoW objects in subreleases are properly created when the main
[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               if(DEBUG_FAI_FUNC) { 
522                 echo "<b>Copy current objects original attributes to next release</b> ".$key;
523                 print_a($parent_attrs);
524               }
525              
526               /* Only update the freeze tag if the entry actually exists. */
527               $ldap->cat($key);
528               if($ldap->count()){
529                 /* Append FAIstate tag to ensure that freezed objects stay freezed
530                  */ 
531                 $rTag = FAI::get_release_tag(FAI::get_release_dn($key));
532                 $parent_attrs['FAIstate'] = $rTag;
533               }
534               FAI::save_FAI_object($key,$parent_attrs);
535             }
536           }
538           if(DEBUG_FAI_FUNC) { 
539             echo "<b>Saving current object</b>".$parent_obj;
540             print_a($objectAttrs);
541           }
542           FAI::save_FAI_object($parent_obj,$objectAttrs);
544           if(($parent_obj != $Current_DN)){
545             msg_dialog::display(_("Error"), sprintf(_("Error, following objects should be equal '%s' and '%s'"),$parent_obj,$Current_DN), ERROR_DIALOG);
546           }
547         }
548       }
549     }
551     /* Reload GOsa si FAI DB/cache
552      */
553     if($reload_fai_classes){
554       if( class_available("DaemonEvent") && class_available("gosaSupportDaemon")){
555         $events = DaemonEvent::get_event_types(SYSTEM_EVENT | HIDDEN_EVENT);        
556         if(isset($events['TRIGGERED']['DaemonEvent_recreate_fai_release_db'])){
557           $evt = $events['TRIGGERED']['DaemonEvent_recreate_fai_release_db']; 
558           $tmp = new $evt['CLASS_NAME']($config);
559           $tmp->set_type(TRIGGERED_EVENT);
560           $tmp->add_targets(array("GOSA"));
561           $o_queue = new gosaSupportDaemon();
562           if(!$o_queue->append($tmp)){
563             msg_dialog::display(_("Service infrastructure"),msgPool::siError($o_queue->get_error()),ERROR_DIALOG);
564           }
565         }
566       }
567     }
569     session::set('FAI_objects_to_save',array());
570   }
573   /* this function will remove all unused (deleted) objects,
574      that have no parent object */
575   static function clean_up_releases($Current_DN)
576   {
577     global $config;
578     $ldap = $config->get_ldap_link();
579     $ldap->cd($config->current['BASE']);
581     /* Collect some basic informations and initialize some variables */ 
582     $base_release       = FAI::get_release_dn($Current_DN);
583     $previous_releases  = array_reverse(FAI::             get_previous_releases_of_this_release($base_release,true));
584     $sub_releases       = array_keys(FAI::get_sub_releases_of_this_release($base_release,false));
585     $Kill = array();
586     $Skip = array();
588     /* We must also include the given release dn */
589     $previous_releases[] = $base_release;
591     /* Merge parent, current and child releases into one big release to 
592        iterate over */
593     $all_releases = $previous_releases;
594     foreach($sub_releases as $sub_release){
595       $all_releases[] = $sub_release;
596     }
598     /* Walk through all releases */
599     foreach($all_releases as $release){
601       /* Get fai departments */
602       $deps_to_search = FAI::get_FAI_departments($release); 
604       /* For every single department  (ou=hoos,ou ..) */
605       foreach($deps_to_search as $fai_base){
607         /* Ldap search for fai classes specified in this release */
608         $ldap->cd($fai_base);
609         $ldap->search("(objectClass=FAIclass)",array("dn","objectClass","FAIstate"));
611         /* check the returned objects, and add/replace them in our return variable */
612         while($attr = $ldap->fetch()){
614           $buffer = array();
615 #        $name = str_ireplace($release,"",$attr['dn']);
616           $name = preg_replace("/".preg_quote($release, '/')."/i","",$attr['dn']);
618           if(isset($attr['FAIstate'][0])&&(preg_match("/removed$/",$attr['FAIstate'][0]))){
620             /* Check if this object is required somehow */    
621             if(!isset($Skip[$name])){
622               $Kill[$attr['dn']] = $attr['dn'];
623             }
624           }else{
626             /* This object is required (not removed), so do not 
627                delete any following sub releases of this object */
628             $Skip[$name] = $attr['dn'];
629           }
630         }
631       }
632     }
633     return($Kill);
634   }
637   /* Remove numeric index and 'count' from ldap->fetch result */
638   static function prepare_ldap_fetch_to_be_saved($attrs)
639   {
640     foreach($attrs as $key => $value){
641       if(is_numeric($key) || ($key == "count") || ($key == "dn")){
642         unset($attrs[$key]);
643       }
644       if(is_array($value) && isset($value['count'])){
645         unset($attrs[$key]['count']);
646       }
647     }
648     return($attrs);
649   }
652   /* Save given attrs to specified dn*/
653   static function save_FAI_object($dn,$attrs)
654   {
655     global $config;
656     $ldap = $config->get_ldap_link();
657     $ldap->cd($config->current['BASE']);
658     $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $dn));
659     $ldap->cd($dn);
661     $ui= get_userinfo();
662     FAI::tag_attrs($attrs, $dn, $ui->gosaUnitTag);
664     $ldap->cat($dn,array("dn"));
665     if($ldap->count()){
667       /* Remove FAIstate*/
668       if(!isset($attrs['FAIstate'])){
669         $attrs['FAIstate'] = array();
670       }
672       $ldap->modify($attrs);
673     }else{
675       /* Unset description if empty  */
676       if(empty($attrs['description'])){
677         unset($attrs['description']);
678       }    
680       $ldap->add($attrs);
681     }
682     if (!$ldap->success()){
683       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, 0, get_class()));
684     }
685   }
688   /* Return FAIstate freeze branch or "" for specified release department */
689   static function get_release_tag($dn)
690   {
691     global $config;
692     $ldap = $config->get_ldap_link();
693     $ldap->cd($dn);
694     $ldap->cat($dn,array("FAIstate"));
696     if($ldap->count()){
698       $attr = $ldap->fetch();
699       if(isset($attr['FAIstate'][0])){
700         if(preg_match("/freeze/",$attr['FAIstate'][0])){
701           return("freeze");
702         }elseif(preg_match("/branch/",$attr['FAIstate'][0])){
703           return("branch");
704         }
705       }
706     }
707     return("");
708   }
711   static function get_following_releases_that_inherit_this_object($dn)
712   {
713     global $config;
714     $ldap = $config->get_ldap_link();
715     $ldap->cd($config->current['BASE']);
717     $ret = array();
719     /* Get base release */
720     $base_release = FAI::get_release_dn($dn);
722     /* Get previous release dns */
723     $sub_releases = FAI::                       get_sub_releases_of_this_release($base_release);
725     /* Get dn suffix. Example  "FAIvairableEntry=keksdose,FAIvariable=Keksregal," */
726 #  $dn_suffix = str_ireplace($base_release,"",$dn);
727     $dn_suffix = preg_replace("/".preg_quote($base_release, '/')."/i","",$dn);
729     /* Check if given object also exists whitin one of these releases */
730     foreach($sub_releases as $p_release => $name){
732       $check_dn = $dn_suffix.$p_release;
734       $ldap->cat($check_dn,array("dn","objectClass"));
736       if($ldap->count()){
737         //return($ret);
738       }else{
739         $ret[$check_dn]=$check_dn;
740       }
741     }
742     return($ret);
743   }
746   /* Get previous version of the object dn */
747   static function get_parent_release_object($dn,$include_myself=true)
748   {
749     global $config;
750     $ldap = $config->get_ldap_link();
751     $ldap->cd($config->current['BASE']);
752     $previous_releases= array();
754     /* Get base release */
755     $base_release = FAI::get_release_dn($dn);
756     if($include_myself){
757       $previous_releases[] = $base_release;  
758     }
760     /* Get previous release dns */
761     $tmp = FAI::             get_previous_releases_of_this_release($base_release,true);
762     foreach($tmp as $release){
763       $previous_releases[] = $release;
764     }
766     /* Get dn suffix. Example  "FAIvairableEntry=keksdose,FAIvariable=Keksregal," */
767 #  $dn_suffix = str_ireplace($base_release,"",$dn);
768     $dn_suffix = preg_replace("/".preg_quote($base_release, '/')."/i","",$dn);
770     /* Check if given object also exists whitin one of these releases */
771     foreach($previous_releases as $p_release){
772       $check_dn = $dn_suffix.$p_release;
773       $ldap->cat($check_dn,array("dn","objectClass"));
775       if($ldap->count()){
776         return($check_dn);
777       }
778     }
779     return("");
780   }
783   /* return release names of all parent releases */
784   static function get_previous_releases_of_this_release($dn,$flat)
785   {
786     global $config;
787     $ldap = $config->get_ldap_link();
788     $ldap->cd($config->current['BASE']);
789     $ret = array();
791     /* Explode dns into pieces, to be able to build parent dns */
792     $dns_to_check = gosa_ldap_explode_dn(preg_replace("/".preg_quote(",".$config->current['BASE'], '/')."/i","",$dn));
794     if(!is_array($dns_to_check)){
795       return;  
796     }
798     /* Unset first entry which represents the given dn */
799     unset($dns_to_check['count']); 
800     unset($dns_to_check[key($dns_to_check)]);
802     /* Create dns addresses and check if this dn is a release dn */
803     $id = 0;
804     while(count($dns_to_check)){
806       /* build parent dn */
807       $new_dn = "";
808       foreach($dns_to_check as $part){
809         $new_dn .= $part.",";
810       }
811       $new_dn .= $config->current['BASE'];
813       /* check if this dn is a release */
814       if(FAI::is_release_department($new_dn)){
815         if($flat){
816           $ret[$id] = $new_dn; 
817         }else{
818           $ret = array($new_dn=>$ret); 
819         }
820         $id ++;
821       }else{
822         return($ret);
823       }
824       reset($dns_to_check);
825       unset($dns_to_check[key($dns_to_check)]);
826     }
827     return($ret);
828   } 
831   /* This function returns all sub release names, recursivly  */
832   static function get_sub_releases_of_this_release($dn,$flat = false)
833   {
834     global $config;
835     $res  = array();
836     $ldap = $config->get_ldap_link();
837     $ldap->cd($config->current['BASE']);
838     $ldap->ls("(objectClass=FAIbranch)",$dn,array("objectClass","dn","ou"));
839     while($attr = $ldap->fetch()){
841       /* Append department name */
842       if($flat){
843         $res[$attr['dn']] = $attr['ou'][0];
844       }else{
845         $res[$attr['dn']] = array();
846       }
848       /* Get sub release departments of this department */
849       if(in_array("FAIbranch",$attr['objectClass'])) {
850         if($flat){
851           $tmp = FAI::                       get_sub_releases_of_this_release($attr['dn'],$flat);
852           foreach($tmp as $dn => $value){
853             $res[$dn]=$value;
854           }
855         }else{
856           $res[$attr['dn']] = FAI::                       get_sub_releases_of_this_release($attr['dn']);
857         }
858       }
859     }
860     return($res);
861   }
864   /* Check if the given department is a release department */
865   static function is_release_department($dn)
866   {
867     global $config;
868     $ldap = $config->get_ldap_link();
869     $ldap->cd($config->current['BASE']);
870     $ldap->cat($dn,array("objectClass","ou"));
872     /* Check objectClasses and name to check if this is a release department */
873     if($ldap->count()){
874       $attrs = $ldap->fetch();
876       $ou = "";
877       if(isset($attrs['ou'][0])){
878         $ou = $attrs['ou'][0];  
879       }
881       if((in_array("FAIbranch",$attrs['objectClass'])) || ($ou == "fai")){
882         return($attrs['dn']);
883       }
884     }
885     return(false);
886   }
889   static function copy_FAI_group_releases($source_release , $destination_name, $type ="" )
890   {
891     global $config;
892     $start = microtime(TRUE);
893     $source_release = trim($source_release,"/");
895     echo "<h2>".sprintf(_("Creating group application release for %s"),$destination_name)."</h2>";
897     $sub_releases = array();
898     $source_dn = "";
899     
900     $tmp = split("\/",$source_release);
901     foreach($tmp as $part){
902       if(empty($part)){
903         continue;
904       }
905       $source_dn            = "ou=".$part.",".$source_dn;
906       $sub_releases[$part]  = $source_dn;
907     }
909     /* Get all groups */
910     $ldap =$config->get_ldap_link();
911     $ldap->cd($config->current['BASE']);
912     $ldap->search("(objectClass=posixGroup)",array("dn"));
913     $groups = array();
914     while($attrs = $ldap->fetch()){
915       $groups[$attrs['dn']] = $attrs;
916     }
918     /* Get all FAI releases, to be able to create missing group application releases 
919         with the correct type of release (FAIstate=freeze/branch).
920      */
921     $f_releases = array();
922     $ldap->cd ($config->current['BASE']);
923     $ldap->search("(objectClass=FAIbranch)",array("ou","FAIstate"));
924     while($attrs = $ldap->fetch()){
925       foreach($sub_releases as $sub_rel){
926         if(preg_match("/^".preg_quote($sub_rel.get_ou('faiBaseRDN'), '/')."/",$attrs['dn'])){
927           $f_releases[$sub_rel.get_ou('faiBaseRDN')] = $attrs;
928         }
929       }
930     }
932     /* Get all group releases */
933     $g_releases = array();
934     foreach($groups as $dn => $data){
935       $ldap->cd($dn);
936       $ldap->search("(objectClass=FAIbranch)",array("ou","FAIstate"));
937       while($attrs = $ldap->fetch()){
938         $g_releases[$attrs['dn']] = $attrs;
939       }
940     }
942     /* Check if base releases exists.
943        If they do not exist, create them and adapt FAIstate attribute from FAI releases. 
944      */
945     foreach($sub_releases as $name => $sub_rel){
947       $FAIstate = "";
948       if(isset($f_releases[$sub_rel.get_ou('faiBaseRDN')]) && isset($f_releases[$sub_rel.get_ou('faiBaseRDN')]['FAIstate'])){
949         $FAIstate = $f_releases[$sub_rel.get_ou('faiBaseRDN')]['FAIstate'][0];
950       }
952       foreach($groups as $dn => $data){
953         if(!isset($g_releases[$sub_rel.$dn])){
954           $ldap->cd($dn);
955           $r_data = array();
956           $r_data['ou'] = $name;
957           $r_data['objectClass'] = array("top","organizationalUnit","FAIbranch");
958           if(!empty($FAIstate)) {
959             $r_data['FAIstate'] = $FAIstate;
960           }
961  
962           $ldap->cd($sub_rel.$dn) ;
963           $ldap->add($r_data);
964           echo "&nbsp;<b>"._("Object").":</b> ";
965           echo sprintf(_("Adding missing group application release container %s."),substr(LDAP::fix($sub_rel.$dn),0,96))."<br>";
966           flush();
967         }
968       }
969     } 
970  
971     /* Create new release container in each group.
972      */
973     $n_data = array();
974     $n_data = array();
975     $n_data['ou'] = $destination_name;
976     $n_data['objectClass'] = array("top","organizationalUnit","FAIbranch");
977     if(!empty($type)){
978       $n_data['FAIstate'] = $type."/cow";
979     }
981     foreach($groups as $dn => $att){
982       $n_dn = "ou=".$destination_name.",".$source_dn.$dn;
983       if(!isset($g_releases[$n_dn])){
984         $ldap->cd ($n_dn);
985         $ldap->add($n_data);
986         echo "&nbsp;<b>"._("Object").":</b> ";
987         echo sprintf(_("Adding group application release container %s."),substr(LDAP::fix($n_dn),0,96))."<br>";
988         flush();
989       }
990     }
992     /* If the source release is empty, then create a new release by copying 
993         all group application menus into a new ou=$destination_name release container.
994       
995        If the source release is not empty. 
996          We detect all releases which match the source release dn and copy the contents.
997      */
998     if(empty($source_release)){
999       $source_dns = $groups;
1000     }else{
1001       $source_dns = array();
1002       foreach($g_releases as $dn => $data){
1003         if(preg_match("/^".preg_quote($source_dn, '/')."/",$dn)){
1004           $source_dns[$dn] = $data; 
1005         }
1006       }
1007     }
1009     /* Detect all menu object we have to copy 
1010      */
1011     $to_copy = array();
1012     foreach($source_dns as $dn => $attrs){
1013       $ldap->cd($dn);
1014       $ldap->ls("(|(objectClass=gotoSubmenuEntry)(objectClass=gotoMenuEntry))",$dn,array("dn"));
1015       while($attrs = $ldap->fetch()){
1016         $destination = preg_replace("/".preg_quote($dn, '/')."$/","ou=".$destination_name.",".$dn,$attrs['dn']);
1017         $to_copy[$attrs['dn']] = $destination;
1018       }
1019     }
1020    
1021     /* At least create the menu objects object */
1022     $plug = new plugin($config);
1023     foreach($to_copy as $source => $destination){
1024       $ldap->cat($destination);
1025       if($ldap->count()){
1026         echo "&nbsp;<b>"._("Object").":</b> ";
1027         echo sprintf(_("Could not create menu entry %s. (Already exists)."),substr(LDAP::fix($destination),0,96))."<br>";
1028         flush();
1029       }else{
1030         $plug->copy($source,$destination);
1031         echo "&nbsp;<b>"._("Object").":</b> ";
1032         echo sprintf(_("Created group application menu entry for %s."),substr(LDAP::fix($destination),0,96))."<br>";
1033         flush();
1034       }
1035     }
1036   }
1039   /*! \brief Create a new FAI branch.
1040    *  @param $sourcedn          String  The source release dn
1041    *  @param $destinationdn     String  The destination dn
1042    *  @param $destinationName   String  The name of the new release
1043    *  @param $type              String  The release type (freeze/branch)
1044    *  @param $is_first          Boolean Use to identify the first func. call when recursivly called.
1045    *  @param $depth             Integer Current depth of recursion.
1046    */
1047   static function copy_FAI_resource_recursive($sourcedn,$destinationdn,$destinationName,$type="branch",$is_first = true,$depth=0)
1048   {
1049     global $config;
1050     error_reporting(E_ALL | E_STRICT);
1051     $ldap     = $config->get_ldap_link();
1052     $basedn   = $config->current['BASE'];
1053     $delarray = array();
1055     /* The following code will output a status string
1056      *  for each handled object, in a seperate iframe.
1057      */
1060     /* Display current action information.
1061      */
1062     if($is_first){
1063       echo "<h2>".sprintf(_("Creating copy of %s"),"<i>".LDAP::fix($sourcedn)."</i>")."</h2>";
1064     }else{
1065       if(preg_match("/^ou=/",$sourcedn)){
1066         echo "<h3>"._("Processing")." <i>".LDAP::fix($destinationdn)."</i></h3>";
1067       }else{
1068         $tmp = split(",",$sourcedn);
1069         echo "&nbsp;<b>"._("Object").":</b> ";
1070         $deststr = LDAP::fix($destinationdn);
1071         if(strlen($deststr) > 96){
1072           $deststr = substr($deststr,0,96)."...";
1073         }
1074         echo $deststr."<br>";
1075       }
1076     }
1077     /* .. immediately display infos */
1078     flush();
1080     /* Check if destination entry already exists
1081      */
1082     $ldap->cat($destinationdn);
1083     if($ldap->count()){
1084       echo _("Could not create new release, the destination dn is already in use.");
1085       return;
1086     }else{
1088       $ldap->clearResult();
1090       /* Get source entry
1091        *  if it does not exist, abort here.
1092        */
1093       $ldap->cd($basedn);
1094       $ldap->cat($sourcedn);
1095       $attr = $ldap->fetch();
1096       if((!$attr) || (count($attr)) ==0) {
1097         echo _("Error while fetching source dn - aborted!");
1098         return;
1099       }
1101       /* The current object we want to create is an department.
1102        * Create the department and add the FAIbranch tag.
1103        */
1104       if(in_array("organizationalUnit",$attr['objectClass'])){
1105         $attr['dn'] = LDAP::convert($destinationdn);
1106         $ldap->cd($basedn);
1107         $ldap->create_missing_trees($destinationdn);
1108         $ldap->cd($destinationdn);
1110         /* If is first entry, append FAIbranch to department entry */
1111         if($is_first){
1112           $ldap->cat($destinationdn);
1113           $attr= $ldap->fetch();
1114           /* Filter unneeded informations */
1115           foreach($attr as $key => $value){
1116             if(is_numeric($key)) unset($attr[$key]);
1117             if(isset($attr[$key]['count'])){
1118               if(is_array($attr[$key])){
1119                 unset($attr[$key]['count']);
1120               }
1121             }
1122           }
1124           unset($attr['count']);
1125           unset($attr['dn']);
1127           /* Add marking attribute */
1128           $attr['objectClass'][] = "FAIbranch";
1129           $attr['FAIstate'] = $type;
1131           /* Add this entry */
1132           $ldap->modify($attr);
1133         }
1134       }else{
1136         /* Replicate all relevant FAI objects here.
1137          * FAI objects, Apps and Mimetypes.
1138          * Get all attributes as binary value, to ensure that Icon, File template aso
1139          *  are created correctly.
1140          */
1141         foreach($attr as $key => $value){
1143           if(in_array($key ,array("gotoLogonScript", "gosaApplicationIcon","gotoMimeIcon"))){
1144             $sr= ldap_read($ldap->cid, LDAP::fix($sourcedn), "$key=*", array($key));
1145             $ei= ldap_first_entry($ldap->cid, $sr);
1146             if ($tmp= @ldap_get_values_len($ldap->cid, $ei,$key)){
1147               $attr[$key] = $tmp;
1148             }
1149           }
1151           if(is_numeric($key)) unset($attr[$key]);
1152           if(isset($attr[$key]['count'])){
1153             if(is_array($attr[$key])){
1154               unset($attr[$key]['count']);
1155             }
1156           }
1157         }
1158         unset($attr['count']);
1159         unset($attr['dn']);
1160         if(!in_array("FAIobject",$attr['objectClass'])){
1161           $attr['objectClass'][] = "FAIobject";
1162         }
1163         $attr['FAIstate'] = $type;
1165         /* Add entry
1166          */
1167         $ldap->cd($destinationdn);
1168         $ldap->cat($destinationdn);
1170         $a = $ldap->fetch();
1171         if(!count($a)){
1172           $ldap->add($attr);
1173         }
1175         if(!$ldap->success()){
1177           /* Some error occurred */
1178           msg_dialog::display(_("Fatal error"),
1179               sprintf(_("Release creation failed due to ldap errors. Additional informations '%s'."),
1180                 $ldap->get_error()."<br>".$sourcedn."<br>".$destinationdn."<br>"),FATAL_ERROR_DIALOG);
1181           exit();
1182         }
1183       }
1184     }
1186     echo "<script language=\"javascript\" type=\"text/javascript\">scrollDown2();</script>" ;
1188     /* Prepare for recursive copy.
1189      * Get all object within the source dn and
1190      *  call the recursive copy for each.
1191      */
1192     $ldap->ls ("(objectClass=*)",$sourcedn);
1193     while ($ldap->fetch()){
1194       $deldn= $ldap->getDN();
1195       $delarray[$deldn]= strlen($deldn);
1196     }
1197     asort ($delarray);
1198     reset ($delarray);
1199     $depth ++;
1200     foreach($delarray as $dn => $bla){
1201       if($dn != $destinationdn){
1202         $ldap->cd($basedn);
1203         $item = $ldap->fetch($ldap->cat($dn));
1204         if(!in_array("FAIbranch",$item['objectClass'])){
1205           FAI::copy_FAI_resource_recursive($dn,str_replace($sourcedn,$destinationdn,$dn),$destinationName,$type,false,$depth);
1206         }
1207       }
1208     }
1209     if($is_first){
1210       echo "<p class='seperator'>&nbsp;</p>";
1211     }
1212   }
1216   /* This function returns the dn of the object release */
1217   static function get_release_dn($Current_DN)
1218   {
1219     global $config;
1220     $ldap = $config->get_ldap_link();
1221     $ldap->cd($config->current['BASE']);
1223     /* Split dn into pices */ 
1224     $dns_to_check = gosa_ldap_explode_dn(preg_replace("/".preg_quote(",".$config->current['BASE'], '/')."/i","",$Current_DN));
1226     if(!is_array($dns_to_check)){
1227       return;  
1228     }
1230     /* Use dn pieces, to create sub dns like 
1231        ou=test,ou=1,ou=0...
1232        ou=1,ou=0...
1233        ou=0... 
1234        To check which dn is our release container.
1235      */
1236     unset($dns_to_check['count']); 
1237     while(count($dns_to_check)){
1239       /* Create dn */
1240       $new_dn = "";
1241       foreach($dns_to_check as $part){
1242         $new_dn .= $part.",";
1243       }
1244       $new_dn .= $config->current['BASE'];
1246       /* Check if this dn is a release dn */
1247       if(FAI::is_release_department($new_dn)){
1248         return($new_dn);
1249       }
1251       /* Remove first element of dn pieces */
1252       reset($dns_to_check);
1253       unset($dns_to_check[key($dns_to_check)]);
1254     }
1255     return("");
1256   }
1259   static function tag_attrs(&$at, $dn= "", $tag= "", $show= false)
1260   {                                                        
1261     /* Remove tags that may already be here... */                         
1262     remove_objectClass("gosaAdministrativeUnitTag", $at);                 
1263     if (isset($at['gosaUnitTag'])){                                       
1264         unset($at['gosaUnitTag']);                                        
1265     }                                                                     
1267     /* Set tag? */
1268     if ($tag != ""){
1269       add_objectClass("gosaAdministrativeUnitTag", $at);
1270       $at['gosaUnitTag']= $tag;                         
1271     }                                                   
1273     /* Initially this object was tagged. 
1274        - But now, it is no longer inside a tagged department. 
1275        So force the remove of the tag.                        
1276        (objectClass was already removed obove)                
1277      */                                                       
1278     if($tag == ""){                     
1279       $at['gosaUnitTag'] = array();                           
1280     }                                                         
1281   }                                                           
1283   /* Returns true if this is a parent object, e.g. FAIpartitionTable, not FAIpartitionDisk */
1284   static function is_parent_object($dn)
1285   {
1286     global $config;
1287     $Current_DN = $dn;
1289     /* special case partitions, as they don't start with cn= in their DN (schema bug?) */
1290     if (preg_match('/^FAIpartitionNr=/', $Current_DN)){
1291       return false;
1292     }
1294     $parent_dn = preg_replace('/^cn=[^,.]*,/', '', $Current_DN);
1295     if (preg_match('/^cn=/', $parent_dn)) {
1296       $ldap = $config->get_ldap_link();
1297       $ldap->cd($config->current['BASE']);
1298       $ldap->cat($parent_dn);
1299       if($ldap->count()){
1300         return false;
1301       }
1302     }else{
1303       return true;
1304     }
1305   }
1307   /* Return child objects, if there are any */
1308   static function get_child_objects($dn)
1309   {
1310     global $config;
1311     $Current_DN = $dn;
1312     $children= array();
1314     if (FAI::is_parent_object($Current_DN)){
1315       $ldap = $config->get_ldap_link();
1316       $ldap->cd($dn);
1317       $ldap->search("(objectClass=FAIclass)",array("dn"));
1318       while($attrs = $ldap->fetch()){
1319         if(preg_match("/".preg_quote($Current_DN, '/')."/",$attrs['dn']) && $attrs['dn'] != $Current_DN){
1320           $children[] = $attrs['dn'];
1321         }
1322       }
1323     }
1324     return $children;
1325   }
1327   /* Get the DN of the parent object; e.g. the FAIpartitionTable of a FAIpartitionDisk.
1328      If $check is false, do not check whether the parent actually exists in LDAP */
1329   static function get_parent_object($dn, $check=true)
1330   {
1331     global $config;
1332     $Current_DN = $dn;
1333     $i = 0;
1335     $tmp_dn = $Current_DN;
1336     $parent_dn = array();
1338     /* special case partitions, as they don't start with cn= in their DN (schema bug?) */
1339     $tmp_dn = preg_replace('/^FAIpartitionNr=/', 'cn=', $tmp_dn);
1341     $tmp_dn = gosa_ldap_explode_dn($tmp_dn);
1342     while(preg_match('/^cn=/', $tmp_dn[$i])) {
1343       $i++;
1344     }
1345     /* DN part does not start with cn= anymore, remove one from the counter to get the
1346        last CN element */
1347     $i--;
1349     for ($i;$i<$tmp_dn['count'];$i++) {
1350       $parent_dn[] = trim($tmp_dn[$i]);
1351     }
1352     $parent_dn = join($parent_dn, ',');
1354     if ($parent_dn != $Current_DN){
1355       if($check){
1356         $ldap = $config->get_ldap_link();
1357         $ldap->cd($config->current['BASE']);
1358         $ldap->cat($parent_dn);
1359         if(!$ldap->count()){
1360           return "";
1361         }
1362       }
1363       return $parent_dn;
1364     }
1365     return "";
1366   }
1368   /* Check whether parent object is removed */
1369   static function parent_is_removed($dn)
1370   {
1371     global $config;
1372     $Current_DN = $dn;
1374     $ldap = $config->get_ldap_link();
1375     $parent_dn = FAI::get_parent_object($Current_DN);
1376     if ($parent_dn) { 
1377       $ldap->cd($config->current['BASE']);
1378       $ldap->cat($parent_dn);
1379       $parentObjectAttrs = FAI::prepare_ldap_fetch_to_be_saved($ldap->fetch());
1380       if(isset($parentObjectAttrs['FAIstate'][0])){
1381         if(preg_match("/removed$/",$parentObjectAttrs['FAIstate'][0])){
1382           return true;
1383         }
1384       }
1385     } 
1386     return false;
1387   }
1389   /* Check whether this is a child object of a Copy-on-Write parent */
1390   static function is_child_of_cow_parent($dn)
1391   { 
1392     global $config;
1393     $Current_DN = $dn;
1394     $parent_dn = "";
1396     if (!FAI::is_parent_object($Current_DN)){
1398       /* This is a child object; check that the parent object is not 
1399          marked as removed */
1400       $cow_parent_dn = FAI::get_parent_object($Current_DN, false);
1401       if ($cow_parent_dn && !FAI::parent_is_removed($Current_DN)){
1403         /* This is a child object, check whether the parent object in 
1404            the main release exists */
1405         $main_parent_dn = FAI::get_parent_release_object($cow_parent_dn);
1406         $ldap = $config->get_ldap_link();
1407         $ldap->cd($config->current['BASE']);
1408         $ldap->cat($main_parent_dn);
1409         if($ldap->count()){
1410           return true;
1411         }
1412       }
1413     }
1414     return false;
1415   }
1422 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1423 ?>