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