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