DataObjects/Core_notify.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          
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         
318         
319         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
320             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
321             
322             $u = DB_DataObject::factory('Person');
323             if ($u->get($a->id)) { /// && strlen($u->passwd)) {
324                 return clone($u);
325             }
326              
327         }
328         
329         if (empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
330             $u = DB_DataObject::factory('Person');
331             $u->whereAdd(' LENGTH(passwd) > 0');
332              $_SESSION[__CLASS__][$sesPrefix .'-empty']  = $u->count();
333         }
334                 
335              
336         if (empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
337             
338             // fake person - open system..
339             //$ce = DB_DataObject::factory('core_enum');
340             //$ce->initEnums();
341             
342             
343             $u = DB_DataObject::factory('Person');
344             $u->id = -1;
345             return $u;
346             
347         }
348         return false;
349     }     
350     function login()
351     {
352         $this->isAuth(); // force session start..
353         $this->verifyAuth();
354         $db = $this->getDatabaseConnection();
355         
356         
357         // open up iptables at login..
358         $dbname = $this->database();
359         touch( '/tmp/run_pman_admin_iptables-'.$dbname);
360          
361         // refresh admin group if we are logged in as one..
362         //DB_DataObject::debugLevel(1);
363         $g = DB_DataObject::factory('Groups');
364         $g->type = 0;
365         $g->get('name', 'Administrators');
366         $gm = DB_DataObject::Factory('group_members');
367         if (in_array($g->id,$gm->listGroupMembership($this))) {
368             // refresh admin groups.
369             $gr = DB_DataObject::Factory('group_rights');
370             $gr->applyDefs($g, 0);
371         }
372              
373         $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
374         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
375         
376     }
377     function logout()
378     {
379         $this->isAuth(); // force session start..
380          $db = $this->getDatabaseConnection();
381         $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
382         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
383         
384     }    
385     function genPassKey ($t) 
386     {
387         return md5($this->email . $t. $this->passwd);
388     }
389     function simpleAuthKey($m = 0)
390     {
391         $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
392         
393         return md5(implode(',' ,  array($month, $this->email , $this->passwd, $this->id)));
394     } 
395     function checkPassword($val)
396     {
397         
398         if (substr($this->passwd,0,1) == '$') {
399             return crypt($val,$this->passwd) == $this->passwd ;
400         }
401         // old style md5 passwords...- cant be used with courier....
402         return md5($val) == $this->passwd;
403     }
404     function setPassword($value) 
405     {
406         $salt='';
407         while(strlen($salt)<9) {
408             $salt.=chr(rand(64,126));
409             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
410         }
411         $this->passwd = crypt($value, '$1$'. $salt. '$');
412        
413        
414     }      
415     
416     function generatePassword() // genearte a password (add set 'rawPasswd' to it's value)
417     {
418         require_once 'Text/Password.php';
419         $this->rawPasswd = strtr(ucfirst(Text_Password::create(5)).ucfirst(Text_Password::create(5)), array(
420         "a"=>"4", "e"=>"3",  "i"=>"1",  "o"=>"0", "s"=>"5",  "t"=>"7"));
421         $this->setPassword($this->rawPasswd);
422         return $this->rawPasswd;
423     }
424     
425     function company()
426     {
427         $x = DB_DataObject::factory('Companies');
428         $x->autoJoin();
429         $x->get($this->company_id);
430         return $x;
431     }
432     function loadCompany()
433     {
434         $this->company = $this->company();
435     }
436     
437     function active()
438     { 
439         return $this->active;
440     }
441     function authUserName($n) // set username prior to acheck user exists query.
442     {
443         
444         $this->whereAdd('LENGTH(passwd) > 1'); 
445         $this->email = $n;
446     }
447     function lang($val)
448     {
449         if ($val == $this->lang) {
450             return;
451         }
452         $uu = clone($this);
453         $this->lang = $val;
454         $this->update($uu);
455
456     }
457             
458     
459     function authUserArray()
460     {
461         
462         $aur = $this->toArray();
463         
464         if ($this->id < 1) {
465             return $aur;
466         }
467         
468         
469         //DB_DataObject::debugLevel(1);
470         $c = DB_Dataobject::factory('Companies');
471         $im = DB_Dataobject::factory('Images');
472         $c->joinAdd($im, 'LEFT');
473         $c->selectAdd();
474         $c->selectAs($c, 'company_id_%s');
475         $c->selectAs($im, 'company_id_logo_id_%s');
476         $c->id = $this->company_id;
477         $c->limit(1);
478         $c->find(true);
479         
480         $aur = array_merge( $c->toArray(),$aur);
481         
482         if (empty($c->company_id_logo_id_id))  {
483                  
484             $im = DB_Dataobject::factory('Images');
485             $im->ontable = 'Companies';
486             $im->onid = $c->id;
487             $im->imgtype = 'LOGO';
488             $im->limit(1);
489             $im->selectAdd();
490             $im->selectAs($im,  'company_id_logo_id_%s');
491             if ($im->find(true)) {
492                     
493                 foreach($im->toArray() as $k=>$v) {
494                     $aur[$k] = $v;
495                 }
496             }
497         }
498       
499         // perms + groups.
500         $aur['perms']  = $this->getPerms();
501         $g = DB_DataObject::Factory('group_members');
502         $aur['groups']  = $g->listGroupMembership($this, 'name');
503         
504         $aur['passwd'] = '';
505         $aur['dailykey'] = '';
506         
507         
508         
509         return $aur;
510     }
511     
512     //   ----------PERMS------  ----------------
513     function getPerms() 
514     {
515          //DB_DataObject::debugLevel(1);
516         // find out all the groups they are a member of.. + Default..
517         
518         // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
519         
520         $g = DB_DataObject::Factory('group_rights');
521         if (!$g->count()) {
522             $g->genDefault();
523         }
524         
525         if ($this->id < 0) {
526             return $g->adminRights(); // system is not set up - so they get full rights.
527         }
528         //DB_DataObject::debugLevel(1);
529         $g = DB_DataObject::Factory('group_members');
530         $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
531         if (!$g->count()) {
532             // add the current user to the admin group..
533             $g = DB_DataObject::Factory('Groups');
534             if ($g->get('name', 'Administrators')) {
535                 $gm = DB_DataObject::Factory('group_members');
536                 $gm->group_id = $g->id;
537                 $gm->user_id = $this->id;
538                 $gm->insert();
539             }
540             
541         }
542         
543         // ------ STANDARD PERMISSION HANDLING.
544         $isOwner = $this->company()->comptype == 'OWNER';
545         $g = DB_DataObject::Factory('group_members');
546         $grps = $g->listGroupMembership($this);
547        //var_dump($grps);
548         $isAdmin = $g->inAdmin;
549         //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
550         // the load all the perms for those groups, and add them all together..
551         // then load all those 
552         $g = DB_DataObject::Factory('group_rights');
553         $ret =  $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
554         //echo '<PRE>';print_r($ret);
555         return $ret;
556          
557         
558     }
559     /**
560      *Basic group fetching - probably needs to filter by type eventually.
561      *
562      *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
563      */
564     
565     function groups($what=false)
566     {
567         $g = DB_DataObject::Factory('group_members');
568         $grps = $g->listGroupMembership($this);
569         $g = DB_DataObject::Factory('Groups');
570         $g->whereAddIn('id', $grps, 'int');
571         return $g->fetchAll($what);
572         
573     }
574     
575     
576     
577     function hasPerm($name, $lvl) 
578     {
579         static $pcache = array();
580         
581         if (!isset($pcache[$this->id])) {
582             $pcache[$this->id] = $this->getPerms();
583         }
584        // echo "<PRE>";print_r($pcache[$au->id]);
585        // var_dump($pcache[$au->id]);
586         if (empty($pcache[$this->id][$name])) {
587             return false;
588         }
589         
590         return strpos($pcache[$this->id][$name], $lvl) > -1;
591         
592     }    
593     
594     //  ------------ROO HOOKS------------------------------------
595     function applyFilters($q, $au, $roo)
596     {
597         //DB_DataObject::DebugLevel(1);
598         if (!empty($q['query']['person_not_internal'])) {
599             $this->whereAdd(" join_company_id_id.isOwner = 0 ");
600         }
601         
602         
603         if (!empty($q['query']['person_internal_only_all'])) {
604             
605             
606             // must be internal and not current user (need for distribution list)
607             // user has a projectdirectory entry and role is not blank.
608             //DB_DataObject::DebugLevel(1);
609             $pd = DB_DataObject::factory('ProjectDirectory');
610             $pd->whereAdd("role != ''");
611             $pd->selectAdd();
612             $pd->selectAdd('distinct(person_id) as person_id');
613             $roled = $pd->fetchAll('person_id');
614             $rs = $roled  ? "  OR
615                     {$this->tableName()}.id IN (".implode(',', $roled) . ") 
616                     " : '';
617             $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
618             
619         }
620         // -- for distribution
621         if (!empty($q['query']['person_internal_only'])) {
622             // must be internal and not current user (need for distribution list)
623             $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
624             
625             //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
626             //    ".id  != ".$au->id);
627             $this->whereAdd("Person.id != {$au->id}");
628         } 
629         
630         if (!empty($q['query']['comptype_or_company_id'])) {
631            // DB_DataObject::debugLevel(1);
632             $bits = explode(',', $q['query']['comptype_or_company_id']);
633             $id = (int) array_pop($bits);
634             $ct = $this->escape($bits[0]);
635             
636             $this->whereAdd(" join_company_id_id.comptype = '$ct' OR Person.company_id = $id");
637             
638         }
639         
640         
641         // staff list..
642         if (!empty($q['query']['person_inactive'])) {
643            // DB_Dataobject::debugLevel(1);
644             $this->active = 1;
645         }
646         $tn_p = $this->tableName();
647         $tn_gm = DB_DataObject::Factory('group_members')->tableName();
648         $tn_g = DB_DataObject::Factory('Groups')->tableName();
649
650         ///---------------- Group views --------
651         if (!empty($q['query']['in_group'])) {
652             // DB_DataObject::debugLevel(1);
653             $ing = (int) $q['query']['in_group'];
654             if ($q['query']['in_group'] == -1) {
655              
656                 // list all staff who are not in a group.
657                 $this->whereAdd("Person.id NOT IN (
658                     SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
659                         $tn_g ON $tn_g.id = $tn_gm.group_id
660                         WHERE $tn_g.type = ".$q['query']['type']."
661                     )");
662                 
663                 
664             } else {
665                 
666                 $this->whereAdd("$tn_p.id IN (
667                     SELECT distinct(user_id) FROM $tn_gm
668                         WHERE group_id = $ing
669                     )");
670                }
671             
672         }
673         
674         if (!empty($q['query']['not_in_directory'])) { 
675             // it's a Person list..
676             // DB_DATaobjecT::debugLevel(1);
677             
678             // specific to project directory which is single comp. login
679             //
680             $owncomp = DB_DataObject::Factory('Companies');
681             $owncomp->get('comptype', 'OWNER');
682             if ($q['company_id'] == $owncomp->id) {
683                 $this->active =1;
684             }
685             
686             
687
688             if ( $q['query']['not_in_directory'] > -1) {
689                 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
690                 // can list current - so that it does not break!!!
691                 $this->whereAdd("$tn_p.id NOT IN 
692                     ( SELECT distinct person_id FROM $tn_pd WHERE
693                         project_id = " . $q['query']['not_in_directory'] . " AND 
694                         company_id = " . $this->company_id . ')');
695             }
696         }
697            
698         if (!empty($q['query']['role'])) { 
699             // it's a Person list..
700             // DB_DATaobjecT::debugLevel(1);
701             
702             // specific to project directory which is single comp. login
703             //
704             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
705                 // can list current - so that it does not break!!!
706             $this->whereAdd("$tn_p.id IN 
707                     ( SELECT distinct person_id FROM $tn_pd WHERE
708                         role = '". $this->escape($q['query']['role']) ."'
709             )");
710         
711         }
712         
713         
714         if (!empty($q['query']['project_member_of'])) {
715                // this is also a flag to return if they are a member..
716             //DB_DataObject::debugLevel(1);
717             $do = DB_DataObject::factory('ProjectDirectory');
718             $do->project_id = $q['query']['project_member_of'];
719             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
720             $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
721             $this->selectAdd("IF($tn_pd.id IS NULL, 0,  $tn_pd.id )  as is_member");
722                 
723                 
724             if (!empty($q['query']['project_member_filter'])) {
725                 $this->having('is_member !=0');
726             
727             }
728             
729         }
730         
731         if (!empty($q['query']['search'])) {
732             $s = $this->escape($q['query']['search']);
733                     $this->whereAdd("
734                         $tn_p.name LIKE '%$s%'  OR
735                         $tn_p.email LIKE '%$s%'  OR
736                         $tn_p.role LIKE '%$s%'  OR
737                         $tn_p.phone LIKE '%$s%' OR
738                         $tn_p.remarks LIKE '%$s%' 
739                         
740                     ");
741         }
742         
743         //
744     }
745     function setFromRoo($ar, $roo)
746     {
747         $this->setFrom($ar);
748         if (!empty($ar['passwd1'])) {
749             $this->setPassword($ar['passwd1']);
750         }
751         
752         
753         if (    $this->id &&
754                 ($this->email == $roo->old->email)&&
755                 ($this->company_id == $roo->old->company_id)
756             ) {
757             return true;
758         }
759         if (empty($this->email)) {
760             return true;
761         }
762         $xx = DB_Dataobject::factory('Person');
763         $xx->setFrom(array(
764             'email' => $this->email,
765            // 'company_id' => $x->company_id
766         ));
767         
768         if ($xx->count()) {
769             return "Duplicate Email found";
770         }
771         return true;
772     }
773     /**
774      *
775      * before Delete - delete significant dependancies..
776      * this is called after checkPerm..
777      */
778     
779     function beforeDelete()
780     {
781         
782         $e = DB_DataObject::Factory('Events');
783         $e->whereAdd('person_id = ' . $this->id);
784         $e->delete(true);
785         
786         // anything else?  
787         
788     }
789     
790     
791     /***
792      * Check if the a user has access to modify this item.
793      * @param String $lvl Level (eg. Core.Projects)
794      * @param Pman_Core_DataObjects_Person $au The authenticated user.
795      * @param boolean $changes alllow changes???
796      *
797      * @return false if no access..
798      */
799     function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
800     {
801          
802        // do we have an empty system..
803         if ($au && $au->id == -1) {
804             return true;
805         }
806         
807         // determine if it's staff!!!
808          
809         if ($au->company()->comptype != 'OWNER') {
810             
811             // - can not change company!!!
812             if ($changes && 
813                 isset($changes['company_id']) && 
814                 $changes['company_id'] != $au->company_id) {
815                 return false;
816             }
817             // can only set new emails..
818             if ($changes && 
819                     !empty($this->email) && 
820                     isset($changes['email']) && 
821                     $changes['email'] != $this->email) {
822                 return false;
823             }
824             
825             // edit self... - what about other staff members...
826             
827             return $this->company_id == $au->company_id;
828         }
829          
830          
831         // yes, only owner company can mess with this...
832         $owncomp = DB_DataObject::Factory('Companies');
833         $owncomp->get('comptype', 'OWNER');
834         
835         $isStaff = ($this->company_id ==  $owncomp->id);
836         
837     
838         switch ($lvl) {
839             // extra case change passwod?
840             case 'P': //??? password
841                 // standard perms -- for editing + if the user is dowing them selves..
842                 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
843                 return $ret || $au->id == $this->id;
844             
845             default:                
846                 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
847         
848         }
849         return false;
850     }
851     function onInsert($req, $roo)  
852     {
853          
854         $p = DB_DataObject::factory('person');
855         if ($roo->authUser->id < 0 && $p->count() == 1) {
856             // this seems a bit risky...
857             
858             $g = DB_DataObject::factory('Groups');
859             $g->initGroups();
860             
861             $g->type = 0;
862             $g->get('name', 'Administrators');
863             
864             $p = DB_DataObject::factory('group_members');
865             $p->group_id = $g->id;
866             $p->user_id = $this->id;     
867             if (!$p->count()) {
868                 $p->insert();
869                 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
870             }
871             $this->login();
872         }
873         if (!empty($req['project_id_addto'])) {
874             $pd = DB_DataObject::factory('ProjectDirectory');
875             $pd->project_id = $req['project_id_addto'];
876             $pd->person_id = $this->id; 
877             $pd->ispm =0;
878             $pd->office_id = $this->office_id;
879             $pd->company_id = $this->company_id;
880             $pd->insert();
881         }
882         
883     }
884     
885     function importFromArray($roo, $persons, $prefix)
886     {
887         foreach($persons as $person){
888             $p = DB_DataObject::factory('person');
889             if($p->get('name', $person['name'])){
890                 continue;
891             }
892             $p->setFrom($person);
893             
894             $companies = DB_DataObject::factory('companies');
895             if(!$companies->get('comptype', 'OWNER')){
896                 $roo->jerr("Missing OWNER companies!");
897             }
898             $p->company_id = $companies->pid();
899             // strip the 'spaces etc.. make lowercase..
900             $name = strtolower(str_replace(' ', '', $person['name']));
901             $p->setPassword("$prefix$name");
902             $p->insert();
903             // set up groups
904             // if $person->groups is set.. then
905             // add this person to that group eg. groups : [ 'Administrator' ] 
906             if(!empty($person['groups'])){
907                 $groups = DB_DataObject::factory('groups');
908                 if(!$groups->get('name', $person['groups'])){
909                     $roo->jerr("Missing groups : {$person['groups']}");
910                 }
911                 $gm = DB_DataObject::factory('group_members');
912                 $gm->change($p, $groups, true);
913             }
914             
915             $p->onInsert(array(), $roo);
916         }
917     }
918  }