Code

Fixed picture removement
[gosa.git] / plugins / personal / generic / class_user.inc
1 <?php
2 /*!
3   \brief   user plugin
4   \author  Cajus Pollmeier <pollmeier@gonicus.de>
5   \version 2.00
6   \date    24.07.2003
8   This class provides the functionality to read and write all attributes
9   relevant for person, organizationalPerson, inetOrgPerson and gosaAccount
10   from/to the LDAP. It does syntax checking and displays the formulars required.
11  */
13 class user extends plugin
14 {
15   /* Definitions */
16   var $plHeadline= "Generic";
17   var $plDescription= "This does something";
19   /* CLI vars */
20   var $cli_summary= "Handling of GOsa's user base object";
21   var $cli_description= "Some longer text\nfor help";
22   var $cli_parameters= array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
24   /* Plugin specific values */
25   var $base= "";
26   var $cn= "";
27   var $personalTitle= "";
28   var $academicTitle= "";
29   var $homePostalAddress= "";
30   var $homePhone= "";
31   var $labeledURI= "";
32   var $o= "";
33   var $ou= "";
34   var $departmentNumber= "";
35   var $employeeNumber= "";
36   var $employeeType= "";
37   var $roomNumber= "";
38   var $telephoneNumber= "";
39   var $facsimileTelephoneNumber= "";
40   var $mobile= "";
41   var $pager= "";
42   var $l= "";
43   var $st= "";
44   var $postalAddress= "";
45   var $dateOfBirth;
46   var $use_dob= "0";
47   var $gender="0";
48   var $preferredLanguage="0";
50   var $jpegPhoto= "*removed*";
51   var $photoData= "";
52   var $old_jpegPhoto= "";
53   var $old_photoData= "";
54   var $cert_dialog= FALSE;
55   var $picture_dialog= FALSE;
57   var $userPKCS12= "";
58   var $userSMIMECertificate= "";
59   var $userCertificate= "";
60   var $certificateSerialNumber= "";
61   var $old_certificateSerialNumber= "";
62   var $old_userPKCS12= "";
63   var $old_userSMIMECertificate= "";
64   var $old_userCertificate= "";
66   var $gouvernmentOrganizationalUnit= "";
67   var $houseIdentifier= "";
68   var $street= "";
69   var $postalCode= "";
70   var $vocation= "";
71   var $ivbbLastDeliveryCollective= "";
72   var $gouvernmentOrganizationalPersonLocality= "";
73   var $gouvernmentOrganizationalUnitDescription= "";
74   var $gouvernmentOrganizationalUnitSubjectArea= "";
75   var $functionalTitle= "";
76   var $role= "";
77   var $publicVisible= "";
79   var $dialog;
81   /* variables to trigger password changes */
82   var $pw_storage= "crypt";
83   var $last_pw_storage= "unset";
84   var $had_userCertificate= FALSE;
86   /* attribute list for save action */
87   var $attributes= array("sn", "givenName", "uid", "personalTitle", "academicTitle",
88       "homePostalAddress", "homePhone", "labeledURI", "o", "ou", "dateOfBirth", "gender","preferredLanguage",
89       "departmentNumber", "employeeNumber", "employeeType", "l", "st","jpegPhoto",
90       "roomNumber", "telephoneNumber", "mobile", "pager", "cn", "userPKCS12",
91       "postalAddress", "facsimileTelephoneNumber", "userSMIMECertificate");
93   var $objectclasses= array("top", "person", "organizationalPerson", "inetOrgPerson",
94       "gosaAccount");
96   /* attributes that are part of the government mode */
97   var $govattrs= array("gouvernmentOrganizationalUnit", "houseIdentifier", "vocation",
98       "ivbbLastDeliveryCollective", "gouvernmentOrganizationalPersonLocality",
99       "gouvernmentOrganizationalUnitDescription","gouvernmentOrganizationalUnitSubjectArea",
100       "functionalTitle", "certificateSerialNumber", "publicVisible", "street", "role",
101       "postalCode");
104   /* constructor, if 'dn' is set, the node loads the given
105      'dn' from LDAP */
106   function user ($config, $dn= NULL)
107   {
108     $this->config= $config;
109     /* Configuration is fine, allways */
110     if ($this->config->current['GOVERNMENTMODE']){
111       $this->attributes=array_merge($this->attributes,$this->govattrs);
112     }
114     /* Load base attributes */
115     plugin::plugin ($config, $dn);
117     if ($this->config->current['GOVERNMENTMODE']){
118       /* Fix public visible attribute if unset */
119       if (!isset($this->attrs['publicVisible'])){
120         $this->publicVisible == "nein";
121       }
122     }
124     /* Load government mode attributes */
125     if ($this->config->current['GOVERNMENTMODE']){
126       /* Copy all attributs */
127       foreach ($this->govattrs as $val){
128         if (isset($this->attrs["$val"][0])){
129           $this->$val= $this->attrs["$val"][0];
130         }
131       }
132     }
134     /* Create me for new accounts */
135     if ($dn == "new"){
136       $this->is_account= TRUE;
137     }
139     /* Make hash default to md5 if not set in config */
140     if (!isset($this->config->current['HASH'])){
141       $hash= "md5";
142     } else {
143       $hash= $this->config->current['HASH'];
144     }
146     /* Load data from LDAP? */
147     if ($dn != NULL){
149       /* Do base conversation */
150       if ($this->dn == "new"){
151         $ui= get_userinfo();
152         $this->base= dn2base($ui->dn);
153       } else {
154         $this->base= dn2base($dn);
155       }
157       /* get password storage type */
158       if (isset ($this->attrs['userPassword'][0])){
159         /* Initialize local array */
160         $matches= array();
161         if (preg_match ("/^{([^}]+)}(.+)/", $this->attrs['userPassword'][0], $matches)){
162           $this->pw_storage= strtolower($matches[1]);
163         } else {
164           if ($this->attrs['userPassword'][0] != ""){
165             $this->pw_storage= "clear";
166           } else {
167             $this->pw_storage= $hash;
168           }
169         }
170       } else {
171         /* Preset with vaule from configuration */
172         $this->pw_storage= $hash;
173       }
175       /* Load extra attributes: certificate and picture */
176       $this->load_picture();
177       $this->load_cert();
178       if ($this->userCertificate != ""){
179         $this->had_userCertificate= TRUE;
180       }
181     }
183     /* Reset password storage indicator, used by password_change_needed() */
184     if ($dn == "new"){
185       $this->last_pw_storage= "unset";
186     } else {
187       $this->last_pw_storage= $this->pw_storage;
188     }
190     /* Generate dateOfBirth entry */
191     if (isset ($this->attrs['dateOfBirth'])){
192       /* This entry is ISO 8601 conform */
193       list($year, $month, $day)= split("-", $this->attrs['dateOfBirth'][0], 3);
194     
195       $this->dateOfBirth=array( 'mon'=> $month,"mday"=> $day,"year"=> $year);
196       $this->use_dob= "1";
197     } else {
198       $this->use_dob= "0";
199     }
201     /* Put gender attribute to upper case */
202     if (isset ($this->attrs['gender'])){
203       $this->gender= strtoupper($this->attrs['gender'][0]);
204     }
205   }
208   /* execute generates the html output for this node */
209   function execute()
210   {
211     /* Call parent execute */
212     plugin::execute();
214     $smarty= get_smarty();
216     /* Fill calendar */
217     if ($this->dateOfBirth == "0"){
218       $date= getdate();
219     } else {
220       if(is_array($this->dateOfBirth)){
221         $date = $this->dateOfBirth;
222       }else{
223         $date = getdate($this->dateOfBirth);
224       } 
225     }
227     $days= array();
228     for($d= 1; $d<32; $d++){
229       $days[$d]= $d;
230     }
231     $years= array();
233     if(($date['year']-100)<1901){
234       $start = 1901;
235     }else{
236       $start = $date['year']-100;
237     }
239     $end = $start +100;
240     
241     for($y= $start; $y<=$end; $y++){
242       $years[]= $y;
243     }
244     $years['-']= "-&nbsp;";
245     $months= array(_("January"), _("February"), _("March"), _("April"),
246         _("May"), _("June"), _("July"), _("August"), _("September"),
247         _("October"), _("November"), _("December"), '-' => '-&nbsp;');
248     $smarty->assign("day", $date["mday"]);
249     $smarty->assign("days", $days);
250     $smarty->assign("months", $months);
251     $smarty->assign("month", $date["mon"]-1);
252     $smarty->assign("years", $years);
253     $smarty->assign("year", $date["year"]);
255     /* Assign sex */
256     $sex= array(0 => "&nbsp;", "F" => _("female"), "M" => _("male"));
257     $smarty->assign("gender_list", $sex);
259     /* Assign prefered langage */
260     $language= array(0 => "&nbsp;", "fr_FR" => ("fr_FR"), "en_EN" => ("en_EN"), 
261                                     "de_DE" => ("de_DE"), "it_IT" => ("it_IT"), 
262                                     "nl_NL" => ("nl_NL"), "ru_RU" => ("ru_RU"));
263     $smarty->assign("preferredLanguage_list", $language);
265     /* Get random number for pictures */
266     srand((double)microtime()*1000000); 
267     $smarty->assign("rand", rand(0, 10000));
269     /* Do we represent a valid gosaAccount? */
270     if (!$this->is_account){
271       echo "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
272         _("This account has no valid GOsa extensions.")."</b>";
273       return;
274     }
276     /* Base select dialog */
277     $once = true;
278     foreach($_POST as $name => $value){
279       if(preg_match("/^chooseBase/",$name) && $once){
280         $once = false;
281         $this->dialog = new baseSelectDialog($this->config,$this->allowedBasesToMoveTo());
282         $this->dialog->setCurrentBase($this->base);
283       }
284     }
286     /* Dialog handling */
287     if(is_object($this->dialog)){
288       /* Must be called before save_object */
289       $this->dialog->save_object();
290    
291       if($this->dialog->isClosed()){
292         $this->dialog = false;
293       }elseif($this->dialog->isSelected()){
294         $this->base = $this->dialog->isSelected();
295         $this->dialog= false;
296       }else{
297         return($this->dialog->execute());
298       }
299     }
301     /* Want picture edit dialog? */
302     if (isset($_POST['edit_picture'])){
303       /* Save values for later recovery, in case some presses
304          the cancel button. */
305       $this->old_jpegPhoto= $this->jpegPhoto;
306       $this->old_photoData= $this->photoData;
307       $this->picture_dialog= TRUE;
308       $this->dialog= TRUE;
309     }
311     /* Remove picture? */
312     if (isset($_POST['picture_remove'])){
313       $this->set_picture ();
314       $this->jpegPhoto= "*removed*";
315       $this->is_modified= TRUE;
317       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
318     }
320     /* Save picture */
321     if (isset($_POST['picture_edit_finish'])){
323       /* Check for clean upload */
324       if ($_FILES['picture_file']['name'] != ""){
325         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
326           print_red(_("The specified file has not been uploaded via HTTP POST! Aborted."));
327           exit;
328         }
330         /* Activate new picture */
331         $this->set_picture($_FILES['picture_file']['tmp_name']);
332       }
333       $this->picture_dialog= FALSE;
334       $this->dialog= FALSE;
335       $this->is_modified= TRUE;
336     }
339     /* Cancel picture */
340     if (isset($_POST['picture_edit_cancel'])){
342       /* Restore values */
343       $this->jpegPhoto= $this->old_jpegPhoto;
344       $this->photoData= $this->old_photoData;
346       /* Update picture */
347       $_SESSION['binary']= $this->photoData;
348       $_SESSION['binarytype']= "image/jpeg";
349       $this->picture_dialog= FALSE;
350       $this->dialog= FALSE;
351     }
353     /* Toggle dateOfBirth information */
354     if (isset($_POST['set_dob'])){
355       $this->use_dob= ($this->use_dob == "0")?"1":"0";
356     }
359     /* Want certificate= */
360     if (isset($_POST['edit_cert'])){
362       /* Save original values for later reconstruction */
363       foreach (array("certificateSerialNumber", "userCertificate",
364             "userSMIMECertificate", "userPKCS12") as $val){
366         $oval= "old_$val";
367         $this->$oval= $this->$val;
368       }
370       $this->cert_dialog= TRUE;
371       $this->dialog= TRUE;
372     }
375     /* Cancel certificate dialog */
376     if (isset($_POST['cert_edit_cancel'])){
378       /* Restore original values in case of 'cancel' */
379       foreach (array("certificateSerialNumber", "userCertificate",
380             "userSMIMECertificate", "userPKCS12") as $val){
382         $oval= "old_$val";
383         $this->$val= $this->$oval;
384       }
385       $this->cert_dialog= FALSE;
386       $this->dialog= FALSE;
387     }
390     /* Remove certificate? */
391     foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12") as $val){
392       if (isset($_POST["remove_$val"])){
394         /* Reset specified cert*/
395         $this->$val= "";
396         $this->is_modified= TRUE;
397       }
398     }
401     /* Upload new cert and close dialog? */     
402     if (isset($_POST['cert_edit_finish'])){
404       /* for all certificates do */
405       foreach (array ("userCertificate", "userSMIMECertificate", "userPKCS12")
406           as $val){
408         /* Check for clean upload */
409         if (array_key_exists($val."_file", $_FILES) &&
410             array_key_exists('name', $_FILES[$val."_file"]) &&
411             $_FILES[$val."_file"]['name'] != "" &&
412             is_uploaded_file($_FILES[$val."_file"]['tmp_name'])) {
413           $this->set_cert("$val", $_FILES[$val."_file"]['tmp_name']);
414         }
415       }
417       /* Save serial number */
418       if (isset($_POST["certificateSerialNumber"]) &&
419           $_POST["certificateSerialNumber"] != ""){
421         if (!is_id($_POST["certificateSerialNumber"])){
422           print_red (_("Please enter a valid serial number"));
424           foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
425             if ($this->$cert != ""){
426               $smarty->assign("$cert"."_state", "true");
427             } else {
428               $smarty->assign("$cert"."_state", "");
429             }
430           }
431           return ($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
432         }
434         $this->certificateSerialNumber= $_POST["certificateSerialNumber"];
435         $this->is_modified= TRUE;
436       }
438       $this->cert_dialog= FALSE;
439       $this->dialog= FALSE;
440     }
442     /* Display picture dialog */
443     if ($this->picture_dialog){
444       return($smarty->fetch (get_template_path('generic_picture.tpl', TRUE, dirname(__FILE__))));
445     }
447     /* Display cert dialog */
448     if ($this->cert_dialog){
449       foreach(array("userCertificate", "userSMIMECertificate", "userPKCS12") as $cert){
450         if ($this->$cert != ""){
451           /* import certificate */
452           $certificate = new certificate;
453           $certificate->import($this->$cert);
454       
455           /* Read out data*/
456           $timeto   = $certificate->getvalidto_date();
457           $timefrom = $certificate->getvalidfrom_date();
458           $str = "<table summary=\"\" border=0><tr><td style='vertical-align:top'>CN</td><td>".preg_replace("/ /", "&nbsp;", $certificate->getname())."</td></tr></table><br>".
459                   sprintf(_("Certificate is valid from %s to %s and is currently %s."), "<b>".date('d M Y',$timefrom)."</b>","<b>".date('d M Y',$timeto)."</b>", $certificate->isvalid()?"<b><font style='color:green'>"._("valid")."</font></b>":"<b><font style='color:red'>"._("invalid")."</font></b>");
460           $smarty->assign($cert."info",$str);
461           $smarty->assign($cert."_state","true");
462         } else {
463           $smarty->assign($cert."info", "<i>"._("No certificate installed")."</i>");
464           $smarty->assign($cert."_state","");
465         }
466       }
467       $smarty->assign("governmentmode", "false");
468       return($smarty->fetch (get_template_path('generic_certs.tpl', TRUE, dirname(__FILE__))));
469     }
471     /* Show us the edit screen */
472     @$smarty->assign("bases", $this->allowedBasesToMoveTo());
473 #  $smarty->assign("bases", $this->config->idepartments);
474     $smarty->assign("base_select",      $this->base);
475     $smarty->assign("selectmode",       chkacl($this->acl, "create"));
476     $smarty->assign("certificatesACL",  chkacl($this->acl, "certificates"));
477     $smarty->assign("jpegPhotoACL",     chkacl($this->acl, "jpegPhoto"));
479     /* Prepare password hashes */
480     if ($this->pw_storage == ""){
481       $this->pw_storage= $this->config->current['HASH'];
482     }
484     $temp   = @passwordMethod::get_available_methods();
485     $hashes = $temp['name'];
486     
487     $smarty->assign("pwmode", $hashes);
488     $smarty->assign("pwmode_select", $this->pw_storage);
489     $smarty->assign("passwordStorageACL", chkacl($this->acl, "passwordStorage"));
491     /* Load attributes and acl's */
492     foreach($this->attributes as $val){
493       $smarty->assign("$val", $this->$val);
494       $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
495     }
497     /* Save government mode attributes */
498     if (isset($this->config->current['GOVERNMENTMODE']) &&
499         preg_match('/true/i', $this->config->current['GOVERNMENTMODE'])){
500       $smarty->assign("governmentmode", "true");
501       $ivbbmodes= array("nein", "ivbv", "testa", "ivbv,testa", "internet",
502           "internet,ivbv", "internet,testa", "internet,ivbv,testa");
503       $smarty->assign("ivbbmodes", $ivbbmodes);
504       foreach ($this->govattrs as $val){
505         $smarty->assign("$val", $this->$val);
506         $smarty->assign("$val"."ACL", chkacl($this->acl,$val));
507       }
508     } else {
509       $smarty->assign("governmentmode", "false");
510     }
512     /* Special mode for uid */
513     $uidACL= "";
514     if (isset ($this->dn)){
515       if ($this->dn != "new"){
516         $uidACL="readonly";
517       }
518     }  else {
519       $uidACL= "readonly";
520     }
521     $uidACL.= " ".chkacl($this->acl, "uid");
522     
523     $smarty->assign("uidACL", $uidACL);
524     $smarty->assign("is_template", $this->is_template);
525     $smarty->assign("use_dob", $this->use_dob);
527     if (isset($this->parent)){
528       if (isset($this->parent->by_object['phoneAccount']) &&
529           $this->parent->by_object['phoneAccount']->is_account){
530         $smarty->assign("has_phoneaccount", "true");
531       } else {
532         $smarty->assign("has_phoneaccount", "false");
533       }
534     } else {
535       $smarty->assign("has_phoneaccount", "false");
536     }
537     return($smarty->fetch (get_template_path('generic.tpl', TRUE, dirname(__FILE__))));
538   }
541   /* remove object from parent */
542   function remove_from_parent()
543   {
544     $ldap= $this->config->get_ldap_link();
545     $ldap->rmdir ($this->dn);
546     show_ldap_error($ldap->get_error(), _("Removing generic user account failed"));
548     /* Delete references to groups */
549     $ldap->cd ($this->config->current['BASE']);
550     $ldap->search ("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array("uid"));
551     while ($ldap->fetch()){
552       $g= new group($this->config, $ldap->getDN());
553       $g->removeUser($this->uid);
554       $g->save ();
555     }
557     /* Delete references to object groups */
558     $ldap->cd ($this->config->current['BASE']);
559     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".$this->dn."))", array("cn"));
560     while ($ldap->fetch()){
561       $og= new ogroup($this->config, $ldap->getDN());
562       unset($og->member[$this->dn]);
563       $og->save ();
564     }
566     /* Optionally execute a command after we're done */
567     $this->handle_post_events("remove");
568   }
571   /* Save data to object */
572   function save_object()
573   {
574     if (isset($_POST['generic'])){
576       /* Parents save function */
577       plugin::save_object ();
579       /* Save government mode attributes */
580       if ($this->config->current['GOVERNMENTMODE']){
581         foreach ($this->govattrs as $val){
582           if (chkacl ($this->acl, "$val") == "" && isset ($_POST["$val"])){
583             $data= stripcslashes($_POST["$val"]);
584             if ($data != $this->$val){
585               $this->is_modified= TRUE;
586             }
587             $this->$val= $data;
588           }
589         }
590       }
592       /* In template mode, the uid is autogenerated... */
593       if ($this->is_template){
594         $this->uid= strtolower($this->sn);
595         $this->givenName= $this->sn;
596       }
598       /* Save base and pw_storage, since these are no LDAP attributes */
599       if (isset($_POST['base'])){
600         foreach(array("base", "pw_storage") as $val){
601           if(isset($_POST[$val])){
602             $data= validate($_POST[$val]);
603             if ($data != $this->$val){
604               $this->is_modified= TRUE;
605             }
606             $this->$val= $data;
607           }
608         }
609       }
610     }
611   }
613   function rebind($ldap, $referral)
614   {
615     $credentials= LDAP::get_credentials($referral, $this->config->current['REFERRAL']);
616     if (ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
617       $this->error = "Success";
618       $this->hascon=true;
619       $this->reconnect= true;
620       return (0);
621     } else {
622       $this->error = "Could not bind to " . $credentials['ADMIN'];
623       return NULL;
624     }
625   }
627   /* Save data to LDAP, depending on is_account we save or delete */
628   function save()
629   {
630     /* Only force save of changes .... 
631        If this attributes aren't changed, avoid saving.
632      */
633     if ($this->use_dob == "1"){
634       $this->dateOfBirth= date("Y-m-d", $this->dateOfBirth);
635     }
636     if($this->gender=="0") $this->gender ="";
637     if($this->preferredLanguage=="0") $this->preferredLanguage ="";
638     
639  
640     /* First use parents methods to do some basic fillup in $this->attrs */
641     plugin::save ();
643     /* Remove additional objectClasses */
644     $tmp= array();
645     foreach ($this->attrs['objectClass'] as $key => $set){
646       $found= false;
647       foreach (array("ivbbentry", "gosaUserTemplate") as $val){
648         if (preg_match ("/^$set$/i", $val)){
649           $found= true;
650           break;
651         }
652       }
653       if (!$found){
654         $tmp[]= $set;
655       }
656     }
658     /* Replace the objectClass array. This is done because of the
659        separation into government and normal mode. */
660     $this->attrs['objectClass']= $tmp;
662     /* Add objectClasss for template mode? */
663     if ($this->is_template){
664       $this->attrs['objectClass'][]= "gosaUserTemplate";
665     }
667     /* Hard coded government mode? */
668     if ($this->config->current['GOVERNMENTMODE'] != 'false'){
669       $this->attrs['objectClass'][]= "ivbbentry";
671       /* Copy standard attributes */
672       foreach ($this->govattrs as $val){
673         if ($this->$val != ""){
674           $this->attrs["$val"]= $this->$val;
675         } elseif (!$this->new) {
676           $this->attrs["$val"]= array();
677         }
678       }
680       /* Remove attribute if set to "nein" */
681       if ($this->publicVisible == "nein"){
682         $this->attrs['publicVisible']= array();
683         if($this->new){
684           unset($this->attrs['publicVisible']);
685         }else{
686           $this->attrs['publicVisible']=array();
687         }
689       }
691     }
693     /* Special handling for attribute userCertificate needed */
694     if ($this->userCertificate != ""){
695       $this->attrs["userCertificate;binary"]= $this->userCertificate;
696       $remove_userCertificate= false;
697     } else {
698       $remove_userCertificate= true;
699     }
701     /* Special handling for dateOfBirth value */
702     if ($this->use_dob != "1"){
703       if ($this->new) {
704         unset($this->attrs["dateOfBirth"]);
705       } else {
706         $this->attrs["dateOfBirth"]= array();
707       }
708     }
709     if (!$this->gender){
710       if ($this->new) {
711         unset($this->attrs["gender"]);
712       } else {
713         $this->attrs["gender"]= array();
714       }
715     }
716     if (!$this->preferredLanguage){
717       if ($this->new) {
718         unset($this->attrs["preferredLanguage"]);
719       } else {
720         $this->attrs["preferredLanguage"]= array();
721       }
722     }
724     /* Special handling for attribute jpegPhote needed, scale image via
725        image magick to 147x200 pixels and inject resulting data. */
726     if ($this->jpegPhoto != "*removed*"){
728       /* Fallback if there's no image magick inside PHP */
729       if (!function_exists("imagick_blob2image")){
730         /* Get temporary file name for conversation */
731         $fname = tempnam ("/tmp", "GOsa");
733         /* Open file and write out photoData */
734         $fp = fopen ($fname, "w");
735         fwrite ($fp, $this->photoData);
736         fclose ($fp);
738         /* Build conversation query. Filename is generated automatically, so
739            we do not need any special security checks. Exec command and save
740            output. For PHP safe mode, you'll need a configuration which respects
741            image magick as executable... */
742         $query= "convert -size 147x200 $fname -resize 147x200 +profile \"*\" -";
743         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__,
744             $query, "Execute");
746         /* Read data written by convert */
747         $output= "";
748         $sh= popen($query, 'r');
749         while (!feof($sh)){
750           $output.= fread($sh, 4096);
751         }
752         pclose($sh);
754         unlink($fname);
756         /* Save attribute */
757         $this->attrs["jpegPhoto"] = $output;
759       } else {
761         /* Load the new uploaded Photo */
762         if(!$handle  =  imagick_blob2image($this->photoData))  {
763           gosa_log("Can't Load image");
764         }
766         /* Resizing image to 147x200 and blur */
767         if(!imagick_resize($handle,147,200,IMAGICK_FILTER_GAUSSIAN,0)){
768           gosa_log("imagick_resize failed");
769         }
771         /* Converting image to JPEG */
772         if(!imagick_convert($handle,"JPEG")) {
773           gosa_log("Can't Convert to JPEG");
774         }
776         /* Creating binary Code for the Image */
777         if(!$dump = imagick_image2blob($handle)){
778           gosa_log("Can't create blob for image");
779         }
781         /* Sending Image */
782         $output=  $dump;
784         /* Save attribute */
785         $this->attrs["jpegPhoto"] = $output;
786       }
788     } elseif(!$this->new) {
789       $this->attrs["jpegPhoto"] = array();
790     }
792     /* Build new dn */
793     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
794       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
795     } else {
796       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
797     }
799     /* This only gets called when user is renaming himself */
800     $ldap= $this->config->get_ldap_link();
801     if ($this->dn != $new_dn){
803       /* Write entry on new 'dn' */
804       $this->move($this->dn, $new_dn);
806       /* Happen to use the new one */
807       change_ui_dn($this->dn, $new_dn);
808       $this->dn= $new_dn;
809     }
812     /* Save data. Using 'modify' implies that the entry is already present, use 'add' for
813        new entries. So do a check first... */
814     $ldap->cat ($this->dn, array('dn'));
815     if ($ldap->fetch()){
816       $mode= "modify";
817     } else {
818       $mode= "add";
819       $ldap->cd($this->config->current['BASE']);
820       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
821     }
823     /* Set password to some junk stuff in case of templates */
824     if ($this->is_template){
825       $this->attrs['userPassword']= '{crypt}N0T$3T4N0W';
826     }
828     @DEBUG (DEBUG_LDAP, __LINE__, __FUNCTION__, __FILE__,
829         $this->attributes, "Save via $mode");
831     /* Finally write data with selected 'mode' */
832     $this->cleanup();
833     $ldap->cd ($this->dn);
834     $ldap->$mode ($this->attrs);
835     if (show_ldap_error($ldap->get_error(), _("Saving generic user account failed"))){
836       return (1);
837     }
839     /* Remove cert? 
840        For some reason, the 'ldap' class doesn't want to remove binary entries, so I need
841        to work around myself. */
842     if ($remove_userCertificate == true && !$this->new && $this->had_userCertificate){
844       /* Reset array, assemble new, this should be reworked */
845       $this->attrs= array();
846       $this->attrs['userCertificate;binary']= array();
848       /* Prepare connection */
849       if (!($ds = ldap_connect($this->config->current['SERVER']))) {
850         die ("Could not connect to LDAP server");
851       }
852       ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
853       if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
854         ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
855         ldap_set_rebind_proc($ds, array(&$this, "rebind"));
856       }
857       if(isset($config->current['TLS']) && $config->current['TLS'] == "true"){
858         ldap_start_tls($ds);
859       }
860       if (!($res = @ldap_bind($ds, $this->config->current['ADMIN'],
861               $this->config->current['PASSWORD']))) {
862         die ("Could not bind to LDAP");
863       }
865       /* Modify using attrs */
866       ldap_mod_del($ds,$this->dn,$this->attrs);
867       ldap_close($ds);
868     }
870     /* Kerberos server defined? */
871     if (isset($this->config->data['SERVERS']['KERBEROS'])){
872       $cfg= $this->config->data['SERVERS']['KERBEROS'];
873     }
874     if (isset($cfg['SERVER']) && function_exists('kadm5_init_with_password')){
876       /* Connect to the admin interface */
877       $handle = kadm5_init_with_password($cfg['SERVER'], $cfg['REALM'],
878           $cfg['ADMIN'], $cfg['PASSWORD']);
880       /* Errors? */             
881       if ($handle === FALSE){
882         print_red (_("Kerberos database communication failed"));
883         return (2);
884       }
886       /* Build user principal, get list of existsing principals */
887       $principal= $this->uid."@".$cfg['REALM'];
888       $principals = kadm5_get_principals($handle);
890       /* User exists in database? */
891       if (in_array($principal, $principals)){
893         /* Ok. User exists. Remove him/her when pw_storage has
894            changed to be NOT kerberos. */
895         if ($this->pw_storage != "kerberos"){
896           $ret= kadm5_delete_principal ( $handle, $principal);
898           if ($ret === FALSE){
899             print_red (_("Can't remove user from kerberos database."));
900           }
901         }
903       } else {
905         /* User doesn't exists, create it when pw_storage is kerberos. */
906         if ($this->pw_storage == "kerberos"){
907           $ret= kadm5_create_principal ( $handle, $principal);
909           if ($ret === FALSE){
910             print_red (_("Can't add user to kerberos database."));
911           }
912         }
914       }
916       /* Free kerberos admin handle */
917       kadm5_destroy($handle);
918     }
920     /* Optionally execute a command after we're done */
921     if ($mode == "add"){
922       $this->handle_post_events("add");
923     } elseif ($this->is_modified){
924       $this->handle_post_events("modify");
925     }
927     /* Fix tagging if needed */
928     $this->handle_object_tagging();
930     return (0);
931   }
934   /* Check formular input */
935   function check()
936   {
937     /* Call common method to give check the hook */
938     $message= plugin::check();
940     /* Assemble cn */
941     $this->cn= $this->givenName." ".$this->sn;
943     /* Permissions for that base? */
944     if (isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid"){
945       $new_dn= 'uid='.$this->uid.','.get_people_ou().$this->base;
946     } else {
947       $new_dn= 'cn='.$this->cn.','.get_people_ou().$this->base;
948     }
950     $ui= get_userinfo();
951     $acl= get_permissions ($new_dn, $ui->subtreeACL);
952     $acl= get_module_permission($acl, "user", $new_dn);
953     if ($this->dn == "new" && chkacl($acl, "create") != ""){
954       $message[]= _("You have no permissions to create a user on this 'Base'.");
955     } elseif ($this->dn != $new_dn && $this->dn != "new"){
956       $acl= get_permissions ($this->dn, $ui->subtreeACL);
957       $acl= get_module_permission($acl, "user", $this->dn);
958       if (chkacl($acl, "create") != ""){
959         $message[]= _("You have no permissions to move a user from the original 'Base'.");
960       }
961     }
963     /* must: sn, givenName, uid */
964     if ($this->sn == "" && chkacl ($this->acl, "sn") == ""){
965       $message[]= _("The required field 'Name' is not set.");
966     }
968     /* UID already used? */
969     $ldap= $this->config->get_ldap_link();
970     $ldap->cd($this->config->current['BASE']);
971     $ldap->search("(uid=$this->uid)", array("uid"));
972     $ldap->fetch();
973     if ($ldap->count() != 0 && $this->dn == 'new'){
974       $message[]= _("There's already a person with this 'Login' in the database.");
975     }
977     /* In template mode, the uid and givenName are autogenerated... */
978     if (!$this->is_template){
979       if ($this->givenName == "" && chkacl ($this->acl, "givenName") == ""){
980         $message[]= _("The required field 'Given name' is not set.");
981       }
982       if ($this->uid == "" && chkacl ($this->acl, "uid") == ""){
983         $message[]= _("The required field 'Login' is not set.");
984       }
985       if (!(isset($this->config->current['DNMODE']) && $this->config->current['DNMODE'] == "uid")){
986         $ldap->cd($this->config->current['BASE']);
987         $ldap->search("(cn=".$this->cn.")", array("uid"));
988         $ldap->fetch();
989         if ($ldap->count() != 0 && $this->dn != $new_dn && $this->dn == 'new'){
990           $message[]= _("There's already a person with this 'Name'/'Given name' combination in the database.");
991         }
992       }
993     }
995     /* Check for valid input */
996     if ($this->is_modified && !is_uid($this->uid)){
997       $message[]= _("The field 'Login' contains invalid characters. Lowercase, numbers and dashes are allowed.");
998     }
999     if (!is_url($this->labeledURI)){
1000       $message[]= _("The field 'Homepage' contains an invalid URL definition.");
1001     }
1002     if (preg_match ("/[\\\\]/", $this->sn)){
1003       $message[]= _("The field 'Name' contains invalid characters.");
1004     }
1005     if (preg_match ("/[\\\\]/", $this->givenName)){
1006       $message[]= _("The field 'Given name' contains invalid characters.");
1007     }
1009     /* Check phone numbers */
1010     if (!is_phone_nr($this->telephoneNumber)){
1011       $message[]= _("The field 'Phone' contains an invalid phone number.");
1012     }
1013     if (!is_phone_nr($this->facsimileTelephoneNumber)){
1014       $message[]= _("The field 'Fax' contains an invalid phone number.");
1015     }
1016     if (!is_phone_nr($this->mobile)){
1017       $message[]= _("The field 'Mobile' contains an invalid phone number.");
1018     }
1019     if (!is_phone_nr($this->pager)){
1020       $message[]= _("The field 'Pager' contains an invalid phone number.");
1021     }
1023     /* Check for reserved characers */
1024     if (preg_match ('/[,+"?\'()=<>;]/', $this->givenName)){
1025       $message[]= _("The field 'Given name' contains invalid characters.");
1026     }
1027     if (preg_match ('/[,+"?\'()=<>;]/', $this->sn)){
1028       $message[]= _("The field 'Name' contains invalid characters.");
1029     }
1031   return $message;
1032   }
1035   /* Indicate whether a password change is needed or not */
1036   function password_change_needed()
1037   {
1038     return ($this->pw_storage != $this->last_pw_storage);
1039   }
1042   /* Load a jpegPhoto from LDAP, this is going to be simplified later on */
1043   function load_picture()
1044   {
1045     /* make connection and read jpegPhoto */
1046     $ds= ldap_connect($this->config->current['SERVER']);
1047     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1048     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1049       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1050       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1051     }
1053     if(isset($this->config->current['TLS']) &&
1054         $this->config->current['TLS'] == "true"){
1056       ldap_start_tls($ds);
1057     }
1059     $r= ldap_bind($ds);
1060     $sr= @ldap_read($ds, $this->dn, "jpegPhoto=*", array("jpegPhoto"));
1062     /* in case we don't get an entry, load a default picture */
1063     $this->set_picture ("./images/default.jpg");
1064     $this->jpegPhoto= "*removed*";
1066     /* fill data from LDAP */
1067     if ($sr) {
1068       $ei=ldap_first_entry($ds, $sr);
1069       if ($ei) {
1070         if ($info = ldap_get_values_len($ds, $ei, "jpegPhoto")){
1071           $this->photoData= $info[0];
1072           $_SESSION['binary']= $this->photoData;
1073           $_SESSION['binarytype']= "image/jpeg";
1074           $this->jpegPhoto= "";
1075         }
1076       }
1077     }
1079     /* close conncetion */
1080     ldap_unbind($ds);
1081   }
1084   /* Load a certificate from LDAP, this is going to be simplified later on */
1085   function load_cert()
1086   {
1087     $ds= ldap_connect($this->config->current['SERVER']);
1088     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1089     if (function_exists("ldap_set_rebind_proc") && isset($this->config->current['RECURSIVE']) && $this->config->current['RECURSIVE'] == "true") {
1090       ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
1091       ldap_set_rebind_proc($ds, array(&$this, "rebind"));
1092     }
1093     if(isset($this->config->current['TLS']) &&
1094         $this->config->current['TLS'] == "true"){
1096       ldap_start_tls($ds);
1097     }
1099     $r= ldap_bind($ds);
1100     $sr= @ldap_read($ds, $this->dn, "userCertificate=*", array("userCertificate"));
1102     if ($sr) {
1103       $ei= @ldap_first_entry($ds, $sr);
1104       
1105       if ($ei) {
1106         if (!$info = @ldap_get_values_len($ds, $ei, "userCertificate;binary")){
1107           $this->userCertificate= "";
1108         } else {
1109           $this->userCertificate= $info[0];
1110         }
1111       }
1112     } else {
1113       $this->userCertificate= "";
1114     }
1116     ldap_unbind($ds);
1117   }
1120   /* Load picture from file to object */
1121   function set_picture($filename ="")
1122   {
1123     if (!is_file($filename) || $filename == ""){
1124       $filename= "./images/default.jpg";
1125       $this->jpegPhoto= "*removed*";
1126     }
1128     $fd = fopen ($filename, "rb");
1129     $this->photoData= fread ($fd, filesize ($filename));
1130     $_SESSION['binary']= $this->photoData;
1131     $_SESSION['binarytype']= "image/jpeg";
1132     $this->jpegPhoto= "";
1134     fclose ($fd);
1135   }
1138   /* Load certificate from file to object */
1139   function set_cert($cert, $filename)
1140   {
1141     $fd = fopen ($filename, "rb");
1142     if (filesize($filename)>0) {
1143       $this->$cert= fread ($fd, filesize ($filename));
1144       fclose ($fd);
1145       $this->is_modified= TRUE;
1146     } else {
1147       print_red(_("Could not open specified certificate!"));
1148     }
1149   }
1151   /* Adapt from given 'dn' */
1152   function adapt_from_template($dn)
1153   {
1154     plugin::adapt_from_template($dn);
1156     /* Get base */
1157     $this->base= preg_replace('/^[^,]+,'.get_people_ou().'/i', '', $dn);
1159     if ($this->config->current['GOVERNMENTMODE']){
1161       /* Walk through govattrs */
1162       foreach ($this->govattrs as $val){
1164         if (isset($this->attrs["$val"][0])){
1166           /* If attribute is set, replace dynamic parts: 
1167              %sn, %givenName and %uid. Fill these in our local variables. */
1168           $value= $this->attrs["$val"][0];
1170           foreach (array("sn", "givenName", "uid") as $repl){
1171             if (preg_match("/%$repl/i", $value)){
1172               $value= preg_replace ("/%$repl/i",
1173                   $this->parent->$repl, $value);
1174             }
1175           }
1176           $this->$val= $value;
1177         }
1178       }
1179     }
1181     /* Get back uid/sn/givenName */
1182     if ($this->parent != NULL){
1183       $this->uid= $this->parent->uid;
1184       $this->sn= $this->parent->sn;
1185       $this->givenName= $this->parent->givenName;
1186     }
1187   }
1189  
1190   /* This avoids that users move themselves out of their rights. 
1191    */
1192   function allowedBasesToMoveTo()
1193   {
1194     $allowed = array();
1195     $ret_all = false;
1196     if($this->uid == $_SESSION['ui']->username){
1197       $ldap= $this->config->get_ldap_link(); 
1198       $ldap->cd($this->config->current['BASE']); 
1199       $ldap->search("(&(objectClass=posixGroup)(memberUid=".$_SESSION['ui']->username."))",array("gosaSubtreeACL"));
1200        
1201       while($attrs = $ldap->fetch()){
1202     
1203         if(isset($attrs['gosaSubtreeACL'])){
1204         
1205           foreach($attrs['gosaSubtreeACL'] as $attr){
1206             if((preg_match("/:user#/",$attr))||(preg_match("/:all/",$attr))){
1207               $s =  preg_replace("/^.*ou=groups,/","",$attrs['dn']);
1209               foreach($this->config->idepartments as $key => $dep) {
1210                 if(preg_match("/".$s."/i",$key)){
1211                   $allowed[$key] = $dep;
1212                 }
1213               }
1214             }
1215           }
1216         }
1217       }
1218       if(count($allowed) == 0){
1219         foreach($this->config->idepartments as $key => $dep) {
1220           if($this->base==$key){
1221             $allowed[$key] = $dep;
1222           }
1223         }
1224       }  
1225   
1226       return($allowed);
1227       
1228     }else{
1229       return($this->config->idepartments);
1230     }
1231   } 
1234   function getCopyDialog()
1235   {
1236     $str = "";
1238     $_SESSION['binary'] = $this->photoData; 
1239     $_SESSION['binarytype']= "image/jpeg";
1241     /* Get random number for pictures */
1242     srand((double)microtime()*1000000); 
1243     $rand = rand(0, 10000);
1245     $smarty = get_smarty();
1247     $smarty->assign("passwordTodo","clear");
1249     if(isset($_POST['passwordTodo'])){
1250       $smarty->assign("passwordTodo",$_POST['passwordTodo']);
1251     }
1253     $smarty->assign("sn",       $this->sn);
1254     $smarty->assign("givenName",$this->givenName);
1255     $smarty->assign("uid",      $this->uid);
1256     $smarty->assign("rand",     $rand);
1257     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE,dirname(__FILE__)));
1260     $ret = array();
1261     $ret['string'] = $str;
1262     $ret['status'] = "";  
1263     return($ret);
1264   }
1266   function saveCopyDialog()
1267   {
1269     if((isset($_FILES['picture_file']['tmp_name'])) && ($_FILES['picture_file']['size'] > 0)){
1270       $this->set_picture($_FILES['picture_file']['tmp_name']);
1271     }
1273     /* Remove picture? */
1274     if (isset($_POST['picture_remove'])){
1275       $this->jpegPhoto= "*removed*";
1276       $this->set_picture ("./images/default.jpg");
1277       $this->is_modified= TRUE;
1278     }
1280     $attrs = array("uid","givenName","sn");
1281     foreach($attrs as $attr){
1282       if(isset($_POST[$attr])){
1283         $this->$attr = $_POST[$attr];
1284       }
1285     } 
1286   }
1289 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1290 ?>