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