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