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