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