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