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