DataObjects/Person.php
[Pman.Core] / DataObjects / Person.php
1 <?php
2 /**
3  * Table Definition for Person
4  */
5 require_once 'DB/DataObject.php';
6
7 class Pman_Core_DataObjects_Person extends DB_DataObject 
8 {
9     ###START_AUTOCODE
10     /* the code below is auto generated do not remove the above tag */
11
12     public $__table = 'Person';                          // table name
13     public $id;                              // int(11)  not_null primary_key auto_increment
14     public $email;                           // string(128)  not_null
15     
16     public $company_id;                      // int(11)  
17     public $office_id;                       // int(11)  
18     
19     public $name;                            // string(128)  not_null
20     public $firstname;                            // string(128)  not_null
21     public $lastname;                            // string(128)  not_null
22     public $phone;                           // string(32)  not_null
23     public $fax;                             // string(32)  not_null
24     
25     public $role;                            // string(32)  not_null
26     public $remarks;                         // blob(65535)  not_null blob
27     public $passwd;                          // string(64)  not_null
28     public $owner_id;                        // int(11)  not_null
29     public $lang;                            // string(8)  
30     public $no_reset_sent;                   // int(11)  
31     public $action_type;                     // string(32)  
32     public $project_id;                      // int(11)
33
34     
35     public $active;                          // int(11)  not_null
36     public $deleted_by;                      // int(11)  not_null
37     public $deleted_dt;                      // datetime(19)  binary
38
39     
40     /* the code above is auto generated do not remove the tag below */
41     ###END_AUTOCODE
42     
43     function owner()
44     {
45         $p = DB_DataObject::Factory('Person');
46         $p->get($this->owner_id);
47         return $p;
48     }
49     
50     /**
51      *
52      *
53      *
54      *
55      *  FIXME !!!! -- USE Pman_Core_Mailer !!!!!
56      *
57      *
58      *
59      *  
60      */
61     function buildMail($templateFile, $args)
62     {
63           
64         $args = (array) $args;
65         $content  = clone($this);
66         
67         foreach((array)$args as $k=>$v) {
68             $content->$k = $v;
69         }
70         
71         $ff = HTML_FlexyFramework::get();
72         
73         
74         //?? is this really the place for this???
75         if (
76                 !$ff->cli && 
77                 empty($args['no_auth']) &&
78                 !in_array($templateFile, array(
79                     // templates that can be sent without authentication.
80                      'password_reset' ,
81                      'password_welcome'
82                  ))
83             ) {
84             
85             $content->authUser = $this->getAuthUser();
86             if (!$content->authUser) {
87                 return PEAR::raiseError("Not authenticated");
88             }
89         }
90         
91         // should handle x-forwarded...
92         
93         $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
94             $_SERVER["HTTP_HOST"] :
95             (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
96             
97         /* use the regex compiler, as it doesnt parse <tags */
98         
99         $tops = array(
100             'compiler'    => 'Flexy',
101             'nonHTML' => true,
102             'filters' => array('SimpleTags','Mail'),
103             //     'debug'=>1,
104         );
105         
106         
107         
108         if (!empty($args['templateDir'])) {
109             $tops['templateDir'] = $args['templateDir'];
110         }
111         
112         
113         
114         require_once 'HTML/Template/Flexy.php';
115         $template = new HTML_Template_Flexy( $tops );
116         $template->compile("mail/$templateFile.txt");
117         
118         /* use variables from this object to ouput data. */
119         $mailtext = $template->bufferedOutputObject($content);
120         
121         $htmlbody = false;
122         // if a html file with the same name exists, use that as the body
123         // I've no idea where this code went, it was here before..
124         if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
125             $tops['nonHTML'] = false;
126             $template = new HTML_Template_Flexy( $tops );
127             $template->compile("mail/$templateFile.html");
128             $htmlbody = $template->bufferedOutputObject($content);
129             
130         }
131         
132         
133         
134         //echo "<PRE>";print_R($mailtext);
135         //print_R($mailtext);exit;
136         /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
137         require_once 'Mail/mimeDecode.php';
138         require_once 'Mail.php';
139         
140         $decoder = new Mail_mimeDecode($mailtext);
141         $parts = $decoder->getSendArray();
142         
143         if (PEAR::isError($parts)) {
144             return $parts;
145             //echo "PROBLEM: {$parts->message}";
146             //exit;
147         } 
148         list($recipents,$headers,$body) = $parts;
149         $recipents = array($this->email);
150         if (!empty($content->bcc) && is_array($content->bcc)) {
151             $recipents =array_merge($recipents, $content->bcc);
152         }
153         $headers['Date'] = date('r');
154         
155         if ($htmlbody !== false) {
156             require_once 'Mail/mime.php';
157             $mime = new Mail_mime(array('eol' => "\n"));
158             $mime->setTXTBody($body);
159             $mime->setHTMLBody($htmlbody);
160             // I think there might be code in mediaoutreach toEmail somewhere
161             // h embeds images here..
162             $body = $mime->get();
163             $headers = $mime->headers($headers);
164             
165         }
166         
167          
168         
169         return array(
170             'recipients' => $recipents,
171             'headers'    => $headers,
172             'body'      => $body
173         );
174         
175         
176     }
177     
178     
179     /**
180      * send a template
181      * - user must be authenticate or args[no_auth] = true
182      *   or template = password_[reset|welcome]
183      * 
184      */
185     function sendTemplate($templateFile, $args)
186     {
187         
188         $ar = $this->buildMail($templateFile, $args);
189       
190         
191         //print_r($recipents);exit;
192         $mailOptions = PEAR::getStaticProperty('Mail','options');
193         $mail = Mail::factory("SMTP",$mailOptions);
194         
195         if (PEAR::isError($mail)) {
196             return $mail;
197         } 
198         $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
199         $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
200         error_reporting($oe);
201        
202         return $ret;
203     
204     }
205     
206   
207     
208     
209     function getEmailFrom()
210     {
211         return '"' . addslashes($this->name) . '" <' . $this->email . '>';
212     }
213     function toEventString() 
214     {
215         return empty($this->name) ? $this->email : $this->name;
216     } 
217     function verifyAuth()
218     { 
219         $ff= HTML_FlexyFramework::get();
220         if (!empty($ff->Pman['auth_comptype']) && $ff->Pman['auth_comptype'] != $this->company()->comptype) {
221             $ff->page->jerr("Login not permited to outside companies");
222         }
223         return true;
224         
225     }    
226    
227    
228     //   ---------------- authentication / passwords and keys stuff  ----------------
229     function isAuth()
230     {
231         $db = $this->getDatabaseConnection();
232         // we combine db + project names,
233         // otherwise if projects use different 'auth' objects
234         // then we get unserialize issues.
235         $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
236         
237         
238         @session_start();
239         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
240             // in session...
241             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
242             
243             $u = DB_DataObject::factory('Person');
244             if ($u->get($a->id)) { //&& strlen($u->passwd)) {
245                 $u->verifyAuth();
246                 
247                 return true;
248             }
249             
250             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
251             
252         }
253         // local auth - 
254         $u = DB_DataObject::factory('Person');
255         $ff = HTML_FlexyFramework::get();
256         if (!empty($ff->Pman['local_autoauth']) && 
257             (!empty($_SERVER['SERVER_ADDR'])) &&
258             ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
259             ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') &&
260             $u->get('email', $ff->Pman['local_autoauth'])
261         ) {
262             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
263             return true;
264         }
265            
266         // http basic auth..
267         $u = DB_DataObject::factory('Person');
268
269         if (!empty($_SERVER['PHP_AUTH_USER']) 
270             &&
271             !empty($_SERVER['PHP_AUTH_PW'])
272             &&
273             $u->get('email', $_SERVER['PHP_AUTH_USER'])
274             &&
275             $u->checkPassword($_SERVER['PHP_AUTH_PW'])
276            ) {
277             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
278             return true; 
279         }
280         
281         if (!empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
282             return false;
283         }
284         
285         // not in session or not matched...
286         $u = DB_DataObject::factory('Person');
287         $u->whereAdd(' LENGTH(passwd) > 0');
288         $n = $u->count();
289         $_SESSION[__CLASS__][$sesPrefix .'-empty']  = $n;
290         $error =  PEAR::getStaticProperty('DB_DataObject','lastError');
291         if ($error) {
292             die($error->toString()); // not really a good thing to do...
293         }
294         if (!$n){ // authenticated as there are no users in the system...
295             return true;
296         }
297         
298         return false;
299         
300     }
301     function getAuthUser()
302     {
303         if (!$this->isAuth()) {
304             return false;
305         }
306         $db = $this->getDatabaseConnection();
307         $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
308         
309         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
310             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
311             
312             $u = DB_DataObject::factory('Person');
313             if ($u->get($a->id)) { /// && strlen($u->passwd)) {
314                 return clone($u);
315             }
316              
317         }
318         
319         if (empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
320             $u = DB_DataObject::factory('Person');
321             $u->whereAdd(' LENGTH(passwd) > 0');
322              $_SESSION[__CLASS__][$sesPrefix .'-empty']  = $u->count();
323         }
324                 
325              
326         if (empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
327             
328             // fake person - open system..
329             //$ce = DB_DataObject::factory('core_enum');
330             //$ce->initEnums();
331             
332             
333             $u = DB_DataObject::factory('Person');
334             $u->id = -1;
335             return $u;
336             
337         }
338         return false;
339     }     
340     function login()
341     {
342         $this->isAuth(); // force session start..
343         $this->verifyAuth();
344         $db = $this->getDatabaseConnection();
345         // refresh admin group if we are logged in as one..
346         //DB_DataObject::debugLevel(1);
347         $g = DB_DataObject::factory('Groups');
348         $g->type = 0;
349         $g->get('name', 'Administrators');
350         $gm = DB_DataObject::Factory('group_members');
351         if (in_array($g->id,$gm->listGroupMembership($this))) {
352             // refresh admin groups.
353             $gr = DB_DataObject::Factory('group_rights');
354             $gr->applyDefs($g, 0);
355         }
356              
357         $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
358         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
359         
360     }
361     function logout()
362     {
363         $this->isAuth(); // force session start..
364          $db = $this->getDatabaseConnection();
365         $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
366         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
367         
368     }    
369     function genPassKey ($t) 
370     {
371         return md5($this->email . $t. $this->passwd);
372     }
373     function simpleAuthKey($m = 0)
374     {
375         $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
376         
377         return md5(implode(',' ,  array($month, $this->email , $this->passwd, $this->id)));
378     } 
379     function checkPassword($val)
380     {
381         
382         if (substr($this->passwd,0,1) == '$') {
383             return crypt($val,$this->passwd) == $this->passwd ;
384         }
385         // old style md5 passwords...- cant be used with courier....
386         return md5($val) == $this->passwd;
387     }
388     function setPassword($value) 
389     {
390         $salt='';
391         while(strlen($salt)<9) {
392             $salt.=chr(rand(64,126));
393             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
394         }
395         $this->passwd = crypt($value, '$1$'. $salt. '$');
396        
397        
398     }      
399     
400     function generatePassword() // genearte a password (add set 'rawPasswd' to it's value)
401     {
402         require_once 'Text/Password.php';
403         $this->rawPasswd = strtr(ucfirst(Text_Password::create(5)).ucfirst(Text_Password::create(5)), array(
404         "a"=>"4", "e"=>"3",  "i"=>"1",  "o"=>"0", "s"=>"5",  "t"=>"7"));
405         $this->setPassword($this->rawPasswd);
406         return $this->rawPasswd;
407     }
408     
409     function company()
410     {
411         $x = DB_DataObject::factory('Companies');
412         $x->get($this->company_id);
413         return $x;
414     }
415     function loadCompany()
416     {
417         $this->company = $this->company();
418     }
419     
420     function active()
421     { 
422         return $this->active;
423     }
424     function authUserName($n) // set username prior to acheck user exists query.
425     {
426         
427         $this->whereAdd('LENGTH(passwd) > 1'); 
428         $this->email = $n;
429     }
430     function lang($val)
431     {
432         if ($val == $this->lang) {
433             return;
434         }
435         $uu = clone($this);
436         $this->lang = $val;
437         $this->update($uu);
438
439     }
440             
441     
442     function authUserArray()
443     {
444         
445         $aur = $this->toArray();
446         
447         if ($this->id < 1) {
448             return $aur;
449         }
450         
451         
452         //DB_DataObject::debugLevel(1);
453         $c = DB_Dataobject::factory('Companies');
454         $im = DB_Dataobject::factory('Images');
455         $c->joinAdd($im, 'LEFT');
456         $c->selectAdd();
457         $c->selectAs($c, 'company_id_%s');
458         $c->selectAs($im, 'company_id_logo_id_%s');
459         $c->id = $this->company_id;
460         $c->limit(1);
461         $c->find(true);
462         
463         $aur = array_merge( $c->toArray(),$aur);
464         
465         if (empty($c->company_id_logo_id_id))  {
466                  
467             $im = DB_Dataobject::factory('Images');
468             $im->ontable = 'Companies';
469             $im->onid = $c->id;
470             $im->imgtype = 'LOGO';
471             $im->limit(1);
472             $im->selectAdd();
473             $im->selectAs($im,  'company_id_logo_id_%s');
474             if ($im->find(true)) {
475                     
476                 foreach($im->toArray() as $k=>$v) {
477                     $aur[$k] = $v;
478                 }
479             }
480         }
481       
482         // perms + groups.
483         $aur['perms']  = $this->getPerms();
484         $g = DB_DataObject::Factory('group_members');
485         $aur['groups']  = $g->listGroupMembership($this, 'name');
486         
487         $aur['passwd'] = '';
488         $aur['dailykey'] = '';
489         
490         
491         
492         return $aur;
493     }
494     
495     //   ----------PERMS------  ----------------
496     function getPerms() 
497     {
498          //DB_DataObject::debugLevel(1);
499         // find out all the groups they are a member of.. + Default..
500         
501         // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
502         
503         $g = DB_DataObject::Factory('group_rights');
504         if (!$g->count()) {
505             $g->genDefault();
506         }
507         
508         if ($this->id < 0) {
509             return $g->adminRights(); // system is not set up - so they get full rights.
510         }
511         //DB_DataObject::debugLevel(1);
512         $g = DB_DataObject::Factory('group_members');
513         $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
514         if (!$g->count()) {
515             // add the current user to the admin group..
516             $g = DB_DataObject::Factory('Groups');
517             if ($g->get('name', 'Administrators')) {
518                 $gm = DB_DataObject::Factory('group_members');
519                 $gm->group_id = $g->id;
520                 $gm->user_id = $this->id;
521                 $gm->insert();
522             }
523             
524         }
525         
526         // ------ STANDARD PERMISSION HANDLING.
527         $isOwner = $this->company()->comptype == 'OWNER';
528         $g = DB_DataObject::Factory('group_members');
529         $grps = $g->listGroupMembership($this);
530        //var_dump($grps);
531         $isAdmin = $g->inAdmin;
532         //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
533         // the load all the perms for those groups, and add them all together..
534         // then load all those 
535         $g = DB_DataObject::Factory('group_rights');
536         $ret =  $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
537         //echo '<PRE>';print_r($ret);
538         return $ret;
539          
540         
541     }
542     /**
543      *Basic group fetching - probably needs to filter by type eventually.
544      *
545      *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
546      */
547     
548     function groups($what=false)
549     {
550         $g = DB_DataObject::Factory('group_members');
551         $grps = $g->listGroupMembership($this);
552         $g = DB_DataObject::Factory('Groups');
553         $g->whereAddIn('id', $grps, 'int');
554         return $g->fetchAll($what);
555         
556     }
557     
558     
559     
560     function hasPerm($name, $lvl) 
561     {
562         static $pcache = array();
563         
564         if (!isset($pcache[$this->id])) {
565             $pcache[$this->id] = $this->getPerms();
566         }
567        // echo "<PRE>";print_r($pcache[$au->id]);
568        // var_dump($pcache[$au->id]);
569         if (empty($pcache[$this->id][$name])) {
570             return false;
571         }
572         
573         return strpos($pcache[$this->id][$name], $lvl) > -1;
574         
575     }    
576     
577     //  ------------ROO HOOKS------------------------------------
578     function applyFilters($q, $au, $roo)
579     {
580         //DB_DataObject::DebugLevel(1);
581         if (!empty($q['query']['person_not_internal'])) {
582             $this->whereAdd(" join_company_id_id.isOwner = 0 ");
583         }
584         
585         
586         if (!empty($q['query']['person_internal_only_all'])) {
587             
588             
589             // must be internal and not current user (need for distribution list)
590             // user has a projectdirectory entry and role is not blank.
591             //DB_DataObject::DebugLevel(1);
592             $pd = DB_DataObject::factory('ProjectDirectory');
593             $pd->whereAdd("role != ''");
594             $pd->selectAdd();
595             $pd->selectAdd('distinct(person_id) as person_id');
596             $roled = $pd->fetchAll('person_id');
597             $rs = $roled  ? "  OR
598                     {$this->tableName()}.id IN (".implode(',', $roled) . ") 
599                     " : '';
600             $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
601             
602         }
603         // -- for distribution
604         if (!empty($q['query']['person_internal_only'])) {
605             // must be internal and not current user (need for distribution list)
606             $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
607             
608             //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
609             //    ".id  != ".$au->id);
610             $this->whereAdd("Person.id != {$au->id}");
611         } 
612         
613         if (!empty($q['query']['comptype_or_company_id'])) {
614            // DB_DataObject::debugLevel(1);
615             $bits = explode(',', $q['query']['comptype_or_company_id']);
616             $id = (int) array_pop($bits);
617             $ct = $this->escape($bits[0]);
618             
619             $this->whereAdd(" join_company_id_id.comptype = '$ct' OR Person.company_id = $id");
620             
621         }
622         
623         
624         // staff list..
625         if (!empty($q['query']['person_inactive'])) {
626            // DB_Dataobject::debugLevel(1);
627             $this->active = 1;
628         }
629         $tn_p = $this->tableName();
630         $tn_gm = DB_DataObject::Factory('group_members')->tableName();
631         $tn_g = DB_DataObject::Factory('Groups')->tableName();
632
633         ///---------------- Group views --------
634         if (!empty($q['query']['in_group'])) {
635             // DB_DataObject::debugLevel(1);
636             $ing = (int) $q['query']['in_group'];
637             if ($q['query']['in_group'] == -1) {
638              
639                 // list all staff who are not in a group.
640                 $this->whereAdd("Person.id NOT IN (
641                     SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
642                         $tn_g ON $tn_g.id = $tn_gm.group_id
643                         WHERE $tn_g.type = ".$q['query']['type']."
644                     )");
645                 
646                 
647             } else {
648                 
649                 $this->whereAdd("$tn_p.id IN (
650                     SELECT distinct(user_id) FROM $tn_gm
651                         WHERE group_id = $ing
652                     )");
653                }
654             
655         }
656         
657         if (!empty($q['query']['not_in_directory'])) { 
658             // it's a Person list..
659             // DB_DATaobjecT::debugLevel(1);
660             
661             // specific to project directory which is single comp. login
662             //
663             $owncomp = DB_DataObject::Factory('Companies');
664             $owncomp->get('comptype', 'OWNER');
665             if ($q['company_id'] == $owncomp->id) {
666                 $this->active =1;
667             }
668             
669             
670
671             if ( $q['query']['not_in_directory'] > -1) {
672                 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
673                 // can list current - so that it does not break!!!
674                 $this->whereAdd("$tn_p.id NOT IN 
675                     ( SELECT distinct person_id FROM $tn_pd WHERE
676                         project_id = " . $q['query']['not_in_directory'] . " AND 
677                         company_id = " . $this->company_id . ')');
678             }
679         }
680            
681         if (!empty($q['query']['role'])) { 
682             // it's a Person list..
683             // DB_DATaobjecT::debugLevel(1);
684             
685             // specific to project directory which is single comp. login
686             //
687             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
688                 // can list current - so that it does not break!!!
689             $this->whereAdd("$tn_p.id IN 
690                     ( SELECT distinct person_id FROM $tn_pd WHERE
691                         role = '". $this->escape($q['query']['role']) ."'
692             )");
693         
694         }
695         
696         
697         if (!empty($q['query']['project_member_of'])) {
698                // this is also a flag to return if they are a member..
699             //DB_DataObject::debugLevel(1);
700             $do = DB_DataObject::factory('ProjectDirectory');
701             $do->project_id = $q['query']['project_member_of'];
702             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
703             $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
704             $this->selectAdd("IF($tn_pd.id IS NULL, 0,  $tn_pd.id )  as is_member");
705                 
706                 
707             if (!empty($q['query']['project_member_filter'])) {
708                 $this->having('is_member !=0');
709             
710             }
711             
712         }
713         
714         if (!empty($q['query']['search'])) {
715             $s = $this->escape($q['query']['search']);
716                     $this->whereAdd("
717                         $tn_p.name LIKE '%$s%'  OR
718                         $tn_p.email LIKE '%$s%'  OR
719                         $tn_p.role LIKE '%$s%'  OR
720                         $tn_p.phone LIKE '%$s%' OR
721                         $tn_p.remarks LIKE '%$s%' 
722                         
723                     ");
724         }
725         
726         //
727     }
728     function setFromRoo($ar, $roo)
729     {
730         $this->setFrom($ar);
731         if (!empty($ar['passwd1'])) {
732             $this->setPassword($ar['passwd1']);
733         }
734         
735         
736         if (    $this->id &&
737                 ($this->email == $roo->old->email)&&
738                 ($this->company_id == $roo->old->company_id)
739             ) {
740             return true;
741         }
742         if (empty($this->email)) {
743             return true;
744         }
745         $xx = DB_Dataobject::factory('Person');
746         $xx->setFrom(array(
747             'email' => $this->email,
748            // 'company_id' => $x->company_id
749         ));
750         
751         if ($xx->count()) {
752             return "Duplicate Email found";
753         }
754         return true;
755     }
756     /**
757      *
758      * before Delete - delete significant dependancies..
759      * this is called after checkPerm..
760      */
761     
762     function beforeDelete()
763     {
764         
765         $e = DB_DataObject::Factory('Events');
766         $e->whereAdd('person_id = ' . $this->id);
767         $e->delete(true);
768         
769         // anything else?  
770         
771     }
772     
773     
774     /***
775      * Check if the a user has access to modify this item.
776      * @param String $lvl Level (eg. Core.Projects)
777      * @param Pman_Core_DataObjects_Person $au The authenticated user.
778      * @param boolean $changes alllow changes???
779      *
780      * @return false if no access..
781      */
782     function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
783     {
784          
785        // do we have an empty system..
786         if ($au && $au->id == -1) {
787             return true;
788         }
789         
790         // determine if it's staff!!!
791          
792         if ($au->company()->comptype != 'OWNER') {
793             
794             // - can not change company!!!
795             if ($changes && 
796                 isset($changes['company_id']) && 
797                 $changes['company_id'] != $au->company_id) {
798                 return false;
799             }
800             // can only set new emails..
801             if ($changes && 
802                     !empty($this->email) && 
803                     isset($changes['email']) && 
804                     $changes['email'] != $this->email) {
805                 return false;
806             }
807             
808             // edit self... - what about other staff members...
809             
810             return $this->company_id == $au->company_id;
811         }
812          
813          
814         // yes, only owner company can mess with this...
815         $owncomp = DB_DataObject::Factory('Companies');
816         $owncomp->get('comptype', 'OWNER');
817         
818         $isStaff = ($this->company_id ==  $owncomp->id);
819         
820     
821         switch ($lvl) {
822             // extra case change passwod?
823             case 'P': //??? password
824                 // standard perms -- for editing + if the user is dowing them selves..
825                 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
826                 return $ret || $au->id == $this->id;
827             
828             default:                
829                 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
830         
831         }
832         return false;
833     }
834     function onInsert($req, $roo)  
835     {
836          
837         $p = DB_DataObject::factory('person');
838         if ($roo->authUser->id < 0 && $p->count() == 1) {
839             // this seems a bit risky...
840             
841             $g = DB_DataObject::factory('Groups');
842             $g->initGroups();
843             
844             $g->type = 0;
845             $g->get('name', 'Administrators');
846             
847             $p = DB_DataObject::factory('group_members');
848             $p->group_id = $g->id;
849             $p->user_id = $this->id;     
850             if (!$p->count()) {
851                 $p->insert();
852                 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
853             }
854             $this->login();
855         }
856         if (!empty($req['project_id_addto'])) {
857             $pd = DB_DataObject::factory('ProjectDirectory');
858             $pd->project_id = $req['project_id_addto'];
859             $pd->person_id = $this->id; 
860             $pd->ispm =0;
861             $pd->office_id = $this->office_id;
862             $pd->company_id = $this->company_id;
863             $pd->insert();
864         }
865         
866     }
867  }