DataObjects/core.sql
[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         $u = DB_DataObject::factory('Person');
310         $u->whereAdd(' LENGTH(passwd) > 0');
311         if (!$u->count()){
312             $u = DB_DataObject::factory('Person');
313             $u->id = -1;
314             return $u;
315             
316         }
317         return false;
318     }     
319     function login()
320     {
321         $this->isAuth(); // force session start..
322         $this->verifyAuth();
323         $db = $this->getDatabaseConnection();
324         // refresh admin group if we are logged in as one..
325         //DB_DataObject::debugLevel(1);
326         $g = DB_DataObject::factory('Groups');
327         $g->type = 0;
328         $g->get('name', 'Administrators');
329         $gm = DB_DataObject::Factory('group_members');
330         if (in_array($g->id,$gm->listGroupMembership($this))) {
331             // refresh admin groups.
332             $gr = DB_DataObject::Factory('group_rights');
333             $gr->applyDefs($g, 0);
334         }
335              
336         $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
337         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
338         
339     }
340     function logout()
341     {
342         $this->isAuth(); // force session start..
343          $db = $this->getDatabaseConnection();
344         $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
345         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
346         
347     }    
348     function genPassKey ($t) 
349     {
350         return md5($this->email . $t. $this->passwd);
351     }
352     function simpleAuthKey($m = 0)
353     {
354         $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
355         
356         return md5(implode(',' ,  array($month, $this->email , $this->passwd, $this->id)));
357     } 
358     function checkPassword($val)
359     {
360         
361         if (substr($this->passwd,0,1) == '$') {
362             return crypt($val,$this->passwd) == $this->passwd ;
363         }
364         // old style md5 passwords...- cant be used with courier....
365         return md5($val) == $this->passwd;
366     }
367     function setPassword($value) 
368     {
369         $salt='';
370         while(strlen($salt)<9) {
371             $salt.=chr(rand(64,126));
372             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
373         }
374         $this->passwd = crypt($value, '$1$'. $salt. '$');
375        
376        
377     }      
378     
379     function company()
380     {
381         $x = DB_DataObject::factory('Companies');
382         $x->get($this->company_id);
383         return $x;
384     }
385     function loadCompany()
386     {
387         $this->company = $this->company();
388     }
389     
390     function active()
391     { 
392         return $this->active;
393     }
394     function authUserName($n) // set username prior to acheck user exists query.
395     {
396         
397         $this->whereAdd('LENGTH(passwd) > 1'); 
398         $this->email = $n;
399     }
400     function lang($val)
401     {
402         if ($val == $this->lang) {
403             return;
404         }
405         $uu = clone($this);
406         $this->lang = $val;
407         $this->update($uu);
408
409     }
410             
411     
412     function authUserArray()
413     {
414         
415         $aur = $this->toArray();
416         
417         if ($this->id < 1) {
418             return $aur;
419         }
420         
421         
422         //DB_DataObject::debugLevel(1);
423         $c = DB_Dataobject::factory('Companies');
424         $im = DB_Dataobject::factory('Images');
425         $c->joinAdd($im, 'LEFT');
426         $c->selectAdd();
427         $c->selectAs($c, 'company_id_%s');
428         $c->selectAs($im, 'company_id_logo_id_%s');
429         $c->id = $this->company_id;
430         $c->limit(1);
431         $c->find(true);
432         
433         $aur = array_merge( $c->toArray(),$aur);
434         
435         if (empty($c->company_id_logo_id_id))  {
436                  
437             $im = DB_Dataobject::factory('Images');
438             $im->ontable = 'Companies';
439             $im->onid = $c->id;
440             $im->imgtype = 'LOGO';
441             $im->limit(1);
442             $im->selectAdd();
443             $im->selectAs($im,  'company_id_logo_id_%s');
444             if ($im->find(true)) {
445                     
446                 foreach($im->toArray() as $k=>$v) {
447                     $aur[$k] = $v;
448                 }
449             }
450         }
451       
452         // perms + groups.
453         $aur['perms']  = $this->getPerms();
454         $g = DB_DataObject::Factory('group_members');
455         $aur['groups']  = $g->listGroupMembership($this, 'name');
456         
457         $aur['passwd'] = '';
458         $aur['dailykey'] = '';
459         
460         
461         
462         return $aur;
463     }
464     
465     //   ----------PERMS------  ----------------
466     function getPerms() 
467     {
468          //DB_DataObject::debugLevel(1);
469         // find out all the groups they are a member of.. + Default..
470         
471         // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
472         
473         $g = DB_DataObject::Factory('group_rights');
474         if (!$g->count()) {
475             $g->genDefault();
476         }
477         
478         if ($this->id < 0) {
479             return $g->adminRights(); // system is not set up - so they get full rights.
480         }
481         //DB_DataObject::debugLevel(1);
482         $g = DB_DataObject::Factory('group_members');
483         $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
484         if (!$g->count()) {
485             // add the current user to the admin group..
486             $g = DB_DataObject::Factory('Groups');
487             if ($g->get('name', 'Administrators')) {
488                 $gm = DB_DataObject::Factory('group_members');
489                 $gm->group_id = $g->id;
490                 $gm->user_id = $this->id;
491                 $gm->insert();
492             }
493             
494         }
495         
496         // ------ STANDARD PERMISSION HANDLING.
497         $isOwner = $this->company()->comptype == 'OWNER';
498         $g = DB_DataObject::Factory('group_members');
499         $grps = $g->listGroupMembership($this);
500        //var_dump($grps);
501         $isAdmin = $g->inAdmin;
502         //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
503         // the load all the perms for those groups, and add them all together..
504         // then load all those 
505         $g = DB_DataObject::Factory('group_rights');
506         $ret =  $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
507         //echo '<PRE>';print_r($ret);
508         return $ret;
509          
510         
511     }
512     /**
513      *Basic group fetching - probably needs to filter by type eventually.
514      *
515      *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
516      */
517     
518     function groups($what=false)
519     {
520         $g = DB_DataObject::Factory('group_members');
521         $grps = $g->listGroupMembership($this);
522         $g = DB_DataObject::Factory('Groups');
523         $g->whereAddIn('id', $grps, 'int');
524         return $g->fetchAll($what);
525         
526     }
527     
528     
529     
530     function hasPerm($name, $lvl) 
531     {
532         static $pcache = array();
533         
534         if (!isset($pcache[$this->id])) {
535             $pcache[$this->id] = $this->getPerms();
536         }
537        // echo "<PRE>";print_r($pcache[$au->id]);
538        // var_dump($pcache[$au->id]);
539         if (empty($pcache[$this->id][$name])) {
540             return false;
541         }
542         
543         return strpos($pcache[$this->id][$name], $lvl) > -1;
544         
545     }    
546     
547     //  ------------ROO HOOKS------------------------------------
548     function applyFilters($q, $au, $roo)
549     {
550         //DB_DataObject::DebugLevel(1);
551         if (!empty($q['query']['person_not_internal'])) {
552             $this->whereAdd(" join_company_id_id.isOwner = 0 ");
553         }
554         
555         
556         if (!empty($q['query']['person_internal_only_all'])) {
557             
558             
559             // must be internal and not current user (need for distribution list)
560             // user has a projectdirectory entry and role is not blank.
561             //DB_DataObject::DebugLevel(1);
562             $pd = DB_DataObject::factory('ProjectDirectory');
563             $pd->whereAdd("role != ''");
564             $pd->selectAdd();
565             $pd->selectAdd('distinct(person_id) as person_id');
566             $roled = $pd->fetchAll('person_id');
567             $rs = $roled  ? "  OR
568                     {$this->tableName()}.id IN (".implode(',', $roled) . ") 
569                     " : '';
570             $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
571             
572         }
573         // -- for distribution
574         if (!empty($q['query']['person_internal_only'])) {
575             // must be internal and not current user (need for distribution list)
576             $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
577             
578             //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
579             //    ".id  != ".$au->id);
580             $this->whereAdd("Person.id != {$au->id}");
581         } 
582         
583         if (!empty($q['query']['comptype_or_company_id'])) {
584            // DB_DataObject::debugLevel(1);
585             $bits = explode(',', $q['query']['comptype_or_company_id']);
586             $id = (int) array_pop($bits);
587             $ct = $this->escape($bits[0]);
588             
589             $this->whereAdd(" join_company_id_id.comptype = '$ct' OR Person.company_id = $id");
590             
591         }
592         
593         
594         // staff list..
595         if (!empty($q['query']['person_inactive'])) {
596            // DB_Dataobject::debugLevel(1);
597             $this->active = 1;
598         }
599         $tn_p = $this->tableName();
600         $tn_gm = DB_DataObject::Factory('group_members')->tableName();
601         $tn_g = DB_DataObject::Factory('Groups')->tableName();
602
603         ///---------------- Group views --------
604         if (!empty($q['query']['in_group'])) {
605             // DB_DataObject::debugLevel(1);
606             $ing = (int) $q['query']['in_group'];
607             if ($q['query']['in_group'] == -1) {
608              
609                 // list all staff who are not in a group.
610                 $this->whereAdd("Person.id NOT IN (
611                     SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
612                         $tn_g ON $tn_g.id = $tn_gm.group_id
613                         WHERE $tn_g.type = ".$q['query']['type']."
614                     )");
615                 
616                 
617             } else {
618                 
619                 $this->whereAdd("$tn_p.id IN (
620                     SELECT distinct(user_id) FROM $tn_gm
621                         WHERE group_id = $ing
622                     )");
623                }
624             
625         }
626         
627         if (!empty($q['query']['not_in_directory'])) { 
628             // it's a Person list..
629             // DB_DATaobjecT::debugLevel(1);
630             
631             // specific to project directory which is single comp. login
632             //
633             $owncomp = DB_DataObject::Factory('Companies');
634             $owncomp->get('comptype', 'OWNER');
635             if ($q['company_id'] == $owncomp->id) {
636                 $this->active =1;
637             }
638             
639             
640
641             if ( $q['query']['not_in_directory'] > -1) {
642                 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
643                 // can list current - so that it does not break!!!
644                 $this->whereAdd("$tn_p.id NOT IN 
645                     ( SELECT distinct person_id FROM $tn_pd WHERE
646                         project_id = " . $q['query']['not_in_directory'] . " AND 
647                         company_id = " . $this->company_id . ')');
648             }
649         }
650            
651         if (!empty($q['query']['role'])) { 
652             // it's a Person list..
653             // DB_DATaobjecT::debugLevel(1);
654             
655             // specific to project directory which is single comp. login
656             //
657             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
658                 // can list current - so that it does not break!!!
659             $this->whereAdd("$tn_p.id IN 
660                     ( SELECT distinct person_id FROM $tn_pd WHERE
661                         role = '". $this->escape($q['query']['role']) ."'
662             )");
663         
664         }
665         
666         
667         if (!empty($q['query']['project_member_of'])) {
668                // this is also a flag to return if they are a member..
669             //DB_DataObject::debugLevel(1);
670             $do = DB_DataObject::factory('ProjectDirectory');
671             $do->project_id = $q['query']['project_member_of'];
672             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
673             $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
674             $this->selectAdd("IF($tn_pd.id IS NULL, 0,  $tn_pd.id )  as is_member");
675                 
676                 
677             if (!empty($q['query']['project_member_filter'])) {
678                 $this->having('is_member !=0');
679             
680             }
681             
682         }
683         
684         if (!empty($q['query']['search'])) {
685             $s = $this->escape($q['query']['search']);
686                     $this->whereAdd("
687                         $tn_p.name LIKE '%$s%'  OR
688                         $tn_p.email LIKE '%$s%'  OR
689                         $tn_p.role LIKE '%$s%'  OR
690                         $tn_p.phone LIKE '%$s%' OR
691                         $tn_p.remarks LIKE '%$s%' 
692                         
693                     ");
694         }
695         
696         //
697     }
698     function setFromRoo($ar, $roo)
699     {
700         $this->setFrom($ar);
701         if (!empty($ar['passwd1'])) {
702             $this->setPassword($ar['passwd1']);
703         }
704         
705         
706         if (    $this->id &&
707                 ($this->email == $roo->old->email)&&
708                 ($this->company_id == $roo->old->company_id)
709             ) {
710             return true;
711         }
712         if (empty($this->email)) {
713             return true;
714         }
715         $xx = DB_Dataobject::factory('Person');
716         $xx->setFrom(array(
717             'email' => $this->email,
718            // 'company_id' => $x->company_id
719         ));
720         
721         if ($xx->count()) {
722             return "Duplicate Email found";
723         }
724         return true;
725     }
726     /**
727      *
728      * before Delete - delete significant dependancies..
729      * this is called after checkPerm..
730      */
731     
732     function beforeDelete()
733     {
734         
735         $e = DB_DataObject::Factory('Events');
736         $e->whereAdd('person_id = ' . $this->id);
737         $e->delete(true);
738         
739         // anything else?  
740         
741     }
742     
743     
744     /***
745      * Check if the a user has access to modify this item.
746      * @param String $lvl Level (eg. Core.Projects)
747      * @param Pman_Core_DataObjects_Person $au The authenticated user.
748      * @param boolean $changes alllow changes???
749      *
750      * @return false if no access..
751      */
752     function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
753     {
754          
755        // do we have an empty system..
756         if ($au && $au->id == -1) {
757             return true;
758         }
759         
760         // determine if it's staff!!!
761          
762         if ($au->company()->comptype != 'OWNER') {
763             
764             // - can not change company!!!
765             if ($changes && 
766                 isset($changes['company_id']) && 
767                 $changes['company_id'] != $au->company_id) {
768                 return false;
769             }
770             // can only set new emails..
771             if ($changes && 
772                     !empty($this->email) && 
773                     isset($changes['email']) && 
774                     $changes['email'] != $this->email) {
775                 return false;
776             }
777             
778             // edit self... - what about other staff members...
779             
780             return $this->company_id == $au->company_id;
781         }
782          
783          
784         // yes, only owner company can mess with this...
785         $owncomp = DB_DataObject::Factory('Companies');
786         $owncomp->get('comptype', 'OWNER');
787         
788         $isStaff = ($this->company_id ==  $owncomp->id);
789         
790     
791         switch ($lvl) {
792             // extra case change passwod?
793             case 'P': //??? password
794                 // standard perms -- for editing + if the user is dowing them selves..
795                 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
796                 return $ret || $au->id == $this->id;
797             
798             default:                
799                 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
800         
801         }
802         return false;
803     }
804     function onInsert($req, $roo)  
805     {
806         
807         if ($roo->authUser->id < 0) {
808             $g = DB_DataObject::factory('Groups');
809             $g->type = 0;
810             $g->get('name', 'Administrators');
811             
812             $p = DB_DataObject::factory('group_members');
813             $p->group_id = $g->id;
814             $p->user_id = $this->id;     
815             if (!$p->count()) {
816                 $p->insert();
817                 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
818             }
819             $this->login();
820         }
821         if (!empty($req['project_id_addto'])) {
822             $pd = DB_DataObject::factory('ProjectDirectory');
823             $pd->project_id = $req['project_id_addto'];
824             $pd->person_id = $this->id; 
825             $pd->ispm =0;
826             $pd->office_id = $this->office_id;
827             $pd->company_id = $this->company_id;
828             $pd->insert();
829         }
830         
831     }
832  }