Code

Updated FAI state detction.
[gosa.git] / gosa-plugins / fai / admin / fai / class_FAI.inc
1 <?php
3 define("DEBUG_FAI_FUNC",FALSE);
6 class FAI
7 {
9   /* TEST PHASE .... */
11   /* Returns all object for the given release.
12      This function resolves the releases  
13      from base up to the given dn.
14    */
15   static function get_all_objects_for_given_base($Current_DN,$filter,$detailed = false)
16   {
17     global $config;
18     $ldap = $config->get_ldap_link();
19     $ldap->cd($config->current['BASE']);
20     $res = array();
21     $tmp = array();
23     if(!FAI::is_release_department($Current_DN)) {
24       return($res);
25     }
27     /* Collect some basic informations and initialize some variables */ 
28     $base_release       = FAI::get_release_dn($Current_DN);
29     $previous_releases  = array_reverse(FAI::get_previous_releases_of_this_release($base_release,true));
31     $ldap->cat($base_release);
32     $attrs = $ldap->fetch();
33     $FAIstate = "branch";
34     if(isset($attrs['FAIstate'][0])){
35       $FAIstate = $attrs['FAIstate'][0];
36     }
38     /* We must also include the given release dn */
39     $previous_releases[] = $base_release;
41     /* Walk through all releases */
42     foreach($previous_releases as $release){
44       /* Get fai departments */
45       $deps_to_search = FAI::get_FAI_departments($release); 
47       /* For every single department  (ou=hoos,ou ..) */
48       foreach($deps_to_search as $fai_base){
50         /* Ldap search for fai classes specified in this release */
51         $attributes  = array("dn","objectClass","FAIstate","cn");
52         $res_tmp = get_list($filter,"fai",$fai_base,$attributes,GL_SUBSEARCH | GL_SIZELIMIT);
54         /* check the returned objects, and add/replace them in our return variable */
55         foreach($res_tmp as $attr){
57           $buffer = array();
58           $name = preg_replace("/".normalizePreg($release)."/i","",$attr['dn']);
60           if(isset($attr['FAIstate'][0])){
61             if(preg_match("/removed$/",$attr['FAIstate'][0])){
62               if(isset($res[$name])){
63                 unset($res[$name]);
64               }
65               continue;
66             }
67           }
69           /* Seems to be an inherited class, apply current FAIstate to this classes 
70            */
71           if(!preg_match("/".normalizePreg($base_release)."$/i",$attr['dn'])){
72             $buffer['FAIstate'] = $FAIstate; 
73           }else{
75             /* Seems to be created within this release department.
76                This indicates - it can't be of state "freeze"
77              */             
78             if(isset($attr['FAIstate'])){
79               $buffer['FAIstate'] = $attr['FAIstate'][0];
80             }else{
81               $buffer['FAIstate'] = "branch"; 
82             }
83           }
85           /* In detailed mode are some additonal informations visible */
86           if($detailed){
88             /* Create list of parents */
89             if(isset($res[$name])){
90               $buffer = $res[$name];
91               $buffer['parents'][] = $res[$name]['dn'];
92             }else{
93               $buffer['parents'] = array();
94             }
96             /* Append objectClass to resulsts */
97             foreach($attributes as $val){
98               if(isset($attr[$val])){
99                 $buffer[$val] = $attr[$val];
100               }
101             }
102             unset($buffer['objectClass']['count']);
103           }
105           /* Add this object to our list */
106           $buffer['dn']           = $attr['dn'];
107           $res[$name] = $buffer;
108         }
109       }
110     }
111     return($res);
112   }
115   /* Return all relevant FAI departments */
116   static function get_FAI_departments($suffix = "")
117   {
118     $arr = array("hooks","scripts","disk","packages","profiles","templates","variables");
119     $tmp = array();
120     if(preg_match("/^,/",$suffix)){
121       $suffix = preg_replace("/^,/","",$suffix);
122     }
123     foreach($arr as $name){
124       if(empty($suffix)){
125         $tmp[$name] = "ou=".$name;
126       }else{
127         $tmp[$name] = "ou=".$name.",".$suffix;
128       }
129     }
130     return($tmp);
131   }
134   /* Return all releases within the given base */
135   static function get_all_releases_from_base($dn,$appendedName=false)
136   {
137     global $config;
139     if(!preg_match("/".normalizePreg(get_ou('faiou'))."/",$dn)){
140       $base = get_ou('faiou').$dn;
141     }else{
142       $base = $dn;
143     }
144     $res = array();  
146     $ldap = $config->get_ldap_link();
147     $ldap->cd($base);
148     $ldap->search("(objectClass=FAIbranch)",array("ou","dn"));
149     while($attrs = $ldap->fetch()){
150       if($appendedName){
151         $res[$attrs['dn']] = convert_department_dn(preg_replace("/,".normalizePreg(get_ou('faiou')).".*$/","",$attrs['dn']));
152       }else{
153         $res[$attrs['dn']] = $attrs['ou'][0];
154       }
155     }
156     return($res);
157   }
160   /* Add this object to list of objects, that must be checked for release saving */
161   static function prepare_to_save_FAI_object($Current_DN,$objectAttrs,$removed = false)
162   {
163     /* Get ldap object */  
164     global $config;
165     $addObj['Current_DN'] = $Current_DN;
166     $addObj['objectAttrs']= $objectAttrs;
167     $addObj['removed']    = $removed;
168     $addObj['diff']       = TRUE;
170     if(!$removed){
171       $ldap = $config->get_ldap_link();
172       $ldap->cd($config->current['BASE']);
174       /* Get some basic informations */
175       $parent_obj   = FAI::get_parent_release_object($Current_DN);
176       if(!empty($parent_obj)){
177         $ldap->cat($parent_obj,array("*"));
178         $attrs = FAI::                           prepare_ldap_fetch_to_be_saved($ldap->fetch());
180         if(!FAI::array_diff_FAI( $attrs,$objectAttrs)){
181           $addObj['diff'] = FALSE;
182         }
183       } 
184     }else{
186       /* If this is the last CLASS of a specific name (e.g. DEPOTSERVER)
187           we have to remove this name from all profiles in this release.
188       */
189       $ldap = $config->get_ldap_link();
190       $ldap->cd($config->current['BASE']);
191       $obj_dn = FAI::get_parent_release_object($Current_DN,TRUE);
193       /* Dont't try to modify non FAIclasses  
194        */
195       if(!preg_match("/[^,]+,".normalizePreg(get_ou("faiou"))."/",$obj_dn)){
196         trigger_error("PLEASE check fai class handling in ".__LINE__." -> ".__FILE__);        
197         echo "<br>-->".$Current_DN."<br>";
198         echo "<br>-->".$obj_dn."<br>";
199       }else{
201         /* Get source object and check if it is a base FAIclass
202          */
203         $ldap->cat($obj_dn);
204         $attrs = $ldap->fetch();
205         $classes = array("FAIprofile","FAIscript","FAIpackageList","FAIpartitionTable","FAIHook","FAIvariable","FAItemplate");
206         if(count(array_intersect($classes,$attrs['objectClass']))){
207           $cn    = $attrs['cn'][0];
209           /* Check if this is the last with this name in the current release.
210               In this case we have to remove the package name 
211               from all profiles in this release.
212            */
213           $classes = FAI::get_all_objects_for_given_base(FAI::get_release_dn($Current_DN),
214               "(&(objectClass=FAIclass)(cn=".$cn."))"); 
216           /* Check if this is the last class with this name.
217            */
218           if(count($classes) == 1){
220             /* Get all FAI Profiles 
221              */
222             $profiles = FAI::get_all_objects_for_given_base(FAI::get_release_dn($Current_DN),
223                 "(&(objectClass=FAIprofile)(FAIclass=*))"); 
225             /* Walk though all profiles and remove the source class name
226              */
227             foreach($profiles as $dn){
228               $ldap->cat($dn['dn']);
229               $attrs = $ldap->fetch();
231               $attrs = array('FAIclass' => $attrs['FAIclass'][0]);
233               /* Check if this Profile uses the source class ($cn)
234                */
235               if(preg_match("/".normalizePreg($cn)."/",$attrs['FAIclass'])){
236                 $attrs['FAIclass'] = preg_replace("/[ ]*".normalizePreg($cn)."[ ]*/i"," ",$attrs['FAIclass']);
237                 if(empty($attrs['FAIclass'])){
238                   $attrs['FAIclass'] = array();
239                 }
240                 $ldap->cd($dn['dn']);
241                 $ldap->modify($attrs);
243                 if (!$ldap->success()){
244                   msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_MOD, get_class()));
245                 }
246               }
247             }
248           }
249         }
250       }
251     }
255     $FAI_objects_to_save = session::get('FAI_objects_to_save') ;
256     $FAI_objects_to_save[$Current_DN] =  $addObj;
257     session::set('FAI_objects_to_save',$FAI_objects_to_save);
258   }
261   /* Detect differences in attribute arrays  */
262   static function array_diff_FAI($ar1,$ar2)
263   {
265     if((!isset($ar1['description'])) || (isset($ar1['description']) && (count($ar1['description']) == 0))){
266       $ar1['description'] = "";
267     }
268     if((!isset($ar2['description'])) || (isset($ar2['description']) && (count($ar2['description']) == 0))){
269       $ar2['description'] = "";
270     }
272     if(count($ar1) != count($ar2)) {
273       return (true);
274     }
276     foreach($ar1 as $key1 => $val1){
278       if((is_array($val1)) && (count($val1)==1)){
279         $ar1[$key1] = $val1[0];
280       }
282       if(isset($ar2[$key1])&&  (is_array($ar2[$key1])) && (count($ar2[$key1])==1)){
283         $val1 = $val1[0];
284         $ar2[$key1] = $ar2[$key1][0];
285       }
286     }
287     ksort($ar1);
288     ksort($ar2);
289     if(count( array_diff($ar1,$ar2)) || FAI::arr_diff($ar1,$ar2)){
290       return(true);
291     }else{
292       return(false);
293     }
294   }
297   static function arr_diff($ar1,$ar2)
298   {
299     foreach($ar1 as $ak1 => $av1){
300       if(!isset($ar2[$ak1]) || (!($av1 === $ar2[$ak1]))){
301         return(TRUE);    
302       }elseif(is_array($av1)){
303         $ret = (FAI::arr_diff($av1,$ar2[$ak1]));
304         if($ret) {
305           return(TRUE);
306         }
307       }
308     }
309     return(FALSE);
310   }
315   /* check which objects must be saved, and save them */
316   static function save_release_changes_now()
317   {
318     global $config;
319     /* Variable init*/
320     $to_save = array();
321     
322     $reload_fai_classes = FALSE;
324     /* check which objects must be saved */
325     if(!session::is_set('FAI_objects_to_save')){
326       return;
327     }
328     $FAI_objects_to_save = session::get('FAI_objects_to_save');
329     if(!is_array($FAI_objects_to_save)) {
330       print_a(array(session::get('FAI_objects_to_save')));
331       trigger_error("Can't save FAI objects, no array given.");
332       return;
333     }
334   
335     foreach($FAI_objects_to_save as $Current_DN => $object){
336       if($object['diff']){
337         $sub_name = $Current_DN;
338         while(isset($FAI_objects_to_save[$sub_name])){
339           $to_save[strlen($sub_name)][$sub_name] = $FAI_objects_to_save[$sub_name]; 
340           unset($FAI_objects_to_save[$sub_name]);
341           $sub_name = preg_replace('/^[^,]+,/', '', $sub_name);
342         }
343       }
344     }
345     session::set('FAI_objects_to_save',$FAI_objects_to_save);
347     /* Sort list of objects that must be saved, and ensure that 
348        container   objects are safed, before their childs are saved */
349     ksort($to_save);
350     $tmp = array();
351     foreach($to_save as $SubObjects){
352       foreach($SubObjects as $object){
353         $tmp[] = $object;
354       }
355     }
356     $to_save = $tmp;
359     /* Save objects and manage the correct release behavior*/
360     foreach($to_save as $save){
362       $Current_DN = $save['Current_DN'];
363       $removed    = $save['removed'];
364       $objectAttrs= $save['objectAttrs'];
366       /* Get ldap object */ 
367       $ldap = $config->get_ldap_link();
368       $ldap->cd($config->current['BASE']);
370       /* Get some basic informations */
371       $base_release       = FAI::get_release_dn($Current_DN);
372       $sub_releases       = FAI::                       get_sub_releases_of_this_release($base_release,true);
373       $parent_obj         = FAI::get_parent_release_object($Current_DN);
374       $following_releases = FAI::                       get_sub_releases_of_this_release($base_release,true);
376       /* Check if given dn exists or if is a new entry */
377       $ldap->cat($Current_DN);
378       if(!$ldap->count()){
379         $is_new = true;
380       }else{
381         $is_new = false;
382       }
384       /* if parameter removed is true, we have to add FAIstate to the current attrs 
385          FAIstate should end with ...|removed after this operation */  
386       if($removed ){
387         $ldap->cat($Current_DN);
389         /* Get current object, because we must add the FAIstate ...|removed */
390         if((!$ldap->count()) && !empty($parent_obj)){
391           $ldap->cat($parent_obj);
392         }
394         /* Check if we have found a suiteable object */ 
395         if(!$ldap->count()){
396           echo "Error can't remove this object ".$Current_DN;
397           return;
398         }else{
400           /* Set FAIstate to current objectAttrs */
401           $objectAttrs = FAI::                           prepare_ldap_fetch_to_be_saved($ldap->fetch());
402           if(isset($objectAttrs['FAIstate'][0])){
403             if(!preg_match("/removed$/",$objectAttrs['FAIstate'][0])){
404               $objectAttrs['FAIstate'][0] .= "|removed";
405             }
406           }else{
407             $objectAttrs['FAIstate'][0] = "|removed";
408           }
410           /* Force reload of FAI classes */
411           $classes = array("FAIprofile","FAIscript","FAIpackageList","FAIpartitionTable","FAIHook","FAIvariable","FAItemplate");
412           if(count(array_intersect($classes,$objectAttrs['objectClass']))){
413             $reload_fai_classes = TRUE;
414           }
415         }
416       }
418       /* Check if this a leaf release or not */ 
419       if(count($following_releases) == 0 ){
421         /* This is a leaf object. It isn't inherited by any other object */    
422         if(DEBUG_FAI_FUNC) { 
423           echo "<b>Saving directly, is a leaf object</b><br> ".$Current_DN;
424           print_a($objectAttrs);
425         }
426         FAI::save_FAI_object($Current_DN,$objectAttrs);
428         /* Force reload of FAI classes */
429         $classes = array("FAIprofile","FAIscript","FAIpackageList","FAIpartitionTable","FAIHook","FAIvariable","FAItemplate");
430         if(count(array_intersect($classes,$objectAttrs['objectClass']))){
431           $reload_fai_classes = TRUE;
432         }
434       }else{
436         /* This object is inherited by some sub releases */  
438         /* Get all releases, that inherit this object */ 
439         $r = FAI::get_following_releases_that_inherit_this_object($Current_DN);
441         /* Get parent object */
442         $ldap->cat($parent_obj);
443         $parent_attrs = FAI::prepare_ldap_fetch_to_be_saved($ldap->fetch());
445         /* New objects require special handling */
446         if($is_new){
448           /* Force reload of FAI classes */
449           $classes = array("FAIprofile","FAIscript","FAIpackageList","FAIpartitionTable","FAIHook","FAIvariable","FAItemplate");
450           if(count(array_intersect($classes,$objectAttrs['objectClass']))){
451             $reload_fai_classes = TRUE;
452           }
454           /* check if there is already an entry named like this,
455              in one of our parent releases */
456           if(!empty($parent_obj)){
457             if(DEBUG_FAI_FUNC) { 
458               echo "There is already an entry named like this.</b><br>";
460               echo "<b>Saving main object</b>".$Current_DN;
461               print_a($objectAttrs);
462             }    
463             FAI::save_FAI_object($Current_DN,$objectAttrs);
465             foreach($r as $key){
466               if(DEBUG_FAI_FUNC) { 
467                 echo "<b>Saving parent to following release</b> ".$key;
468                 print_a($parent_attrs);
469               }
470               FAI::save_FAI_object($key,$parent_attrs);
471             }
472           }else{
474             if(DEBUG_FAI_FUNC) { 
475               echo "<b>Saving main object</b>".$Current_DN;
476               print_a($objectAttrs);
477             }
478             FAI::save_FAI_object($Current_DN,$objectAttrs);
480             if(isset($objectAttrs['FAIstate'])){
481               $objectAttrs['FAIstate'] .= "|removed"; 
482             }else{
483               $objectAttrs['FAIstate'] = "|removed";
484             }
486             foreach($r as $key ){
487               if(DEBUG_FAI_FUNC) { 
488                 echo "<b>Create an empty placeholder in follwing release</b> ".$key; 
489                 print_a($objectAttrs);
490               }
491               FAI::save_FAI_object($key,$objectAttrs);
492             }
493           }
494         }else{
496           /* check if we must patch the follwing release */
497           if(!empty($r)){
498             foreach($r as $key ){
499               if(DEBUG_FAI_FUNC) { 
500                 echo "<b>Copy current objects original attributes to next release</b> ".$key;
501                 print_a($parent_attrs);
502               }
503               FAI::save_FAI_object($key,$parent_attrs);
504             }
505           }
507           if(DEBUG_FAI_FUNC) { 
508             echo "<b>Saving current object</b>".$parent_obj;
509             print_a($objectAttrs);
510           }
511           FAI::save_FAI_object($parent_obj,$objectAttrs);
513           if(($parent_obj != $Current_DN)){
514             msg_dialog::display(_("Error"), sprintf(_("Error, following objects should be equal '%s' and '%s'"),$parent_obj,$Current_DN), ERROR_DIALOG);
515           }
516         }
517       }
518     }
520     /* Reload GOsa si FAI DB/cache
521      */
522     if($reload_fai_classes){
523       if( class_available("DaemonEvent") && class_available("gosaSupportDaemon")){
524         $events = DaemonEvent::get_event_types(SYSTEM_EVENT | HIDDEN_EVENT);        
525         if(isset($events['TRIGGERED']['DaemonEvent_recreate_fai_release_db'])){
526           $evt = $events['TRIGGERED']['DaemonEvent_recreate_fai_release_db']; 
527           $tmp = new $evt['CLASS_NAME']($config);
528           $tmp->set_type(TRIGGERED_EVENT);
529           $tmp->add_targets(array("GOsa"));
530           $o_queue = new gosaSupportDaemon();
531           if(!$o_queue->append($tmp)){
532             msg_dialog::display(_("Service infrastructure"),msgPool::siError($o_queue->get_error()),ERROR_DIALOG);
533           }
534         }
535       }
536     }
538     session::set('FAI_objects_to_save',array());
539   }
542   /* this function will remove all unused (deleted) objects,
543      that have no parent object */
544   static function clean_up_releases($Current_DN)
545   {
546     global $config;
547     $ldap = $config->get_ldap_link();
548     $ldap->cd($config->current['BASE']);
550     /* Collect some basic informations and initialize some variables */ 
551     $base_release       = FAI::get_release_dn($Current_DN);
552     $previous_releases  = array_reverse(FAI::             get_previous_releases_of_this_release($base_release,true));
553     $Kill = array();
554     $Skip = array();
556     /* We must also include the given release dn */
557     $previous_releases[] = $base_release;
559     /* Walk through all releases */
560     foreach($previous_releases as $release){
562       /* Get fai departments */
563       $deps_to_search = FAI::get_FAI_departments($release); 
565       /* For every single department  (ou=hoos,ou ..) */
566       foreach($deps_to_search as $fai_base){
568         /* Ldap search for fai classes specified in this release */
569         $ldap->cd($fai_base);
570         $ldap->search("(objectClass=FAIclass)",array("dn","objectClass","FAIstate"));
572         /* check the returned objects, and add/replace them in our return variable */
573         while($attr = $ldap->fetch()){
575           $buffer = array();
576 #        $name = str_ireplace($release,"",$attr['dn']);
577           $name = preg_replace("/".normalizePreg($release)."/i","",$attr['dn']);
579           if(isset($attr['FAIstate'][0])&&(preg_match("/removed$/",$attr['FAIstate'][0]))){
581             /* Check if this object is required somehow */    
582             if(!isset($Skip[$name])){
583               $Kill[$attr['dn']] = $attr['dn'];
584             }
585           }else{
587             /* This object is required (not removed), so do not 
588                delete any following sub releases of this object */
589             $Skip[$name] = $attr['dn'];
590           }
591         }
592       }
593     }
594     return($Kill);
595   }
598   /* Remove numeric index and 'count' from ldap->fetch result */
599   static function prepare_ldap_fetch_to_be_saved($attrs)
600   {
601     foreach($attrs as $key => $value){
602       if(is_numeric($key) || ($key == "count") || ($key == "dn")){
603         unset($attrs[$key]);
604       }
605       if(is_array($value) && isset($value['count'])){
606         unset($attrs[$key]['count']);
607       }
608     }
609     return($attrs);
610   }
613   /* Save given attrs to specified dn*/
614   static function save_FAI_object($dn,$attrs)
615   {
616     global $config;
617     $ldap = $config->get_ldap_link();
618     $ldap->cd($config->current['BASE']);
619     $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $dn));
620     $ldap->cd($dn);
622     $ldap->cat($dn,array("dn"));
623     if($ldap->count()){
625       /* Remove FAIstate*/
626       if(!isset($attrs['FAIstate'])){
627         $attrs['FAIstate'] = array();
628       }
630       $ldap->modify($attrs);
631     }else{
633       /* Unset description if empty  */
634       if(empty($attrs['description'])){
635         unset($attrs['description']);
636       }    
638       $ldap->add($attrs);
639     }
640     if (!$ldap->success()){
641       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, 0, get_class()));
642     }
643   }
646   /* Return FAIstate freeze branch or "" for specified release department */
647   static function get_release_tag($dn)
648   {
649     global $config;
650     $ldap = $config->get_ldap_link();
651     $ldap->cd($dn);
652     $ldap->cat($dn,array("FAIstate"));
654     if($ldap->count()){
656       $attr = $ldap->fetch();
657       if(isset($attr['FAIstate'][0])){
658         if(preg_match("/freeze/",$attr['FAIstate'][0])){
659           return("freeze");
660         }elseif(preg_match("/branch/",$attr['FAIstate'][0])){
661           return("branch");
662         }
663       }
664     }
665     return("");
666   }
669   static function get_following_releases_that_inherit_this_object($dn)
670   {
671     global $config;
672     $ldap = $config->get_ldap_link();
673     $ldap->cd($config->current['BASE']);
675     $ret = array();
677     /* Get base release */
678     $base_release = FAI::get_release_dn($dn);
680     /* Get previous release dns */
681     $sub_releases = FAI::                       get_sub_releases_of_this_release($base_release);
683     /* Get dn suffix. Example  "FAIvairableEntry=keksdose,FAIvariable=Keksregal," */
684 #  $dn_suffix = str_ireplace($base_release,"",$dn);
685     $dn_suffix = preg_replace("/".normalizePreg($base_release)."/i","",$dn);
687     /* Check if given object also exists whitin one of these releases */
688     foreach($sub_releases as $p_release => $name){
690       $check_dn = $dn_suffix.$p_release;
692       $ldap->cat($check_dn,array("dn","objectClass"));
694       if($ldap->count()){
695         //return($ret);
696       }else{
697         $ret[$check_dn]=$check_dn;
698       }
699     }
700     return($ret);
701   }
704   /* Get previous version of the object dn */
705   static function get_parent_release_object($dn,$include_myself=true)
706   {
707     global $config;
708     $ldap = $config->get_ldap_link();
709     $ldap->cd($config->current['BASE']);
710     $previous_releases= array();
712     /* Get base release */
713     $base_release = FAI::get_release_dn($dn);
714     if($include_myself){
715       $previous_releases[] = $base_release;  
716     }
718     /* Get previous release dns */
719     $tmp = FAI::             get_previous_releases_of_this_release($base_release,true);
720     foreach($tmp as $release){
721       $previous_releases[] = $release;
722     }
724     /* Get dn suffix. Example  "FAIvairableEntry=keksdose,FAIvariable=Keksregal," */
725 #  $dn_suffix = str_ireplace($base_release,"",$dn);
726     $dn_suffix = preg_replace("/".normalizePreg($base_release)."/i","",$dn);
728     /* Check if given object also exists whitin one of these releases */
729     foreach($previous_releases as $p_release){
730       $check_dn = $dn_suffix.$p_release;
731       $ldap->cat($check_dn,array("dn","objectClass"));
733       if($ldap->count()){
734         return($check_dn);
735       }
736     }
737     return("");
738   }
741   /* return release names of all parent releases */
742   static function get_previous_releases_of_this_release($dn,$flat)
743   {
744     global $config;
745     $ldap = $config->get_ldap_link();
746     $ldap->cd($config->current['BASE']);
747     $ret = array();
749     /* Explode dns into pieces, to be able to build parent dns */
750     $dns_to_check = gosa_ldap_explode_dn(preg_replace("/".normalizePreg(",".$config->current['BASE'])."/i","",$dn));
752     if(!is_array($dns_to_check)){
753       return;  
754     }
756     /* Unset first entry which represents the given dn */
757     unset($dns_to_check['count']); 
758     unset($dns_to_check[key($dns_to_check)]);
760     /* Create dns addresses and check if this dn is a release dn */
761     $id = 0;
762     while(count($dns_to_check)){
764       /* build parent dn */
765       $new_dn = "";
766       foreach($dns_to_check as $part){
767         $new_dn .= $part.",";
768       }
769       $new_dn .= $config->current['BASE'];
771       /* check if this dn is a release */
772       if(FAI::is_release_department($new_dn)){
773         if($flat){
774           $ret[$id] = $new_dn; 
775         }else{
776           $ret = array($new_dn=>$ret); 
777         }
778         $id ++;
779       }else{
780         return($ret);
781       }
782       reset($dns_to_check);
783       unset($dns_to_check[key($dns_to_check)]);
784     }
785     return($ret);
786   } 
789   /* This function returns all sub release names, recursivly  */
790   static function get_sub_releases_of_this_release($dn,$flat = false)
791   {
792     global $config;
793     $res  = array();
794     $ldap = $config->get_ldap_link();
795     $ldap->cd($config->current['BASE']);
796     $ldap->ls("(objectClass=FAIbranch)",$dn,array("objectClass","dn","ou"));
797     while($attr = $ldap->fetch()){
799       /* Append department name */
800       if($flat){
801         $res[$attr['dn']] = $attr['ou'][0];
802       }else{
803         $res[$attr['dn']] = array();
804       }
806       /* Get sub release departments of this department */
807       if(in_array("FAIbranch",$attr['objectClass'])) {
808         if($flat){
809           $tmp = FAI::                       get_sub_releases_of_this_release($attr['dn'],$flat);
810           foreach($tmp as $dn => $value){
811             $res[$dn]=$value;
812           }
813         }else{
814           $res[$attr['dn']] = FAI::                       get_sub_releases_of_this_release($attr['dn']);
815         }
816       }
817     }
818     return($res);
819   }
822   /* Check if the given department is a release department */
823   static function is_release_department($dn)
824   {
825     global $config;
826     $ldap = $config->get_ldap_link();
827     $ldap->cd($config->current['BASE']);
828     $ldap->cat($dn,array("objectClass","ou"));
830     /* Check objectClasses and name to check if this is a release department */
831     if($ldap->count()){
832       $attrs = $ldap->fetch();
834       $ou = "";
835       if(isset($attrs['ou'][0])){
836         $ou = $attrs['ou'][0];  
837       }
839       if((in_array("FAIbranch",$attrs['objectClass'])) || ($ou == "fai")){
840         return($attrs['dn']);
841       }
842     }
843     return(false);
844   }
847   static function copy_FAI_group_releases($source_release , $destination_name, $type ="" )
848   {
849     global $config;
850     $start = microtime(TRUE);
851     $source_release = trim($source_release,"/");
853     echo "<h2>".sprintf(_("Creating group application release for %s"),$destination_name)."</h2>";
855     $sub_releases = array();
856     $source_dn = "";
857     
858     $tmp = split("\/",$source_release);
859     foreach($tmp as $part){
860       if(empty($part)){
861         continue;
862       }
863       $source_dn            = "ou=".$part.",".$source_dn;
864       $sub_releases[$part]  = $source_dn;
865     }
867     /* Get all groups */
868     $ldap =$config->get_ldap_link();
869     $ldap->cd($config->current['BASE']);
870     $ldap->search("(objectClass=posixGroup)",array("dn"));
871     $groups = array();
872     while($attrs = $ldap->fetch()){
873       $groups[$attrs['dn']] = $attrs;
874     }
876     /* Get all FAI releases, to be able to create missing group application releases 
877         with the correct type of release (FAIstate=freeze/branch).
878      */
879     $f_releases = array();
880     $ldap->cd ($config->current['BASE']);
881     $ldap->search("(objectClass=FAIbranch)",array("ou","FAIstate"));
882     while($attrs = $ldap->fetch()){
883       foreach($sub_releases as $sub_rel){
884         if(preg_match("/^".normalizePreg($sub_rel.get_ou('faiou'))."/",$attrs['dn'])){
885           $f_releases[$sub_rel.get_ou('faiou')] = $attrs;
886         }
887       }
888     }
890     /* Get all group releases */
891     $g_releases = array();
892     foreach($groups as $dn => $data){
893       $ldap->cd($dn);
894       $ldap->search("(objectClass=FAIbranch)",array("ou","FAIstate"));
895       while($attrs = $ldap->fetch()){
896         $g_releases[$attrs['dn']] = $attrs;
897       }
898     }
900     /* Check if base releases exists.
901        If they do not exist, create them and adapt FAIstate attribute from FAI releases. 
902      */
903     foreach($sub_releases as $name => $sub_rel){
905       $FAIstate = "";
906       if(isset($f_releases[$sub_rel.get_ou('faiou')]) && isset($f_releases[$sub_rel.get_ou('faiou')]['FAIstate'])){
907         $FAIstate = $f_releases[$sub_rel.get_ou('faiou')]['FAIstate'][0];
908       }
910       foreach($groups as $dn => $data){
911         if(!isset($g_releases[$sub_rel.$dn])){
912           $ldap->cd($dn);
913           $r_data = array();
914           $r_data['ou'] = $name;
915           $r_data['objectClass'] = array("top","organizationalUnit","FAIbranch");
916           if(!empty($FAIstate)) {
917             $r_data['FAIstate'] = $FAIstate;
918           }
919  
920           $ldap->cd($sub_rel.$dn) ;
921           $ldap->add($r_data);
922           echo "&nbsp;<b>"._("Object").":</b> ";
923           echo sprintf(_("Adding missing group application release container %s."),substr(LDAP::fix($sub_rel.$dn),0,96))."<br>";
924           flush();
925         }
926       }
927     } 
928  
929     /* Create new release container in each group.
930      */
931     $n_data = array();
932     $n_data = array();
933     $n_data['ou'] = $destination_name;
934     $n_data['objectClass'] = array("top","organizationalUnit","FAIbranch");
935     if(!empty($type)){
936       $n_data['FAIstate'] = $type."/cow";
937     }
939     foreach($groups as $dn => $att){
940       $n_dn = "ou=".$destination_name.",".$source_dn.$dn;
941       if(!isset($g_releases[$n_dn])){
942         $ldap->cd ($n_dn);
943         $ldap->add($n_data);
944         echo "&nbsp;<b>"._("Object").":</b> ";
945         echo sprintf(_("Adding group application release container %s."),substr(LDAP::fix($n_dn),0,96))."<br>";
946         flush();
947       }
948     }
950     /* If the source release is empty, then create a new release by copying 
951         all group application menus into a new ou=$destination_name release container.
952       
953        If the source release is not empty. 
954          We detect all releases which match the source release dn and copy the contents.
955      */
956     if(empty($source_release)){
957       $source_dns = $groups;
958     }else{
959       $source_dns = array();
960       foreach($g_releases as $dn => $data){
961         if(preg_match("/^".normalizePreg($source_dn)."/",$dn)){
962           $source_dns[$dn] = $data; 
963         }
964       }
965     }
967     /* Detect all menu object we have to copy 
968      */
969     $to_copy = array();
970     foreach($source_dns as $dn => $attrs){
971       $ldap->cd($dn);
972       $ldap->ls("(|(objectClass=gotoSubmenuEntry)(objectClass=gotoMenuEntry))",$dn,array("dn"));
973       while($attrs = $ldap->fetch()){
974         $destination = preg_replace("/".normalizePreg($dn)."$/","ou=".$destination_name.",".$dn,$attrs['dn']);
975         $to_copy[$attrs['dn']] = $destination;
976       }
977     }
978    
979     /* At least create the menu objects object */
980     $plug = new plugin($config);
981     foreach($to_copy as $source => $destination){
982       $ldap->cat($destination);
983       if($ldap->count()){
984         echo "&nbsp;<b>"._("Object").":</b> ";
985         echo sprintf(_("Could not create menu entry %s. (Already exists)."),substr(LDAP::fix($destination),0,96))."<br>";
986         flush();
987       }else{
988         $plug->copy($source,$destination);
989         echo "&nbsp;<b>"._("Object").":</b> ";
990         echo sprintf(_("Created group application menu entry for %s."),substr(LDAP::fix($destination),0,96))."<br>";
991         flush();
992       }
993     }
994   }
997   /*! \brief Create a new FAI branch.
998    *  @param $sourcedn          String  The source release dn
999    *  @param $destinationdn     String  The destination dn
1000    *  @param $destinationName   String  The name of the new release
1001    *  @param $type              String  The release type (freeze/branch)
1002    *  @param $is_first          Boolean Use to identify the first func. call when recursivly called.
1003    *  @param $depth             Integer Current depth of recursion.
1004    */
1005   static function copy_FAI_resource_recursive($sourcedn,$destinationdn,$destinationName,$type="branch",$is_first = true,$depth=0)
1006   {
1007     global $config;
1008     error_reporting(E_ALL | E_STRICT);
1009     $ldap     = $config->get_ldap_link();
1010     $basedn   = $config->current['BASE'];
1011     $delarray = array();
1013     /* The following code will output a status string
1014      *  for each handled object, in a seperate iframe.
1015      */
1018     /* Display current action information.
1019      */
1020     if($is_first){
1021       echo "<h2>".sprintf(_("Creating copy of %s"),"<i>".LDAP::fix($sourcedn)."</i>")."</h2>";
1022     }else{
1023       if(preg_match("/^ou=/",$sourcedn)){
1024         echo "<h3>"._("Processing")." <i>".LDAP::fix($destinationdn)."</i></h3>";
1025       }else{
1026         $tmp = split(",",$sourcedn);
1027         echo "&nbsp;<b>"._("Object").":</b> ";
1028         $deststr = LDAP::fix($destinationdn);
1029         if(strlen($deststr) > 96){
1030           $deststr = substr($deststr,0,96)."...";
1031         }
1032         echo $deststr."<br>";
1033       }
1034     }
1035     /* .. immediately display infos */
1036     flush();
1038     /* Check if destination entry already exists
1039      */
1040     $ldap->cat($destinationdn);
1041     if($ldap->count()){
1042       echo _("Could not create new release, the destination dn is already in use.");
1043       return;
1044     }else{
1046       $ldap->clearResult();
1048       /* Get source entry
1049        *  if it does not exist, abort here.
1050        */
1051       $ldap->cd($basedn);
1052       $ldap->cat($sourcedn);
1053       $attr = $ldap->fetch();
1054       if((!$attr) || (count($attr)) ==0) {
1055         echo _("Error while fetching source dn - aborted!");
1056         return;
1057       }
1059       /* The current object we want to create is an department.
1060        * Create the department and add the FAIbranch tag.
1061        */
1062       if(in_array("organizationalUnit",$attr['objectClass'])){
1063         $attr['dn'] = LDAP::convert($destinationdn);
1064         $ldap->cd($basedn);
1065         $ldap->create_missing_trees($destinationdn);
1066         $ldap->cd($destinationdn);
1068         /* If is first entry, append FAIbranch to department entry */
1069         if($is_first){
1070           $ldap->cat($destinationdn);
1071           $attr= $ldap->fetch();
1072           /* Filter unneeded informations */
1073           foreach($attr as $key => $value){
1074             if(is_numeric($key)) unset($attr[$key]);
1075             if(isset($attr[$key]['count'])){
1076               if(is_array($attr[$key])){
1077                 unset($attr[$key]['count']);
1078               }
1079             }
1080           }
1082           unset($attr['count']);
1083           unset($attr['dn']);
1085           /* Add marking attribute */
1086           $attr['objectClass'][] = "FAIbranch";
1088           /* Add this entry */
1089           $ldap->modify($attr);
1090         }
1091       }else{
1093         /* Replicate all relevant FAI objects here.
1094          * FAI objects, Apps and Mimetypes.
1095          * Get all attributes as binary value, to ensure that Icon, File template aso
1096          *  are created correctly.
1097          */
1098         foreach($attr as $key => $value){
1100           if(in_array($key ,array("gotoLogonScript", "gosaApplicationIcon","gotoMimeIcon"))){
1101             $sr= ldap_read($ldap->cid, LDAP::fix($sourcedn), "$key=*", array($key));
1102             $ei= ldap_first_entry($ldap->cid, $sr);
1103             if ($tmp= @ldap_get_values_len($ldap->cid, $ei,$key)){
1104               $attr[$key] = $tmp;
1105             }
1106           }
1108           if(is_numeric($key)) unset($attr[$key]);
1109           if(isset($attr[$key]['count'])){
1110             if(is_array($attr[$key])){
1111               unset($attr[$key]['count']);
1112             }
1113           }
1114         }
1115         unset($attr['count']);
1116         unset($attr['dn']);
1118         /* Add entry
1119          */
1120         $ldap->cd($destinationdn);
1121         $ldap->cat($destinationdn);
1123         $a = $ldap->fetch();
1124         if(!count($a)){
1125           $ldap->add($attr);
1126         }
1128         if(!$ldap->success()){
1130           /* Some error occurred */
1131           print "---------------------------------------------";
1132           print $ldap->get_error()."<br>";
1133           print $sourcedn."<br>";
1134           print $destinationdn."<br>";
1135           print_a( $attr);
1136           exit();
1137         }
1138       }
1139     }
1141     echo "<script language=\"javascript\" type=\"text/javascript\">scrollDown2();</script>" ;
1143     /* Prepare for recursive copy.
1144      * Get all object within the source dn and
1145      *  call the recursive copy for each.
1146      */
1147     $ldap->ls ("(objectClass=*)",$sourcedn);
1148     while ($ldap->fetch()){
1149       $deldn= $ldap->getDN();
1150       $delarray[$deldn]= strlen($deldn);
1151     }
1152     asort ($delarray);
1153     reset ($delarray);
1154     $depth ++;
1155     foreach($delarray as $dn => $bla){
1156       if($dn != $destinationdn){
1157         $ldap->cd($basedn);
1158         $item = $ldap->fetch($ldap->cat($dn));
1159         if(!in_array("FAIbranch",$item['objectClass'])){
1160           FAI::copy_FAI_resource_recursive($dn,str_replace($sourcedn,$destinationdn,$dn),$destinationName,$type,false,$depth);
1161         }
1162       }
1163     }
1164     if($is_first){
1165       echo "<p class='seperator'>&nbsp;</p>";
1166     }
1167   }
1171   /* This function returns the dn of the object release */
1172   static function get_release_dn($Current_DN)
1173   {
1174     global $config;
1175     $ldap = $config->get_ldap_link();
1176     $ldap->cd($config->current['BASE']);
1178     /* Split dn into pices */ 
1179     $dns_to_check = gosa_ldap_explode_dn(preg_replace("/".normalizePreg(",".$config->current['BASE'])."/i","",$Current_DN));
1181     if(!is_array($dns_to_check)){
1182       return;  
1183     }
1185     /* Use dn pieces, to create sub dns like 
1186        ou=test,ou=1,ou=0...
1187        ou=1,ou=0...
1188        ou=0... 
1189        To check which dn is our release container.
1190      */
1191     unset($dns_to_check['count']); 
1192     while(count($dns_to_check)){
1194       /* Create dn */
1195       $new_dn = "";
1196       foreach($dns_to_check as $part){
1197         $new_dn .= $part.",";
1198       }
1199       $new_dn .= $config->current['BASE'];
1201       /* Check if this dn is a release dn */
1202       if(FAI::is_release_department($new_dn)){
1203         return($new_dn);
1204       }
1206       /* Remove first element of dn pieces */
1207       reset($dns_to_check);
1208       unset($dns_to_check[key($dns_to_check)]);
1209     }
1210     return("");
1211   }
1217 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1218 ?>