Code

Removed show_ldap_error from gosa-core
[gosa.git] / gosa-core / include / class_gosaSupportDaemon.inc
1 <?php
2 /*
3  * This code is part of GOsa (http://www.gosa-project.org)
4  * Copyright (C) 2003-2008 GONICUS GmbH
5  *
6  * ID: $$Id$$
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
23 class gosaSupportDaemon
24 {
25   private $s_host       = "";
26   private $i_port       = 0;
27   private $s_encryption_key = "";
29   private $o_sock       = NULL;
30   private $f_timeout    = 2;
31   private $s_error      = "";
32   private $b_error      = FALSE;
34   private $is_connected     = FALSE;
37   /*! \brief  Creates a new gosaSupportDaemon object.
38     @param string   Host    The Host where the daemon is running on.  
39     @param integer  Port    The port which the daemon use.
40     @param string   Key     The encryption string.
41     @param boolean  Connect Directly connect to daemon socket.
42     @param float    Timeout The timelimit for all socket actions.
43    */
44   public function __construct($connect=TRUE,$timeout=2)
45   {
46     #FIXME: bad idea about referencing global variables from within classes
47     global $config;
49     # load from config, store statically
50     if (isset($config->current['GOSA_SI'])){
52       if ($this->s_host == ""){
53         $this->s_host= preg_replace("/^.*@([^:]+):.*$/", "$1", $config->current['GOSA_SI']);
54         $this->i_port= preg_replace("/^.*@[^:]+:(.*)$/", "$1", $config->current['GOSA_SI']);
55         $this->s_encryption_key = preg_replace("/^(.*)@[^:]+:.*$/", "$1", $config->current['GOSA_SI']);
56       }
58       $this->f_timeout = $timeout;
59       if($connect){
60         $this->connect();
61       }
62     }
63   }
66   /*! \brief  Establish daemon connection. 
67     @return boolean Returns true if the connection was succesfully established. 
68    */
69   public function connect()
70   {
71     $this->o_sock = new Socket_Client($this->s_host,$this->i_port,TRUE,$this->f_timeout);
72     if($this->o_sock->connected()){ 
73       $this->o_sock->setEncryptionKey($this->s_encryption_key); 
74       $this->is_connected = TRUE;
75     }else{
76       $this->set_error($this->o_sock->get_error());
77       $this->disconnect();
78       new log("debug","gosaSupportDaemon::connect()", "Could not connect to server.", array(),$this->get_error());
79     }
80     return($this->is_connected);
81   }
84   /*! \brief  Disconnect from gosa daemon.
85    */
86   public function disconnect()
87   {
88     $this->o_sock->close();
89     $this->is_connected = FALSE;
90   }
93   /*! \brief  Sets an error message, which can be returned with get_error().
94     @param  string  The Error message,
95    */
96   private function set_error($str)
97   {
98     $this->b_error = TRUE;
99     $this->s_error = $str;
100   }
103   /*! \brief  Sets an error message, which can be returned with get_error().
104     @param  string  The Error message,
105    */
106   private function reset_error()
107   {
108     $this->b_error = FALSE;
109     $this->s_error = "";
110   }
113   /*! \brief  Checks if an error occured.
114     @return boolean returns TRUE or FALSE, whether there is an error or not.
115    */
116   public function is_error()
117   {
118     return($this->b_error);
119   }
122   /*! \brief  Returns the last error. 
123     @return Returns the last error.
124    */
125   public function get_error()
126   {
127     $str = $this->s_error;
128     $str = preg_replace("/ /","&nbsp;",$str);
129     return($str);
130   }
133   /*! \brief  Returns an array containing all queued entries.
134     @return Array All queued entries as an array.
135    */
136   public function get_queued_entries($event_types = array("*"),$from=-1,$to=-1,$sort="timestamp DESC")
137   {
138     $this->reset_error();
139     $ret = array();
141     $tags = "";
142     foreach($event_types as $type){
143       $tags .= "<phrase><headertag>".$type."</headertag></phrase>";
144     }
145     if(count($event_types) > 1){
146       $tags = "<connector>or</connector>".$tags;
147     }
148     if(count($event_types)){
149       $tags = "<where><clause>".$tags."</clause></where>";
150     }
152     $xml_msg = "<xml>
153       <header>gosa_query_jobdb</header>
154       <target>GOSA</target>
155       <source>GOSA</source>
156       ".$tags."
158       <orderby>".$sort."</orderby>";
159 if($from != -1 && $to != -1){
160 $xml_msg.= "
161       <limit>
162        <from>".$from."</from>
163        <to>".$to."</to>
164       </limit>";
166 $xml_msg.= "
167       </xml>";
169     if($this->connect()){
170       $this->o_sock->write($xml_msg);
171       $str = trim($this->o_sock->read());
172       $entries = $this->xml_to_array($str);
173       if(isset($entries['XML']) && is_array($entries['XML'])){
175         /* Check if returned values represent a valid answer */
176         if(isset($entries['XML'])){
177           
178           /* Unset header tags */
179           foreach(array("HEADER","SOURCE","TARGET") as $type){
180             unset($entries['XML'][$type]);
181           }
182           $ret = $entries['XML']; 
183         }
184       }
185     }
186     
187     return($ret);
188   }
191   /*! \brief  Checks if the given ids are used queue ids.
192     @param  Array   The ids we want to check..
193     @return Array   An array containing all ids as index and TRUE/FALSE as value. 
194    */
195   public function ids_exist($ids)
196   {
197     if(!is_array($ids)){
198       trigger_error("Requires an array as parameter.");
199       return;
200     }
201     $this->reset_error();
203     $ret = array();
205     $xml_msg = "<xml>
206       <header>gosa_query_jobdb</header>
207       <target>GOSA</target>
208       <source>GOSA</source>
209       <where>
210       <clause>
211       <connector>or</connector>";
212     foreach($ids as $id){
213       $xml_msg .= "<phrase>
214         <operator>eq</operator>
215         <id>".$id."</id>
216         </phrase>";
217     }
218     $xml_msg .= "</clause>
219       </where>
220       </xml>";
222     if($this->connect()){
223       $this->o_sock->write($xml_msg);
224       $str = trim($this->o_sock->read());
225       $entries = $this->xml_to_array($str);
226       if(isset($entries['XML']) && is_array($entries['XML'])){
227         foreach($entries['XML'] as $entry){
228           if(isset($entry['ID'])){
229             $ret[] = $entry['ID'];
230           }
231         }
232       }
233     }
234     return($ret);
235   }
238   /*! \brief  Returns an entry containing all requested ids.
239     @param  Array   The IDs of the entries we want to return.
240     @return Array   Of the requested entries. 
241    */
242   public function get_entries_by_id($ids)
243   {
244     if(!is_array($ids)){
245       trigger_error("Requires an array as parameter.");
246       return;
247     }
248     $this->reset_error();
250     $ret = array();
252     $xml_msg = "<xml>
253       <header>gosa_query_jobdb</header>
254       <target>GOSA</target>
255       <source>GOSA</source>
256       <where>
257       <clause>
258       <connector>or</connector>";
259     foreach($ids as $id){
260       $xml_msg .= "<phrase>
261         <operator>eq</operator>
262         <id>".$id."</id>
263         </phrase>";
264     }
265     $xml_msg .= "</clause>
266       </where>
267       </xml>";
269     if($this->connect()){
270       $this->o_sock->write($xml_msg);
271       $str = trim($this->o_sock->read());
272       $entries = $this->xml_to_array($str); 
273       if(isset($entries['XML'])){
274         foreach($entries['XML'] as $name => $entry){
275           if(preg_match("/^ANSWER[0-9]*$/",$name)){
276             $ret[$name] = $entry;
277           }
278         }
279       }
280     }
281     return($ret);
282   }
285   /*! \brief  Checks if the given id is in use.
286     @param  Integer The ID of the entry.
287     @return Boolean TRUE if entry exists. 
288    */
289   public function id_exists($id)
290   {
291     if(!is_numeric($id)){
292       trigger_error("Requires an integer as parameter.");
293       return;
294     }
296     $this->reset_error();
298     $xml_msg = "<xml>
299       <header>gosa_query_jobdb</header>
300       <target>GOSA</target>
301       <source>GOSA</source>
302       <where>
303       <clause>
304       <phrase>
305       <operator>eq</operator>
306       <id>".$id."</id>
307       </phrase>
308       </clause>
309       </where>
310       </xml>";
312     if($this->connect()){
313       $this->o_sock->write($xml_msg);
314       $str = trim($this->o_sock->read());
315       $entries = $this->xml_to_array($str); 
316       if( isset($entries['XML']['HEADER']) && 
317           $entries['XML']['HEADER']=="answer" && 
318           isset($entries['XML']['ANSWER1'])){
319         return(TRUE);
320       }
321     }
322     return(FALSE);
323   }
326   /*! \brief  Returns an entry from the gosaSupportQueue
327     @param  Integer The ID of the entry we want to return.
328     @return Array   Of the requested entry. 
329    */
330   public function get_entry_by_id($id)
331   {
332     if(!is_numeric($id)){
333       trigger_error("Requires an integer as parameter.");
334       return;
335     }
336     $this->reset_error();
337   
338     $ret = array();
339     $xml_msg = "<xml>
340       <header>gosa_query_jobdb</header>
341       <target>GOSA</target>
342       <source>GOSA</source>
343       <where>
344       <clause>
345       <phrase>
346       <operator>eq</operator>
347       <id>".$id."</id>
348       </phrase>
349       </clause>
350       </where>
351       </xml>";
352     if($this->connect()){
353       $this->o_sock->write($xml_msg);
354       $str = trim($this->o_sock->read());
355       $entries = $this->xml_to_array($str); 
356       if( isset($entries['XML']['HEADER']) &&
357           $entries['XML']['HEADER']=="answer" &&
358           isset($entries['XML']['ANSWER1'])){
359         $ret = $entries['XML']['ANSWER1'];
360       }
361     }
362     return($ret);
363   }
366   /*! \brief  Removes a set of entries from the GOsa support queue. 
367     @param  Array The IDs to remove.
368     @return Boolean True on success.
369    */
370   public function remove_entries($ids)
371   {
372     if(!is_array($ids)){
373       trigger_error("Requires an array as parameter.");
374       return;
375     }
377     $this->reset_error();
379     $ret = array();
381     $xml_msg = "<xml>
382       <header>gosa_delete_jobdb_entry</header>
383       <target>GOSA</target>
384       <source>GOSA</source>
385       <where>
386       <clause>
387       <connector>or</connector>";
388     foreach($ids as $id){
389       $xml_msg .= "<phrase>
390         <operator>eq</operator>
391         <id>".$id."</id>
392         </phrase>";
393     }
394     $xml_msg .= "</clause>
395       </where>
396       </xml>";
398     if($this->connect()){
399       $this->o_sock->write($xml_msg);
400       $str = $this->o_sock->read();
401       $entries = $this->xml_to_array($str);
402       if(isset($entries['XML']) || isset($entries['COUNT'])){
403         new log("debug","DaemonEvent (IDS) ", "gosaSupportDaemon::remove_entries()", $ids,"SUCCESS");
404         return(TRUE);
405       }else{
406         new log("debug","DaemonEvent (IDS) ", "gosaSupportDaemon::remove_entries()", $ids,"FAILED ".$this->get_error());
407       }
408     }
409     return(FALSE);
410   }
414   /*! \brief  Removes an entry from the GOsa support queue. 
415     @param  Integer The ID of the entry we want to remove.
416     @return Boolean True on success.
417    */
418   public function remove_entry($id)
419   {
420     return($this->remove_entries(array($id)));
421   }
424   /*! \brief  Parses the given xml string into an array 
425     @param  String XML string  
426     @return Array Returns an array containing the xml structure. 
427    */
428   private function xml_to_array($xml)
429   {
430     $params = array();
431     $level = array();
432     $parser  = xml_parser_create_ns();
433     xml_parse_into_struct($parser, $xml, $vals, $index);
435     $err_id = xml_get_error_code($parser);
436     if($err_id){
437       xml_parser_free($parser);
438     }else{
439       xml_parser_free($parser);
441       foreach ($vals as $xml_elem) {
442         if ($xml_elem['type'] == 'open') {
443           if (array_key_exists('attributes',$xml_elem)) {
444             list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
445           } else {
446             $level[$xml_elem['level']] = $xml_elem['tag'];
447           }
448         }
449         if ($xml_elem['type'] == 'complete') {
450           $start_level = 1;
451           $php_stmt = '$params';
452           while($start_level < $xml_elem['level']) {
453             $php_stmt .= '[$level['.$start_level.']]';
454             $start_level++;
455           }
456           $php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
457           @eval($php_stmt);
458         }
459       }
460     }
462     if(!isset($params['XML'])){
463       if (!array_key_exists('XML', $params)){
464         $this->set_error(_("Could not parse XML."));
465       }
466       $params = array("COUNT" => 0);
467     }
469     return($params); 
470   }
473   /*! \brief  Updates an entry with a set of new values, 
474     @param  Integer The ID of the entry, we want to update.
475     @param  Array   The variables to update.   
476     @return Boolean Returns TRUE on success. 
477    */
478   public function update_entries($ids,$data)
479   {
480     $this->reset_error();
481     if(!is_array($ids)){
482       trigger_error("Requires an array as first parameter.");
483       return;
484     }
486     if(!is_array($data)){
487       trigger_error("Requires an array as second parameter.");
488       return;
489     }
491     $attr = "";
492     foreach($data as $key => $value){
493       if(is_array($value)){
494         foreach($value as $sub_value){
495           $attr.= "<$key>".strtolower($sub_value)."</$key>\n";
496         }
497       }else{
498         $attr.= "<$key>".strtolower($value)."</$key>\n";
499       }
500     }
502     $xml_msg = "<xml>
503       <header>gosa_update_status_jobdb_entry</header>
504       <target>GOSA</target>
505       <source>GOSA</source>
506       <where>
507       <clause>
508       <connector>or</connector>";
509     foreach($ids as $id){
510       $xml_msg .= "<phrase>
511         <operator>eq</operator>
512         <id>".$id."</id>
513         </phrase>";
514     }
515     $xml_msg .= "</clause>
516       </where>
517       <update>
518       ".$attr." 
519       </update>
520       </xml>";
522     if($this->connect()){
524       $this->o_sock->write($xml_msg);
525       $str      = trim($this->o_sock->read());
526       $entries = $this->xml_to_array($str);
527       if(isset($entries['XML'])){
528         if(isset($entries['XML']['ERROR_STRING'])) {
529           $this->set_error($entries['XML']['ERROR_STRING']);
530           new log("debug","DaemonEvent (IDS) ", "gosaSupportDaemon::update_entries()", $ids,"FAILED setting (".$attr.") error was ".$this->get_error());
531           return(FALSE);
532         }
533         new log("debug","DaemonEvent (IDS) ", "gosaSupportDaemon::update_entries()", $ids,"SUCCESS");
534         return(TRUE);
535       }
536     }
537     return(FALSE);
538   }
541   /*! \brief  Returns the number of currently queued objects.
542       @return Integer  
543    */
544   public function number_of_queued_entries()
545   {
546     $xml_msg ="<xml><header>gosa_count_jobdb</header><target>GOSA</target><source>GOSA</source></xml>";
547     $this->connect();
548     if($this->connect()){
549       $this->o_sock->write($xml_msg);
550       $str     = trim($this->o_sock->read());
551       $entries = $this->xml_to_array($str);
552       if(isset($entries['XML'])){
553         return($entries['XML']['COUNT']);
554       }
555     }
556     return(-1);
557   } 
560   public function send_data($header, $to, $data= array(), $answer_expected = FALSE)
561   {
562     $xml_message= "";
564     /* Prepare data */
565     foreach ($data as $key => $value){
566       if(is_array($value)){
567         foreach($value as $sub_val){
568           $xml_message.= "<$key>$sub_value</$key>";
569         }
570       }else{
571         $xml_message.= "<$key>$value</$key>";
572       }
573     }
575     /* Multiple targets? */
576     if (!is_array($to)){
577       $to_targets= array($to);
578     } else {
579       $to_targets= $to;
580     }
582     /* Build target strings */
583     $target ="";
584     foreach($to_targets as $to){
585       $target.= "<target>$to</target>";
586     }
588     return $this->_send("<xml><header>$header</header><source>GOSA</source>$target".$xml_message."</xml>",$answer_expected);
589   }
592   /* Allows simply appending a new DaemonEvent 
593    */
594   public function append($event)
595   {
596     if(!($event instanceof DaemonEvent)){
597       return(FALSE);
598     }
599   
600     $this->reset_error();
602     /* Add to queue if new 
603      */
604     if($event->is_new()){
606       $request_answer = FALSE;
607       if($event->get_type() == SCHEDULED_EVENT){
608         $action = $event->get_schedule_action();
609         $request_answer = TRUE;
610       }elseif($event->get_type() == TRIGGERED_EVENT){
611         $action = $event->get_trigger_action();
612       }else{
613         trigger_error("Unknown type of queue event given.");
614         return(FALSE);
615       }
617       /* Get event informations, like targets..
618        */
619       $targets    = $event->get_targets();
620       $data       = $event->save();
622       /* Append an entry for each target 
623        */
624       foreach($targets as $target){
625         $data['macaddress'] = $target;
626         $this->send_data($action,$target,$data,$request_answer);
628         if($this->is_error()){
629           return(FALSE);
630         }
631       }
632       return(TRUE);
633     }else{
635       /* Updated edited entry.
636        */
637       $id                 = $event->get_id();
638       $data               = $event->save();
639       return($this->update_entries(array($id),$data));
640     }
642     return(FALSE);
643   }
646 /*! \brief  Returns an array containing all queued entries.
647     @return Array All queued entries as an array.
648    */
649   public function _send($data, $answer_expected= FALSE)
650   {
651     $this->reset_error();
652     $ret = array();
654     if($this->connect()){
655       $this->o_sock->write($data);
656       if ($answer_expected){
657         $str = trim($this->o_sock->read());
658         $entries = $this->xml_to_array($str);
659         if(isset($entries['XML']) && is_array($entries['XML'])){
660           $ret = $entries;
661           if(isset($entries['XML']['ERROR_STRING'])) {
662             $this->set_error($entries['XML']['ERROR_STRING']);
663             new log("debug","DaemonEvent (IDS) ", "gosaSupportDaemon::_send()", array($data=>$data),"FAILED ".$this->get_error());
664           }else{
665             new log("debug","DaemonEvent (IDS) ", "gosaSupportDaemon::_send()", array($data=>$data),"SUCCESS");
666           }
667         }
668       }else{
669         new log("debug","DaemonEvent (IDS) ", "gosaSupportDaemon::_send()", array($data=>$data),"Fire & forget, not result.! ".$this->get_error());
670       }
671     }
672     return($ret);
673   }
676   static function send($header, $to, $data= array(), $answer_expected = FALSE)
677   {
678     $xml_message= "";
680     /* Get communication object */
681     $d= new gosaSupportDaemon(TRUE,10);
683     /* Prepare data */
684     foreach ($data as $key => $value){
685       if(is_array($value)){
686         foreach($value as $sub_val){
687           $xml_message.= "<$key>$sub_value</$key>";
688         }
689       }else{
690         $xml_message.= "<$key>$value</$key>";
691       }
692     }
694     /* Multiple targets? */
695     if (!is_array($to)){
696       $to_targets= array($to);
697     } else {
698       $to_targets= $to;
699     }
701     /* Build target strings */
702     $target ="";
703     foreach($to_targets as $to){
704       $target.= "<target>$to</target>";
705     }
707     return $d->_send("<xml><header>$header</header><source>GOSA</source>$target".$xml_message."</xml>",$answer_expected);
708   }
711   /*! \brief  Removes all jobs from the queue that are tiggered with a specific macAddress.
712       @param  String  $mac  The mac address for which we want to remove all jobs.      
713    */
714   function clean_queue_from_mac($mac)
715   {
716     global $config;
718     /* First of all we have to check which jobs are startet 
719      *  for $mac 
720      */
721     $xml_msg ="<xml><header>gosa_query_jobdb</header><target>GOSA</target><source>GOSA</source><where><clause><phrase><macaddress>".$mac."</macaddress></phrase></clause></where></xml>";  
722     
723     new log("debug","DaemonEvent ", "gosaSupportDaemon::clean_queue_from_mac()", array($mac => $mac)," start cleaning.");
724  
725     $data = $this->_send($xml_msg,TRUE);
726     if(is_array($data) && isset($data['XML'])){
727       $already_aborted = FALSE;
728       foreach($data['XML']  as $name => $entry){
729         if(preg_match("/answer[0-9]*/i",$name)){
730           $entry['STATUS'] = strtoupper($entry['STATUS']);
731           switch($entry['STATUS']){
733             case 'PROCESSING' :
735               /* Send abort event, but only once 
736                */
737               if($already_aborted){
738                 break;
739               }elseif(class_available("DaemonEvent_faireboot")){
740                 $already_aborted = TRUE;
741                 $tmp = new DaemonEvent_faireboot($config);
742                 $tmp->add_targets(array($mac));
743                 $tmp->set_type(TRIGGERED_EVENT);
744                 if(!$this->append($tmp)){
745                   msg_dialog::display(_("Error"), sprintf(_("Cannot send abort event for entry: %s"),$entry['ID']) , ERROR_DIALOG);
746                   new log("debug","DaemonEvent ", "gosaSupportDaemon::clean_queue_from_mac()", array($mac => $mac),
747                       "FAILED, could not send 'DaemonEvent_faireboot' for entry ID (".$entry['ID'].") - ".$this->get_error());
748                 }else{
749                   new log("debug","DaemonEvent ", "gosaSupportDaemon::clean_queue_from_mac()", array($mac => $mac),
750                       "SUCCESS, send 'DaemonEvent_faireboot' for entry ID (".$entry['ID'].")");
751                 }
752                 ;break;
753               }else{
754                 /* Couldn't find abort event, just remove entry */
755               }
757             case 'WAITING':
758             case 'ERROR':
759             default :
760             
761               /* Simply remove entries from queue. 
762                *  Failed or waiting events, can be removed without any trouble.
763                */ 
764               if(!$this->remove_entries(array($entry['ID']))){
765                 msg_dialog::display(_("Error"), sprintf(_("Cannot remove entry: %s"),$entry['ID']) , ERROR_DIALOG);
766               }
767               ;break;
768           }
769     
770         }
771       }
772     }
773   }
776 static function ping($target)
778   if (tests::is_mac($target)){
779     /* Get communication object */
780     $d= new gosaSupportDaemon(TRUE,0.5);
781     $answer= $d->_send("<xml><header>gosa_ping</header><source>GOSA</source><target>$target</target></xml>", TRUE);
782     return (count($answer) ? TRUE:FALSE);
783   }
785   return (FALSE);
790 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
791 ?>