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