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