Code

Updated FAI script
[gosa.git] / gosa-plugins / fai / admin / fai / class_faiScript.inc
1 <?php
3 class faiScript extends plugin
4 {
5   /* attribute list for save action */
6   var $ignore_account   = TRUE;
8   /* Attributes for this Object */
9   var $attributes       = array("cn","description");
11   /* ObjectClasses for this Object*/
12   var $objectclasses    = array("top","FAIclass","FAIscript");
14   /* Class name of the Ldap ObjectClass for the Sub Object */
15   var $subClass         = "FAIscriptEntry";
16   var $subClasses       = array("top","FAIclass","FAIscriptEntry");
18   /* Class name of the php class which allows us to edit a Sub Object */
19   var $subClassName     = "faiScriptEntry";      
21   /* Attributes to initialise for each subObject */
22   var $subAttributes    = array("cn","description","FAIpriority"); 
23   var $sub_Load_Later   = array("FAIscript");
24   var $sub64coded       = array();
25   var $subBinary        = array("FAIscript");
27   /* Specific attributes */
28   var $cn               = "";       // The class name for this object
29   var $description      = "";       // The description for this set of partitions
30   var $is_dialog        = false;    // specifies which buttons will be shown to save or abort
31   var $SubObjects       = array();  // All leafobjects of this object
33   var $FAIstate         = "branch";
34   var $sort_by          = "name";
35   var $sort_order       = "up";
37   var $view_logged = FALSE;
38   var $ui;
40   function faiScript (&$config, $dn= NULL)
41   {
42     /* Load Attributes */
43     plugin::plugin ($config, $dn);
45     /* If "dn==new" we try to create a new entry
46      * Else we must read all objects from ldap which belong to this entry.
47      * First read SubObjects from ldap ... and then the partition definitions for the SubObjects.
48      */
49     if($dn != "new"){
51       $this->dn =$dn;
53       /* Get FAIstate
54        */
55       if(isset($this->attrs['FAIstate'][0])){
56         $this->FAIstate = $this->attrs['FAIstate'][0];
57       }
59       /* Read all leaf objects of this object (For FAIscript this would be FAIscriptEntry)
60        */
61       $ldap     = $this->config->get_ldap_link();
62       $ldap->cd ($this->dn);
63       
64       $attrs_to_search = $this->subAttributes;
65       $attrs_to_search[] = "FAIstate";
66       $ldap->search("(&(objectClass=FAIclass)(objectClass=".$this->subClass."))",$attrs_to_search);
67       $data = array();
68       while($object = $ldap->fetch()){
69         $data[] = $object;
70       }
71       foreach($data as $object){
73         /* Skip objects, that are tagged as removed */
74         if(isset($object['FAIstate'][0])){
75           if(preg_match("/removed$/",$object['FAIstate'][0])){
76             continue;
77           }
78         }
80         /* Set status for save management */
81         $objects = array();
82         $objects['status']      = "FreshLoaded";
83         $objects['dn']          = $object['dn'];
84         $objects                = $this->get_object_attributes($objects,$this->subAttributes);
85         $this->SubObjects[$objects['cn']] = $objects;
86       }
87     
88     }
90     $this->is_new = FALSE;
91     if($this->dn == "new"){
92       $this->is_new =TRUE;
93     }
94  
95     $this->ui = get_userinfo();
96   }
99   /* Reload some attributes */
100   function get_object_attributes($object,$attributes)
101   {
102     $ldap = $this->config->get_ldap_link();
103     $ldap->cd($this->config->current['BASE']);
104     $ldap->cat($object['dn'],$attributes);
105     $tmp  = $ldap->fetch();
107     foreach($attributes as $attrs){
108       if(isset($tmp[$attrs][0])){
109         $var = $tmp[$attrs][0];
111         /* Check if we must decode some attributes */
112         if(in_array_ics($attrs,$this->sub64coded)){
113           $var = base64_decode($var);
114         }
116         /*  check if this is a binary entry */
117         if(in_array_ics($attrs,$this->subBinary)){
118           $var = $ldap->get_attribute($object['dn'], $attrs,$r_array=0);
119         }
121         /* Fix slashes */
122         $var = addslashes($var);
123         $object[$attrs] = $var;
124       }
125     }
126     return($object);
127   }
129   
130   /* Return a valid dn to fetch acls. Because 'new' will not work. */
131   function acl_base_for_current_object($dn)
132   {
133     if($dn == "new"){
134       if($this->dn == "new"){
135         $dn= "cn=dummy,".session::get('CurrentMainBase');
136       }else{
137         $dn = $this->dn;
138       }
139     }
140     return($dn);
141   }
144   function execute()
145   {
146     /* Call parent execute */
147     plugin::execute();
149     if($this->is_account && !$this->view_logged){
150       $this->view_logged = TRUE;
151       new log("view","fai/".get_class($this),$this->dn);
152     }
154     /* Fill templating stuff */
155     $smarty= get_smarty();
156     $display= "";
158     /* Add new sub object */
159     if(isset($_POST['AddSubObject']) && !preg_match("/freeze/i",$this->FAIstate)){
160       $this->dialog= new $this->subClassName($this->config,"new");
161       $this->dialog->FAIstate = $this->FAIstate;
162       $this->dialog->set_acl_base($this->acl_base);
163       $this->dialog->set_acl_category("fai");
164       $this->dialog->parent = &$this;
165       $this->is_dialog=true;
166     }
168     if($this->dn != "new"){
169       session::set('objectinfo',$this->dn);
170     }
172     /* File download requested */
173     if(isset($_GET['getFAIscript'])){
174       if(isset($this->SubObjects[base64_decode($_GET['getFAIscript'])])){
175         $obj = $this->SubObjects[base64_decode($_GET['getFAIscript'])];
176         $obj  = $this->get_object_attributes($obj,$this->sub_Load_Later);
177         send_binary_content(stripslashes($obj['FAIscript']),$obj['cn'].".FAIscript"); 
178       }
179     }
180     
181     /* Handle posts */
182     $s_action = $s_entry = "";
183     foreach($_POST as $name => $value){
185       /* Edit script posted */
186       if(preg_match("/^editscript_/",$name)){
187         $s_action = "edit";
188         $s_entry = preg_replace("/^editscript_/","",$name);
189         $s_entry = base64_decode(preg_replace("/_.*/","",$s_entry));
190         break;
191       }
193       /* Delete script requested */
194       if(preg_match("/^deletescript_/",$name) && preg_match("/freeze/i",$this->FAIstate)){
195         $s_action = "remove";
196         $s_entry = preg_replace("/^deletescript_/","",$name);
197         $s_entry = base64_decode(preg_replace("/_.*/","",$s_entry));
198         break;
199       }
200     }
202     if(isset($_GET['act']) && $_GET['act'] == "edit" && isset($_GET['id'])){
203       $s_entry = base64_decode($_GET['id']);
204       if(isset($this->SubObjects[$s_entry])){
205         $s_action = "edit";
206       }
207     }
209     if($s_action =="edit" && isset($this->SubObjects[$s_entry])){
211       /* Get object, and load missing entry values */
212       $obj  = $this->SubObjects[$s_entry];
213       if($obj['status'] == "FreshLoaded"){
214         $obj  = $this->get_object_attributes($obj,$this->sub_Load_Later);
215       }
217       /* Create new dialog and set acl attributes  */
218       $this->dialog= new $this->subClassName($this->config,$this->dn,$obj);
219       $this->dialog->FAIstate = $this->FAIstate;
220       $this->dialog->set_acl_base($this->acl_base_for_current_object($obj['dn']));
221       $this->dialog->set_acl_category("fai");
223       /* Assign some additional dialog informations like headline and parent  */
224       session::set('objectinfo',$obj['dn']);
225       $this->dialog->parent = &$this;
226       $this->is_dialog=true;
227     }
229     /* Check acls, are we allowed to delete an entry */
230     if($s_action == "remove" && isset($this->SubObjects[$s_entry])){
231       $entry = $this->SubObjects[$s_entry];  
232       $acl = $this->ui->get_permissions($this->acl_base_for_current_object($entry['dn']),"fai/faiScriptEntry")  ;
233       if(preg_match("/d/",$acl)){
234         $status = $entry['status'];
235         if($status == "edited" || $status == "FreshLoaded"){
236           $this->SubObjects[$s_entry]['status']= "delete";
237         }else{
238           unset($this->SubObjects[$s_entry]);
239         }
240       }
241     }
243       /* Save the edited entry */
244     if(isset($_POST['SaveSubObject'])){
246       /* Check if there are still errors remaining that must be fixed before saving */
247       $this->dialog->save_object();
248       $msgs = $this->dialog->check();
249       if(count($msgs)>0){
250         foreach($msgs as $msg){
251           msg_dialog::display(_("Error"), $msg, ERROR_DIALOG);
252         }
253       }else{
255         /* Get return object */
256         $obj = $this->dialog->save();
258         /* If we have renamed the script entry, we must remove the old entry */
259         if(isset($obj['remove'])){
261           /* Get old entry values */
262           $old_stat = $this->SubObjects[$obj['remove']['from']]['status'];
264           /* Depending on status, set new status */
265           if($old_stat == "edited" || $old_stat == "FreshLoaded"){
266             $this->SubObjects[$obj['remove']['from']]['status'] = "delete";
267           }elseif($this->SubObjects[$obj['remove']['from']]['status']=="new"){
268             unset($this->SubObjects[$obj['remove']['from']]);
269           }
271           /* Append the new entry */
272           $obj['status'] = "new";
273           $this->SubObjects[$obj['remove']['to']] = $obj;
274           unset($this->SubObjects[$obj['remove']['to']]['remove']);
275         }else{
276   
277           /* Set new status and append the entry */
278           if($obj['status'] == "FreshLoaded"){
279             $obj['status'] = "edited";
280           }
281           $this->SubObjects[$obj['cn']]=$obj;
282         }
283         $this->is_dialog=false;
284         unset($this->dialog);
285         $this->dialog=FALSE;
287       }
288     }
290     /* Sort entries */
291     $tmp = $keys = array();
293     if($this->sort_by == "name"){
294       foreach($this->SubObjects as $key => $entry){
295         $keys[$key]=$entry['cn'];
296       }
297     }elseif($this->sort_by == "priority"){
298       foreach($this->SubObjects as $key => $entry){
299         $keys[$key]=$entry['FAIpriority'];
300       }
301     }
303     natcasesort($keys);
305     if($this->sort_order == "down"){
306       $keys =array_reverse($keys);
307     }
309     foreach($keys as $key => $order_var){
310       $tmp[$key]=$this->SubObjects[$key];
311     }
312     $this->SubObjects = $tmp;
314     /* Cancel Dialog */
315     if(isset($_POST['CancelSubObject'])){
316       $this->is_dialog=false; 
317       unset($this->dialog);
318       $this->dialog=FALSE;
319     }
321     /* Print dialog if $this->dialog is set */
322     if(is_object($this->dialog)){
323       $this->dialog->save_object();
324       $display = $this->dialog->execute();
325       return($display);
326     }
328     /* Divlist            added 23.02.2006 
329        Containing FAIscripts 
330      */
331     $divlist = new divlist("FAIscripts");
332     $divlist->SetEntriesPerPage(0);
333     $plug = $_GET['plug'];
334    
335     if($this->sort_order == "up"){
336       $dir = "<img src='images/lists/sort-up.png' title='"._("Sort direction")."' alt='\/' border=0>";
337     }else{
338       $dir = "<img src='images/lists/sort-down.png' title='"._("Sort direction")."' alt='/\' border=0>";
339     }
340  
341     if($this->sort_by == "name"){
342       $sort_name = $dir;
343       $sort_prio = "";
344     }else{
345       $sort_name = "";
346       $sort_prio = $dir;
347     }
349     $divlist->SetHeader(array(  array("string"=>"<a href='?plug=".$plug."&amp;sort=name'>"._("Name").$sort_name."</a>"),
350                                 array("string"=>"<a href='?plug=".$plug."&amp;sort=priority'>".$sort_prio._("Priority")."</a>",
351                                       "attach"=>"style='width:100px;'"),
352                                 array("string"=>_("Download"),
353                                       "attach"=>"style='width:100px;'"),
354                                 array("string"=>_("Action"),
355                                       "attach"=>"style='border-right: 0px;width:100px;text-align:right;'")));
356     $divlist->SetHeight(300);
357     $divlist->SetWidth("100%");
358     foreach($this->getList(true) as $key => $name){
360       $dn= $this->acl_base_for_current_object($name['dn']);
361       $acl = $this->ui->get_permissions($dn,"fai/faiScriptEntry")  ;
362       $act = "";
363       
364       /* Hide delete icon if this object is freezed */
365       if(preg_match("/freeze/", $this->FAIstate)){
366         $act .= "<input type='image' src='images/lists/edit.png'      name='editscript_%s'    title='"._("edit")."' alt='"._("edit")."'>";
367       }else{
368         $act .= "<input type='image' src='images/lists/edit.png'      name='editscript_%s'    title='"._("edit")."' alt='"._("edit")."'>";
369         if(preg_match("/d/",$acl)){
370           $act .="<input type='image' src='images/lists/trash.png' name='deletescript_%s'  title='"._("delete")."' alt='"._("delete")."'>";
371         }
372       }
374       /* Check acls for download icon */
375       $s_acl = $this->ui->get_permissions($dn,"fai/faiScriptEntry","FAIscript")  ;
376       if(($this->SubObjects[$key]['status'] == "new") || ($this->SubObjects[$key]['dn'] == "new") || !preg_match("/r/",$s_acl)){
377         $down = "";
378       }else{
379         $down = "<a href='?plug=".$_GET['plug']."&getFAIscript=".base64_encode($key)."'>
380           <img src='images/save.png' alt='"._("Download")."' title='"._("Download")."' border=0>
381           </a>"; 
382       } 
384       /* Check if we are allowed to view this object */
385       $s_acl = $this->ui->get_permissions($dn,"fai/faiScriptEntry","cn")  ;
386       if(preg_match("/r/",$s_acl)){
387         $divlist->AddEntry(array( array("string"=>"<a href='?plug=".$_GET['plug']."&amp;act=edit&amp;id=".base64_encode($key)."'>".$name['name']."</a>"),
388               array("string"=>$name['FAIpriority'] , "attach" => "style='width:100px;'"),
389               array("string"=>$down , "attach" => "style='width:100px;'"),
390               array("string"=>str_replace("%s",base64_encode($key),$act),
391                 "attach"=>"style='border-right: 0px;width:100px;text-align:right;'")));
392       }
393     }
394     $smarty->assign("Entry_divlist",$divlist->DrawList());
396     /* Magic quotes GPC, escapes every ' " \, to solve some security risks
397      * If we post the escaped strings they will be escaped again
398      */
399     foreach($this->attributes as $attrs){
400       if(get_magic_quotes_gpc()){
401         $smarty->assign($attrs,stripslashes($this->$attrs));
402       }else{
403         $smarty->assign($attrs,($this->$attrs));
404       }
405     }
407     $dn = $this->acl_base_for_current_object($this->dn);
408     $smarty->assign("sub_object_is_addable",  
409         preg_match("/c/",$this->ui->get_permissions($dn,"fai/faiScriptEntry")) && 
410         !preg_match("/freeze/",$this->FAIstate));
412     $tmp = $this->plInfo();
413     foreach($tmp['plProvidedAcls'] as $name => $translated){
414       $smarty->assign($name."ACL",$this->getacl($name));
415     }
417     $display.= $smarty->fetch(get_template_path('faiScript.tpl', TRUE));
418     return($display);
419   }
422   /* Generate listbox friendly SubObject list
423    */
424   function getList($use_dns=false){
425     $a_return=array();
426     foreach($this->SubObjects as $obj){
427       if($obj['status'] != "delete"){
429         $cn   = stripslashes($obj['cn']);
430         $desc = "";
432         if((isset($obj['description']))&&(!empty($obj['description']))){
433           $desc = " [".stripslashes($obj['description'])."]";
434         }
436         if($use_dns){
437           $a_return[$obj['cn']]['name']= $cn.$desc;
438           $a_return[$obj['cn']]['dn']= $obj['dn'];
439           $a_return[$obj['cn']]['FAIpriority']= $obj['FAIpriority'];
440         }else{
441           $a_return[$obj['cn']] =  $cn.$desc;
442         }
443       }
444     }
445     return($a_return);
446   }
449   /* Delete me, and all my subtrees
450    */
451   function remove_from_parent()
452   {
453     if($this->acl_is_removeable()){
454       $ldap = $this->config->get_ldap_link();
455       $ldap->cd ($this->dn);
456       $release = $this->parent->parent->fai_release;
457       $use_dn = preg_replace("/".normalizePreg(FAI::get_release_dn($this->dn))."/i", $release, $this->dn);
458       new log("remove","fai/".get_class($this),$use_dn,$this->attributes);
459       FAI::prepare_to_save_FAI_object($use_dn,array(),true);
460  
461       foreach($this->SubObjects as $name => $obj){
462         $use_dn = preg_replace("/".normalizePreg(FAI::get_release_dn($this->dn))."/i", $release, $obj['dn']);
463         FAI::prepare_to_save_FAI_object($use_dn,array(),true);
464       }
465       $this->handle_post_events("remove");
466     }
467   }
470   /* Save data to object 
471    */
472   function save_object()
473   {
474     if((isset($_POST['FAIscript_posted'])) && !preg_match("/freeze/", $this->FAIstate)){
475       plugin::save_object();
476       foreach($this->attributes as $attrs){
477         if(isset($_POST[$attrs])){
478           $this->$attrs = $_POST[$attrs];
479         }
480       }
481     }
482     
483     /* Get sort order */
484     if(isset($_GET['sort']) && in_array($_GET['sort'],array("name","priority"))){
485       if($this->sort_by == $_GET['sort']){
486         if($this->sort_order == "up"){
487           $this->sort_order = "down";
488         }elseif($this->sort_order == "down"){
489           $this->sort_order = "up";
490         }
491       }
492       $this->sort_by = $_GET['sort'];
493     }
494   }
497   /* Check supplied data */
498   function check()
499   {
500     /* Call common method to give check the hook */
501     $message= plugin::check();
503     /* Ensure that we do not overwrite an allready existing entry 
504      */
505     if($this->is_new){
506       $release = $this->parent->parent->fai_release;
507       $new_dn= 'cn='.$this->cn.",".get_ou('faiscriptou').get_ou('faiou').$release;
508       $res = faiManagement::check_class_name("FAIscript",$this->cn,$new_dn);
509       if(isset($res[$this->cn])){
510         $message[] = msgPool::duplicated(_("Name"));
511       }
512     }
514     return ($message);
515   }
518   /* Save to LDAP */
519   function save()
520   {
521     plugin::save();
523     $ldap = $this->config->get_ldap_link();
525     FAI::prepare_to_save_FAI_object($this->dn,$this->attrs);
527     if($this->initially_was_account){
528       new log("modify","fai/".get_class($this),$this->dn,$this->attributes);
529     }else{
530       new log("create","fai/".get_class($this),$this->dn,$this->attributes);
531     }
533     /* Prepare FAIscriptEntry to write it to ldap
534      * First sort array.
535      *  Because we must delete old entries first.
536      * After deletion, we perform add and modify 
537      */
538     $Objects = array();
540     /* We do not need to save untouched objects */
541     foreach($this->SubObjects as $name => $obj){
542       if($obj['status'] == "FreshLoaded"){
543         unset($this->SubObjects[$name]);
544       }
545     }
547     foreach($this->SubObjects as $name => $obj){
548       if($obj['status'] == "delete"){
549         $Objects[$name] = $obj; 
550       }
551     }
552     foreach($this->SubObjects as $name => $obj){
553       if($obj['status'] != "delete"){
554         $Objects[$name] = $obj; 
555       }
556     }
558     foreach($Objects as $name => $obj){
560       foreach($this->sub64coded as $codeIt){
561         $obj[$codeIt]=base64_encode(stripslashes($obj[$codeIt]));
562       }
564       $tmp = array();
565       $attributes = array_merge($this->sub_Load_Later,$this->subAttributes);
566       foreach($attributes as $attrs){
568         if(empty($obj[$attrs])){
569           $obj[$attrs] = array();
570         }
571         if(!is_array($obj[$attrs])){
572           $tmp[$attrs] = stripslashes($obj[$attrs]);
573         }else{
574           $tmp[$attrs] = $obj[$attrs];
575         }
576       }    
578       $tmp['objectClass'] = $this->subClasses;
580       $sub_dn = "cn=".$obj['cn'].",".$this->dn;
582       if($obj['status']=="new"){
583         $ldap->cat($sub_dn,array("objectClass"));
584         if($ldap->count()){
585           $obj['status']="edited";
586         }
587       }
589       if(empty($tmp['FAIpriority'])){
590         $tmp['FAIpriority']  ="0";
591       }
593       /* Tag object */
594       $this->tag_attrs($tmp, $sub_dn, $this->gosaUnitTag);
596       if($obj['status'] == "delete"){
597         FAI::prepare_to_save_FAI_object($sub_dn,array(),true);
598         $this->handle_post_events("remove");
599       }elseif($obj['status'] == "edited"){
600         FAI::prepare_to_save_FAI_object($sub_dn,$tmp);
601         $this->handle_post_events("modify");
602       }elseif($obj['status']=="new"){
603         FAI::prepare_to_save_FAI_object($sub_dn,$tmp);
604         $this->handle_post_events("add");
605       }
606     }
607   }
610   function PrepareForCopyPaste($source)
611   {
612     plugin::PrepareForCopyPaste($source);
614     /* Read all leaf objects of this object (For FAIscript this would be FAIscriptEntry)
615      */
616     $ldap     = $this->config->get_ldap_link();
617     $ldap->cd ($source['dn']);
619     $attrs_to_search = $this->subAttributes;
620     $attrs_to_search[] = "FAIstate";
621     $ldap->search("(&(objectClass=FAIclass)(objectClass=".$this->subClass."))",$attrs_to_search);
623     while($object = $ldap->fetch()){
625       /* Skip objects, that are tagged as removed */
626       if(isset($object['FAIstate'][0])){
627         if(preg_match("/removed$/",$object['FAIstate'][0])){
628           continue;
629         }
630       }
632       /* Set status for save management */
633       $objects = array();
634       $objects['status']      = "edited";
635       $objects['dn']          = $object['dn'];
636       $objects                = $this->get_object_attributes($objects,$this->subAttributes);
637       $objects                = $this->get_object_attributes($objects,$this->sub_Load_Later);
638   
639       $this->SubObjects[$objects['cn']] = $objects;
640     }
641   }
644   /*! \brief  Used for copy & paste.
645               Returns a HTML input mask, which allows to change the cn of this entry.
646       @param  Array   Array containing current status && a HTML template.
647    */
648   function getCopyDialog()
649   {
650     $vars = array("cn");
651     $smarty = get_smarty();
652     $smarty->assign("cn", htmlentities($this->cn));
653     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE));
654     $ret = array();
655     $ret['string'] = $str;
656     $ret['status'] = "";
657     return($ret);
658   }
661   /*! \brief  Used for copy & paste.
662               Some entries must be renamed to avaoid duplicate entries.
663    */
664   function saveCopyDialog()
665   {
666     if(isset($_POST['cn'])){
667       $this->cn = get_post('cn');
668     }
669   }
670   
672   /* Return plugin informations for acl handling */ 
673   static function plInfo()
674   {
675     return (array( 
676           "plShortName" => _("Script"),
677           "plDescription" => _("FAI script"),
678           "plSelfModify"  => FALSE,
679           "plDepends"     => array(),
680           "plPriority"    => 18,
681           "plSection"     => array("administration"),
682           "plCategory"    => array("fai"),
683           "plProvidedAcls" => array(
684             "cn"                => _("Name")." ("._("Readonly").")",
685             "description"       => _("Description"))
686           ));
687   }
690 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
691 ?>