Code

Added seperate list handler for gotomasses.
[gosa.git] / plugins / addons / gotomasses / class_gotomasses.inc
index a8230776f8aad1208e5f1a077a762390f0128261..4a58ca9c8db74179e8499b15c506f28239f3e579 100644 (file)
 class gotomasses extends plugin
 {
   /* Definitions */
-  var $plHeadline     = "Mass machine";
+  var $plHeadline     = "System deployment";
   var $plDescription  = "This does something";
 
   /* attribute list for save action */
   var $attributes= array();
   var $objectclasses= array();
 
-  /* Source file that contains the csv data */
-  var $file_to_read = "Undefined"; #Set in constructor 
+  /* Source file that contains the gotomasses data */
+  var $data_file = "Undefined"; #Set in constructor 
 
-  /* Parsed csv content */
-  var $contents         = array();
+  /* Queue tasks */
+  var $tasks = array();
+  var $current =false;
+  var $dialog = FALSE;
+  var $ids_to_remove = array();
+  var $divlist = NULL;
 
-  /* Used to detect changes made on the csv content.
-   *  Buttons will be disabled and js warnings will be 
-   *  shown if the content wasn't saved or discarded
-   */
-  var $contents_backup  = array();
-
-
-  function gotomasses($config, $dn= NULL)
+  function gotomasses(&$config, $dn= NULL)
   {
-    /* Define source file */
-    $this->file_to_read = CONFIG_DIR."/gotomasses_machines";
-  
     /* Include config object */
-    $this->config= $config;
-    $this->load_csv_data();
-  }
-
+    $this->config= &$config;
 
-  function get_object_groups()
-  {
-    $ret = array();
-    $ldap = $this->config->get_ldap_link();
-    $ldap->cd($this->config->current['BASE']);
-    $ldap->search("(&(objectClass=gosaGroupOfNames)(cn=*))",array("cn"));
-    while($attrs = $ldap->fetch()){
-      $ret [$attrs['cn'][0]] = $attrs['cn'][0];
+    /* Define source file */
+    $this->data_file = CONFIG_DIR."/gotomasses_machines";
+    $file = $this->config->search("gotomasses", "STORAGE_FILE",array('menu'));
+    if(!empty($file)){
+      $this->data_file = $file;
     }
-    return($ret); 
+    $this->load_gotomasses_data();
   }
 
 
   function execute()
   {
-    if(isset($_POST['export_gotomass_csv'])){
-        $data = "";
-        foreach($this->contents as $val){
-          $data .= $val['MAC'].", ".$val['OG']."\n";
-        }
-        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
-        header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
-        header("Cache-Control: no-cache");
-        header("Pragma: no-cache");
-        header("Cache-Control: post-check=0, pre-check=0");
-        header("Content-type: text/plain");
-        if (preg_match('/MSIE 5.5/', $_SERVER['HTTP_USER_AGENT']) ||
-            preg_match('/MSIE 6.0/', $_SERVER['HTTP_USER_AGENT'])){
-          header('Content-Disposition: filename="gotomass.csv"');
-        } else {
-          header('Content-Disposition: attachment; filename="gotomass.csv";');
+    $smarty = get_smarty();
+    /************
+     * Handle posts 
+     ************/
+
+    $s_entry = $s_action = "";
+    $arr = array( "/^edit_task_/"=>"edit","/^remove_task_/"=>"remove",
+                  "/^new_task_/"=>"new_task","/^remove_multiple_task_/" => "remove_multiple");
+    foreach($arr as $regex => $action){
+      foreach($_POST as $name => $value){
+        if(preg_match($regex,$name)){
+          $s_action = $action;
+          $s_entry  = preg_replace($regex,"",$name);
+          $s_entry  = preg_replace("/_(x|y)$/","",$s_entry);
         }
-        echo $data;
-        exit();
-    }
-   
-    /* Import given file */ 
-    if(isset($_POST['import_gotomass_csv']) && isset($_FILES['mass_file'])){
-      $str = @file_get_contents($_FILES['mass_file']['tmp_name']);
-      if(empty($str)){
-        print_red(_("The uploaded file seams to be empty, import aborted."));
-      }else{
-        $this->load_csv_data($str);
       }
     }
 
-    /* Add a new empty entry to the list */ 
-    if(isset($_POST['add_new_entry'])){
-      $this->contents[] = array("MAC" => "", "OG" => "");
+    /* Edit posted from list link */
+    if(isset($_GET['act']) && $_GET['act'] == "edit" && isset($_GET['id']) && isset($this->tasks[$_GET['id']])){
+      $s_action = "edit";
+      $s_entry = $_GET['id'];
     }
 
-    /* Call parent execute */
-    plugin::execute();
-    $smarty= get_smarty();
-    $smarty->assign("contents_modified",$this->contents_modified());
-    $smarty->assign("ogs", $this->get_object_groups());
-    $smarty->assign("contents", $this->contents);
-    $smarty->assign("launchimage","images/launch.png");
-    return ($smarty->fetch (get_template_path('contents.tpl', TRUE)));
-  }
+    /************
+     * List posts 
+     ************/
 
-  
-  /* Check if something is modified */
-  function contents_modified($display = FALSE)
-  {
-    $a = $this->contents;
-    $b = $this->contents_backup;
-    if(count($a) != count($b)){
-      if($display){
-        print_a(array_diff_assoc($a,$b));
-      }
-      return(TRUE);
-    }else{
-      foreach($a as $a_key => $a_val){
-        if(count(array_diff($a_val, $b[$a_key]))){
-
-          if($display){
-            print_a(array_diff($a_val, $b[$a_key]));
+    /* Remove multiple */
+    if($s_action == "remove_multiple"){
+      if(!$this->acl_is_removeable()){
+        print_red(_("You are not allowed to remove a task."));
+      }else{
+        $this->ids_to_remove = $this->list_get_selected_items();
+        $tmp = "";
+        foreach($this->ids_to_remove as $key => $id){
+          if(isset($this->tasks[$id])){
+            $task = $this->tasks[$id];
+            $tmp.= "\n".$this->target_to_string($task);
+          }else{
+            unset($this->ids_to_remove[$key]);
           }
-          return(TRUE);
         }
+        $smarty->assign("multiple", TRUE); 
+        $smarty->assign("info",sprintf(_("Your are about to delete the following tasks: %s"),"<pre>".$tmp."</pre>"));
+        $this->current = $s_entry;
+        return($smarty->fetch(get_template_path('remove.tpl', TRUE)));
       }
     }
-    return(FALSE); 
-  }
-
 
-  function load_csv_data($data = NULL)
-  {
-    if($data == NULL){
-      if(!file_exists($this->file_to_read) || !is_readable($this->file_to_read)){
-        print_red(sprintf(_("Can't locate or read csv storage file '%s'."),$this->file_to_read));
-        return(FALSE);
+    /* Remove specified tasks */
+    if(count($this->ids_to_remove) && isset($_POST['delete_multiple_confirm'])){
+      foreach($this->ids_to_remove as $id){
+        if(isset($this->tasks[$id])){
+          unset($this->tasks[$id]);
+        }
       }
+      $this->save();
+    }
 
-      $fp = @fopen($this->file_to_read,"r");
-      if(!$fp){
-        print_red(sprintf(_("Can't read csv storage file '%s'."),$this->file_to_read));
-        return(FALSE);
+    /* Remove entry from list */
+    if($s_action == "remove" && isset($this->tasks[$s_entry])){
+      if(!$this->acl_is_removeable()){
+        print_red(_("You are not allowed to remove a task."));
+      }else{
+        $entry = $this->tasks[$s_entry];
+        $this->current = $s_entry;
+        $smarty->assign("info",sprintf(_("Your are about to delete the following tasks: %s"),
+                                    "<pre>".$this->target_to_string($entry)."</pre>"));
+        $smarty->assign("multiple", FALSE); 
+        return($smarty->fetch(get_template_path('remove.tpl', TRUE)));
       }
+    }
 
-      $this->contents =array(); 
+    /* Remove entry, remove is confirmed */
+    if($this->current != -1 && isset($_POST['delete_confirm'])){
+      unset($this->tasks[$this->current]);
+      $this->current = -1;
+      $this->save();
+    }
 
-      while(!feof($fp)){
-        $str = trim(fgets($fp,512));
+    /* Remove aborted */
+    if(isset($_POST['delete_cancel'])){
+      $this->ids_to_remove = array();;
+    }
 
-        /* Get mac address */
-        $og = trim(preg_replace("/^[^,;]*(,|;)/","",$str));
-        $mac = preg_replace("/(,|;).*$/","",$str);
+    /* Edit selected entry */
+    if($s_action == "edit" && isset($this->tasks[$s_entry])){
+      $entry = $this->tasks[$s_entry];
+      $this->dialog = new goto_task($this->config,$this,$entry);
+      $this->current = $s_entry;
+    }
 
-        if(!empty($og) || !empty($mac)){
-          $this->contents[] = array("MAC" => $mac , "OG" => $og);
+    /* New entry */
+    if($s_action== "new_task" && $this->acl_is_createable()){
+      $this->dialog = new goto_task($this->config,$this);
+      $this->current = -1;
+    }
+  
+    /* Close dialog */
+    if(isset($_POST['close_goto_task'])){
+      $this->dialog = FALSE;
+      $this->current = -1;
+    }
+
+    /* Close dialog */
+    if((isset($_POST['save_goto_task']) || isset($_POST['apply_goto_task'])) && is_object($this->dialog) ){
+      $this->dialog->save_object();
+      $msgs = $this->dialog->check();
+      if(count($msgs)){
+        foreach($msgs as $msg){
+          print_red($msg);  
         }
-      }
-      fclose($fp);
-    }else{
-      $this->contents =array(); 
-      $rows = split("\n",$data);
-      foreach($rows as $str){
-        
-        /* Get mac address */
-        $og = trim(preg_replace("/^[^,;]*(,|;)/","",$str));
-        $mac = preg_replace("/(,|;).*$/","",$str);
-
-        if(!empty($og) || !empty($mac)){
-          $this->contents[] = array("MAC" => $mac , "OG" => $og);
+      }else{
+        if(isset($this->tasks[$this->current]) && $this->current != -1){
+          $this->tasks[$this->current] = $this->dialog->save();
+        }else{
+          $this->tasks[] = $this->dialog->save();
         }
+        if(!isset($_POST['apply_goto_task'])){
+          $this->dialog = FALSE;
+          $this->current = -1;
+        }
+        $this->save();
       }
     }
-    $this->contents_backup = $this->contents;
-  }
 
+    /* Display dialogs if currently opened */
+    if(is_object($this->dialog)){
+      $this->dialog->save_object();
+      return($this->dialog->execute());
+    }
+
+
+    /************
+     * Handle Divlist 
+     ************/
+
+    $list = new divListMasses($this->config,$this);
+    $list->SetEntries($this->tasks); 
+    return($list->Draw());
+  }
 
-  function save_csv_data()
+  
+  function target_to_string($data)
   {
-    if(!file_exists($this->file_to_read) || !is_writeable($this->file_to_read)){
-      print_red(sprintf(_("Can't locate or write csv storage file '%s'."),$this->file_to_read));
+    $ret = "";
+    if($data['Action'] == "initial_install"){
+      foreach($data['Initial_Target'] as $target){
+        $ret .= $target['MAC'].", ";
+      } 
     }else{
-      $fp = @fopen($this->file_to_read,"w");
-      if(!$fp){
-        print_red(sprintf(_("Can't write csv storage file '%s'."),$this->file_to_read));
-      }else{  
-        $data = "";
-        foreach($this->contents as $val){
-          $data .= $val['MAC'].", ".$val['OG']."\n";
-        }
-        fwrite($fp,$data,strlen($data));
-        fclose($fp);
-      }
+      foreach($data['Target'] as $target){
+        $ret .= $target.", ";
+      } 
     }
+    return(preg_replace("/, $/","",$ret));
   }
 
+  
+  function time_to_string($data)
+  {
+    return($data['Minute']." ".$data['Hour']." ".$data['Day']." ".$data['Month']." ".$data['Weekday']);
+  }
 
-  function save_object()
+  
+  function action_to_string($data)
   {
-    if(isset($_POST['gotomasses'])){
+    $tmp = $this->get_actions();
+    if(isset($tmp[$data['Action']])){
+      return($tmp[$data['Action']]);
+    }else{
+      return(_("Unknown"));
+    }
+  }
 
-      /* Check for input changes */
-      $ogs = $this->get_object_groups();
-      foreach($this->contents as $id => $data){
-        if(isset($_POST['mac_'.$id])){
-          $this->contents[$id]['MAC'] = $_POST['mac_'.$id];
-        }
-        if(isset($_POST['og_'.$id]) && in_array_ics($_POST['og_'.$id],$ogs)){
-          $this->contents[$id]['OG'] = $_POST['og_'.$id];
-        }
+  
+  function load_gotomasses_data()
+  {
+    $ui = get_userinfo();
+
+    /* Check file existence */
+    if(!file_exists($this->data_file) || !is_readable($this->data_file)){
+      print_red(sprintf(_("Can't locate or read gotomasses storage file '%s'."),$this->data_file));
+      return(FALSE);
+    }
+
+    /* check if file is readable */
+    $fp = @fopen($this->data_file,"r");
+    if(!$fp){
+      print_red(sprintf(_("Can't read gotomasses storage file '%s'."),$this->data_file));
+      return(FALSE);
+    }
+
+    /* Get file contents */
+    $data ="";
+    while(!feof($fp)){
+      $data.= fread($fp,512);
+    }
+
+    /* Get lines from file */
+    $this->tasks  = array(); 
+    $comment      = "";
+    $rows         = split("\n",$data);
+
+    /* Walk trough rows and parse data */
+    foreach($rows as $row){
+
+      /* Skip empty lines */
+      $row = trim($row);
+      if(empty($row)){
+        continue;
       }
 
-      /* check for remove requests */
-      $once = TRUE;
-      foreach($_POST as $name => $value){
-        if(preg_match("/^remove_[0-9]*_(x|y)$/",$name) && $once){
-          $once = FALSE;
-          $id = preg_replace("/^remove_/","",$name);
-          $id = preg_replace("/_(x|y)$/","",$id);
+      /* Get comment, if available */     
+      if(preg_match("/^#/",$row)){
+        $comment = preg_replace("/^#/","",$row);
+        continue;
+      }
 
-          if(isset($this->contents[$id])){
-            unset($this->contents[$id]);
+      /* Split row into minutes/ hours ...*/ 
+      $row    = preg_replace('/[\t ]/umi'," ",$row);
+      $row    = preg_replace('/  */umi'," ",$row);
+      $parts  = split(" ",$row);
+
+      if(count($parts) != 10){
+        print_red(_("Entry broken, skipped."));
+      }else{
+
+        $entry = array();
+        $entry['Minute']  = $parts[0];  
+        $entry['Hour']    = $parts[1];  
+        $entry['Day']     = $parts[2];  
+        $entry['Month']   = $parts[3];  
+        $entry['Weekday'] = $parts[4];  
+        $entry['Action']  = $parts[5];  
+        $entry['OGroup']  = $parts[6];  
+        $entry['Zone']    = $parts[7];  
+        $entry['Section'] = $parts[8];  
+        if($entry['Action'] == "initial_install"){
+          $tmp2 = split(";",$parts[9]);
+          foreach($tmp2 as $target){
+            $tmp = split(",",$target);
+            $entry['Initial_Target'][]  = array(
+                          "MAC"     => $tmp[0],
+                          "IP"      => $tmp[1],
+                          "NAME"    => $tmp[2]);
           }
+          $entry['Target']  = array();
+        }else{
+          $entry['Initial_Target']  = array();
+          $entry['Target']  = split(";",$parts[7]);
         }
+        $entry['Comment'] = $comment;  
+        $this->tasks []   = $entry;
       }
+    } 
+  }
 
-      /* Write back all changes */
-      if(isset($_POST['save_gotomass_changes'])){
-        $this->save_csv_data();
 
-        /* Call load again, so we will see if everything is fine. 
-         * And load_csv_data causes the contents_backup to be updated 
-         */
-        $this->load_csv_data();
+  function save_gotomasses_data()
+  {
+    $str = "#GOsa generated file, please just modify if you realy know what you do.";
+    foreach($this->tasks as $task){
+      $str .= "\n#".trim($task['Comment']);
+      $str .= "\n";
+      if($task['Action'] == "initial_install"){
+        $str .= "*     *     *     *     *     ";
+      }else{
+        $str .= str_pad($task['Minute'] ,5," ")." ";
+        $str .= str_pad($task['Hour']   ,5," ")." ";
+        $str .= str_pad($task['Day']    ,5," ")." ";
+        $str .= str_pad($task['Month']  ,5," ")." ";
+        $str .= str_pad($task['Weekday'],5," ")." ";
       }
+      $str .= str_pad($task['Action'] ,5," ")." ";
+      $str .= str_pad($task['OGroup'] ,5," ")." ";
+      $str .= str_pad($task['Zone']   ,5," ")." ";
+      $str .= str_pad($task['Section'],5," ")." ";
+      if($task['Action'] == "initial_install"){
+        foreach($task['Initial_Target'] as $target){
+          $str .= trim($target['MAC']).",".trim($target['IP']).",".trim($target['NAME']).";";
+        }
+      }else{
+        foreach($task['Target'] as $target){
+          $str .= $target.";";
+        }
+      }
+      $str = preg_replace("/;$/","",$str);
+    }
+
+    /* check file existence*/
+    $ui = get_userinfo();
+    if(!file_exists($this->data_file) || !is_writeable($this->data_file)){
+      print_red(sprintf(_("Can't locate or write gotomasses storage file '%s'."),$this->data_file));
+      return(FALSE);
+    }
+
+    /* check permissions */
+    $fp = @fopen($this->data_file,"w");
+    if(!$fp){
+      print_red(sprintf(_("Can't read gotomasses storage file '%s'."),$this->data_file));
+      return(FALSE);
+    }
 
-      /* Reload data from csv file ? */
-      if(isset($_POST['reload_gotomass_data'])){
-        $this->load_csv_data();
+    /* Write contents */
+    $str .= "\n";
+    fwrite($fp,$str);
+    fclose($fp);
+  }
+
+
+  function save_object()
+  {
+  }
+
+
+  /* Return list of object groups */
+  function get_object_groups()
+  {
+    $ret = array();
+    $ldap = $this->config->get_ldap_link();
+    $ldap->cd($this->config->current['BASE']);
+    $ldap->search("(&(objectClass=gosaGroupOfNames)(cn=*))",array("cn"));
+    while($attrs = $ldap->fetch()){
+      $ret[$attrs['cn'][0]] = $attrs['cn'][0];
+    }
+    return($ret); 
+  }
+
+  
+  function save()
+  {
+    $this->save_gotomasses_data();
+  }
+
+
+  function list_get_selected_items()
+  {
+    $ids = array();
+    foreach($_POST as $name => $value){
+      if(preg_match("/^item_selected_[0-9]*$/",$name)){
+        $id   = preg_replace("/^item_selected_/","",$name);
+        $ids[$id] = $id;
       }
     }
+    return($ids);
+  }
+
+
+  function get_actions()
+  {
+    /* Prepare list of available actions */
+    $actions = array(       "reboot"          => _("Reboot"),
+                            "localboot"       => _("Localboot"),
+                            "halt"            => _("Halt system"),
+                            "initial_install" => _("Initial installation"),
+                            "update"          => _("Update"),
+                            "reinstall"       => _("(Re)Install"),
+                            "rescan"          => _("Rescan"),
+                            "wake"            => _("Wake"),
+                            "memcheck"        => _("Memory check"));
+    return($actions);
   }
 
 
   function plInfo()
   {
     return (array(
-        "plShortName"   => _("Mass machine deployment"),
-        "plDescription" => _("Mass machine deployment addon"),
+        "plShortName"   => _("System mass deployment"),
+        "plDescription" => _("Provide a mechanism to automatically activate a set of systems"),
         "plSelfModify"  => FALSE,
         "plDepends"     => array(),
         "plPriority"    => 0,
         "plSection"     => array("addon"),
-        "plCategory"    => array("gotomasses" => array("objectClass" => "none", "description" => _("Mass machine deployment"))),
-        "plProvidedAcls" => array()
+        "plCategory"    => array("gotomasses" => array("objectClass" => "none", "description" => _("System mass deployment"))),
+        "plProvidedAcls" => array("Comment"   => _("Description"), 
+                                  "Action"    => _("Action"),
+                                  "Day"       => _("Day"),
+                                  "Minute"    => _("Minute"),
+                                  "Hour"      => _("Hour"),
+                                  "Month"     => _("Month"),
+                                  "Weekday"   => _("Week day"),
+                                  "Target"    => _("Target"))
         ));
   }
 }