DataObjects/Core_person.php
[Pman.Core] / DataObjects / Core_person.php
1 <?php
2 /**
3  * Table Definition for Person
4  */
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
6
7
8 class Pman_Core_DataObjects_Core_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 = 'core_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($this->tableName());
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 (is_a($parts,'PEAR_Error')) {
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     
228     function toEventString() 
229     {
230         return empty($this->name) ? $this->email : $this->name;
231     } 
232     
233     function verifyAuth()
234     { 
235         $ff= HTML_FlexyFramework::get();
236         if (!empty($ff->Pman['auth_comptype']) &&
237             (!$this->company_id || ($ff->Pman['auth_comptype'] != $this->company()->comptype))
238            ){
239             
240             $sesPrefix = $this->sesPrefix();
241        
242             $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
243             
244             return false;
245             
246             //$ff->page->jerr("Login not permited to outside companies");
247         }
248         return true;
249         
250     }    
251    
252    
253     //   ---------------- authentication / passwords and keys stuff  ----------------
254     function isAuth()
255     {
256         
257         @session_start();
258        
259         $ff= HTML_FlexyFramework::get();
260        
261         $sesPrefix = $this->sesPrefix();
262         
263         if (!empty($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
264             // in session...
265             $a = unserialize($_SESSION[get_class($this)][$sesPrefix .'-auth']);
266              
267             $u = DB_DataObject::factory($this->tableName());
268             if ($a->id && $u->get($a->id)) { //&& strlen($u->passwd)) {
269               
270                 return $u->verifyAuth();  // got authentication...
271                 
272     
273             }
274             
275             unset($_SESSION[get_class($this)][$sesPrefix .'-auth']);
276             unset($_SESSION[get_class($this)][$sesPrefix .'-timeout']);
277             setcookie('Pman.timeout', -1, time() + (30*60), '/');
278             
279         }
280         
281         // http basic auth..
282         $u = DB_DataObject::factory($this->tableName());
283         
284         if (!empty($_SERVER['PHP_AUTH_USER']) 
285             &&
286             !empty($_SERVER['PHP_AUTH_PW'])
287             &&
288             $u->get('email', $_SERVER['PHP_AUTH_USER'])
289             &&
290             $u->checkPassword($_SERVER['PHP_AUTH_PW'])
291            ) {
292             $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize($u);
293             return true; 
294         }
295         //die("test init");
296         if (!$this->canInitializeSystem()) {
297           //  die("can not init");
298             return false;
299         }
300         
301         
302         // local auth - 
303         $default_admin = false;
304         if (!empty($ff->Pman['local_autoauth']) && 
305             ($ff->Pman['local_autoauth'] === true) &&
306             (!empty($_SERVER['SERVER_ADDR'])) &&
307             (
308                 (
309                     $_SERVER['SERVER_ADDR'] == '127.0.0.1' &&
310                     $_SERVER['REMOTE_ADDR'] == '127.0.0.1'
311                 )
312                 ||
313                 (
314                     $_SERVER['SERVER_ADDR'] == '::1' &&
315                     $_SERVER['REMOTE_ADDR'] == '::1'
316                 )
317             )
318         ) {
319             $group = DB_DataObject::factory('core_group');
320             $group->get('name', 'Administrators');
321             
322             $member = DB_DataObject::factory('core_group_member');
323             $member->autoJoin();
324             $member->group_id = $group->id;
325             $member->whereAdd("
326                 join_user_id_id.id IS NOT NULL
327             ");
328             if($member->find(true)){
329                 $default_admin = DB_DataObject::factory($this->tableName());
330                 if(!$default_admin->get($member->user_id)){
331                     $default_admin = false;
332                 }
333             }
334         }
335         
336         //var_dump($ff->Pman['local_autoauth']);         var_dump($_SERVER); exit;
337         $u = DB_DataObject::factory($this->tableName());
338         $ff = HTML_FlexyFramework::get();
339         
340         if (!empty($ff->Pman['local_autoauth']) && 
341             (!empty($_SERVER['SERVER_ADDR'])) &&
342             (
343                 (
344                     $_SERVER['SERVER_ADDR'] == '127.0.0.1' &&
345                     $_SERVER['REMOTE_ADDR'] == '127.0.0.1'
346                 )
347                 ||
348                 (
349                     $_SERVER['SERVER_ADDR'] == '::1' &&
350                     $_SERVER['REMOTE_ADDR'] == '::1'
351                 )
352             ) &&
353             ($default_admin ||  $u->get('email', $ff->Pman['local_autoauth']))
354         ) {
355             $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize($default_admin ? $default_admin : $u);
356             return true;
357         }
358         
359         //var_dump(session_id());
360         //var_dump($_SESSION[__CLASS__]);
361         
362         //if (!empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
363         //    return false;
364         //}
365         //die("got this far?");
366         // not in session or not matched...
367         $u = DB_DataObject::factory($this->tableName());
368         $u->whereAdd(' LENGTH(passwd) > 0');
369         $n = $u->count();
370         $_SESSION[get_class($this)][$sesPrefix .'-empty']  = $n;
371         if (class_exists('PEAR')) {
372             $error =  PEAR::getStaticProperty('DB_DataObject','lastError');
373             if ($error) {
374                 die($error->toString()); // not really a good thing to do...
375             }
376         }
377         if (!$n){ // authenticated as there are no users in the system...
378             return true;
379         }
380         
381         return false;
382         
383     }
384     
385     function canInitializeSystem()
386     {
387         
388         return !strcasecmp(get_class($this) , __CLASS__);
389     }
390     
391     function getAuthUser()
392     {
393         if (!$this->isAuth()) {
394             return false;
395         }
396         
397         $ff= HTML_FlexyFramework::get();
398         
399         $sesPrefix = $this->sesPrefix();
400         
401         //var_dump(array(get_class($this),$sesPrefix .'-auth'));
402        
403         if (!empty($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
404             $a = unserialize($_SESSION[get_class($this)][$sesPrefix .'-auth']);
405             
406             $u = DB_DataObject::factory($this->tableName()); // allow extending this ...
407             $u->autoJoin();
408             if ($u->get($a->id)) { /// && strlen($u->passwd)) {  // should work out the pid .. really..
409                 
410                 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
411                 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
412                 
413                 $user = clone ($u);
414                 return clone($user);
415             
416             }
417             unset($_SESSION[get_class($this)][$sesPrefix .'-auth']);
418             unset($_SESSION[get_class($this)][$sesPrefix .'-timeout']);
419             setcookie('Pman.timeout', -1, time() + (30*60), '/');
420             
421         }
422         
423         
424         
425         if (!$this->canInitializeSystem()) {
426             return false;
427         }
428         
429         
430         
431         if (empty(   $_SESSION[get_class($this)][$sesPrefix .'-empty'] )) {
432             $u = DB_DataObject::factory($this->tableName());
433             $u->whereAdd(' LENGTH(passwd) > 0');
434             $_SESSION[get_class($this)][$sesPrefix .'-empty']  = $u->count();
435         }
436                 
437              
438         if (isset(   $_SESSION[get_class($this)][$sesPrefix .'-empty'] ) && $_SESSION[get_class($this)][$sesPrefix .'-empty']  < 1) {
439             
440             // fake person - open system..
441             //$ce = DB_DataObject::factory('core_enum');
442             //$ce->initEnums();
443             
444             
445             $u = DB_DataObject::factory($this->tableName());
446             $u->id = -1;
447             
448             // if a company has been created fill that in in company_id_id
449             $c = DB_DAtaObject::factory('core_company')->lookupOwner();
450             if ($c) {
451                 $u->company_id_id = $c->pid();
452                 $u->company_id = $c->pid();
453             }
454             
455             return $u;
456             
457         }
458         return false;
459     }     
460     function login()
461     {
462         $this->isAuth(); // force session start..
463         if (!$this->verifyAuth()) { // check for company valid..
464             return false;
465         }
466         
467         // open up iptables at login..
468         $dbname = $this->databaseNickname();
469         touch( '/tmp/run_pman_admin_iptables-'.$dbname);
470          
471         // refresh admin group if we are logged in as one..
472         //DB_DataObject::debugLevel(1);
473         $g = DB_DataObject::factory('core_group');
474         $g->type = 0;
475         $g->get('name', 'Administrators');
476         $gm = DB_DataObject::Factory('core_group_member');
477         if (in_array($g->id,$gm->listGroupMembership($this))) {
478             // refresh admin groups.
479             $gr = DB_DataObject::Factory('core_group_right');
480             $gr->applyDefs($g, 0);
481         }
482         
483         $sesPrefix = $this->sesPrefix();
484         
485         // we should not store the whole data in the session - otherwise it get's huge.
486         $p = DB_DAtaObject::Factory($this->tableName());
487         $p->get($this->pid());
488         
489         $d = $p->toArray();
490         
491         $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
492         setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
493         
494         //var_dump(array(get_class($this),$sesPrefix .'-auth'));
495         $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$d);
496         // ensure it's written so that ajax calls can fetch it..
497         
498         
499         
500     }
501     function logout()
502     {
503         $this->isAuth(); // force session start..
504         
505         $sesPrefix = $this->sesPrefix();
506         
507         $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = -1;
508         
509         $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
510         
511     }    
512     function genPassKey ($t) 
513     {
514         return md5($this->email . $t. $this->passwd);
515     }
516     function simpleAuthKey($m = 0)
517     {
518         $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
519         
520         return md5(implode(',' ,  array($month, $this->email , $this->passwd, $this->id)));
521     } 
522     function checkPassword($val)
523     {
524         if (substr($this->passwd,0,1) == '$') {
525             if (function_exists('pasword_verify')) {
526                 return password_verify($val, $this->passwd);
527             }
528             return crypt($val,$this->passwd) == $this->passwd ;
529         }
530         // old style md5 passwords...- cant be used with courier....
531         return md5($val) == $this->passwd;
532     }
533     
534     function setPassword($value) 
535     {
536         if (function_exists('pasword_hash')) {
537             return password_hash($value);
538         }
539         
540         $salt='';
541         while(strlen($salt)<9) {
542             $salt.=chr(rand(64,126));
543             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
544         }
545         $this->passwd = crypt($value, '$1$'. $salt. '$');
546        
547        
548     }      
549     
550     function generatePassword($length = 5) // genearte a password (add set 'rawPasswd' to it's value)
551     {
552         require_once 'Text/Password.php';
553         $this->rawPasswd = strtr(ucfirst(Text_Password::create($length)).ucfirst(Text_Password::create($length)), array(
554         "a"=>"4", "e"=>"3",  "i"=>"1",  "o"=>"0", "s"=>"5",  "t"=>"7"));
555         $this->setPassword($this->rawPasswd);
556         return $this->rawPasswd;
557     }
558     
559     function company()
560     {
561         $x = DB_DataObject::factory('core_company');
562         $x->autoJoin();
563         $x->get($this->company_id);
564         return $x;
565     }
566     function loadCompany()
567     {
568         $this->company = $this->company();
569     }
570     
571     function active()
572     { 
573         return $this->active;
574     }
575     function authUserName($n) // set username prior to acheck user exists query.
576     {
577         
578         $this->whereAdd('LENGTH(passwd) > 1'); 
579         $this->email = $n;
580     }
581     function lang()
582     {
583         if (!func_num_args()) {
584             return $this->lang;
585         }
586         $val = array_shift(func_get_args());
587         if ($val == $this->lang) {
588             return;
589         }
590         $uu = clone($this);
591         $this->lang = $val;
592         $this->update($uu);
593         return $this->lang;
594     }
595             
596     
597     function authUserArray()
598     {
599         
600         $aur = $this->toArray();
601         
602         if ($this->id < 1) {
603             return $aur;
604         }
605         
606         
607         //DB_DataObject::debugLevel(1);
608         $c = DB_Dataobject::factory('core_company');
609         $im = DB_Dataobject::factory('Images');
610         $c->joinAdd($im, 'LEFT');
611         $c->selectAdd();
612         $c->selectAs($c, 'company_id_%s');
613         $c->selectAs($im, 'company_id_logo_id_%s');
614         $c->id = $this->company_id;
615         $c->limit(1);
616         $c->find(true);
617         
618         $aur = array_merge( $c->toArray(),$aur);
619         
620         if (empty($c->company_id_logo_id_id))  {
621                  
622             $im = DB_Dataobject::factory('Images');
623             $im->ontable = DB_DataObject::factory('core_company')->tableName();
624             $im->onid = $c->id;
625             $im->imgtype = 'LOGO';
626             $im->limit(1);
627             $im->selectAdd();
628             $im->selectAs($im,  'company_id_logo_id_%s');
629             if ($im->find(true)) {
630                     
631                 foreach($im->toArray() as $k=>$v) {
632                     $aur[$k] = $v;
633                 }
634             }
635         }
636       
637         // perms + groups.
638         $aur['perms']  = $this->getPerms();
639         $g = DB_DataObject::Factory('core_group_member');
640         $aur['groups']  = $g->listGroupMembership($this, 'name');
641         
642         $aur['passwd'] = '';
643         $aur['dailykey'] = '';
644         $aur['oath_key'] = '';
645         
646         
647         return $aur;
648     }
649     
650     //   ----------PERMS------  ----------------
651     function getPerms() 
652     {
653          //DB_DataObject::debugLevel(1);
654         // find out all the groups they are a member of.. + Default..
655         
656         // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
657         
658         $g = DB_DataObject::Factory('core_group_right');
659         if (!$g->count()) {
660             $g->genDefault();
661         }
662         
663         if ($this->id < 0) {
664             return $g->adminRights(); // system is not set up - so they get full rights.
665         }
666         //DB_DataObject::debugLevel(1);
667         $g = DB_DataObject::Factory('core_group_member');
668         $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
669         if (!$g->count()) {
670             // add the current user to the admin group..
671             $g = DB_DataObject::Factory('core_group');
672             if ($g->get('name', 'Administrators')) {
673                 $gm = DB_DataObject::Factory('core_group_member');
674                 $gm->group_id = $g->id;
675                 $gm->user_id = $this->id;
676                 $gm->insert();
677             }
678             
679         }
680         
681         // ------ STANDARD PERMISSION HANDLING.
682         $isOwner = $this->company()->comptype == 'OWNER';
683         $g = DB_DataObject::Factory('core_group_member');
684         $grps = $g->listGroupMembership($this);
685        //var_dump($grps);
686         $isAdmin = $g->inAdmin;   //???  what???
687         //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
688         // the load all the perms for those groups, and add them all together..
689         // then load all those 
690         $g = DB_DataObject::Factory('core_group_right');
691         $ret =  $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
692         //echo '<PRE>';print_r($ret);
693         return $ret;
694          
695         
696     }
697     /**
698      *Basic group fetching - probably needs to filter by type eventually.
699      *
700      *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
701      */
702     
703     function groups($what=false)
704     {
705         $g = DB_DataObject::Factory('core_group_member');
706         $grps = $g->listGroupMembership($this);
707         $g = DB_DataObject::Factory('core_group');
708         $g->whereAddIn('id', $grps, 'int');
709         return $g->fetchAll($what);
710         
711     }
712     
713     
714     
715     function hasPerm($name, $lvl) 
716     {
717         static $pcache = array();
718         
719         if (!isset($pcache[$this->id])) {
720             $pcache[$this->id] = $this->getPerms();
721         }
722         
723        // echo "<PRE>";print_r($pcache[$au->id]);
724        // var_dump($pcache[$au->id]);
725         if (empty($pcache[$this->id][$name])) {
726             return false;
727         }
728         
729         return strpos($pcache[$this->id][$name], $lvl) > -1;
730         
731     }    
732     
733     //  ------------ROO HOOKS------------------------------------
734     function applyFilters($q, $au, $roo)
735     {
736         //DB_DataObject::DebugLevel(1);
737         
738         if (!empty($q['query']['is_owner'])) {
739             $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
740         }
741         
742         if (!empty($q['query']['person_not_internal'])) {
743             $this->whereAdd(" join_company_id_id.isOwner = 0 ");
744         }
745         
746         if (!empty($q['query']['person_internal_only_all'])) {
747             
748             
749             // must be internal and not current user (need for distribution list)
750             // user has a projectdirectory entry and role is not blank.
751             //DB_DataObject::DebugLevel(1);
752             $pd = DB_DataObject::factory('ProjectDirectory');
753             $pd->whereAdd("role != ''");
754             $pd->selectAdd();
755             $pd->selectAdd('distinct(person_id) as person_id');
756             $roled = $pd->fetchAll('person_id');
757             $rs = $roled  ? "  OR
758                     {$this->tableName()}.id IN (".implode(',', $roled) . ") 
759                     " : '';
760             $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
761             
762         }
763         // -- for distribution
764         if (!empty($q['query']['person_internal_only'])) {
765             // must be internal and not current user (need for distribution list)
766             $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
767             
768             //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
769             //    ".id  != ".$au->id);
770             $this->whereAdd("{$this->tableName()}.id != {$au->id}");
771         } 
772         
773         if (!empty($q['query']['comptype_or_company_id'])) {
774            // DB_DataObject::debugLevel(1);
775             $bits = explode(',', $q['query']['comptype_or_company_id']);
776             $id = (int) array_pop($bits);
777             $ct = $this->escape($bits[0]);
778             
779             $this->whereAdd(" join_company_id_id.comptype = '$ct' OR {$this->tableName()}.company_id = $id");
780             
781         }
782         
783         
784         // staff list..
785         if (!empty($q['query']['person_inactive'])) {
786            // DB_Dataobject::debugLevel(1);
787             $this->active = 1;
788         }
789         $tn_p = $this->tableName();
790         $tn_gm = DB_DataObject::Factory('core_group_member')->tableName();
791         $tn_g = DB_DataObject::Factory('core_group')->tableName();
792
793         ///---------------- Group views --------
794         if (!empty($q['query']['in_group'])) {
795             // DB_DataObject::debugLevel(1);
796             $ing = (int) $q['query']['in_group'];
797             if ($q['query']['in_group'] == -1) {
798              
799                 // list all staff who are not in a group.
800                 $this->whereAdd("{$this->tableName()}.id NOT IN (
801                     SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
802                         $tn_g ON $tn_g.id = $tn_gm.group_id
803                         WHERE $tn_g.type = ".$q['query']['type']."
804                     )");
805                 
806                 
807             } else {
808                 
809                 $this->whereAdd("$tn_p.id IN (
810                     SELECT distinct(user_id) FROM $tn_gm
811                         WHERE group_id = $ing
812                     )");
813                }
814             
815         }
816         
817         if(!empty($q['in_group_name'])){
818             
819             $v = $this->escape($q['in_group_name']);
820             
821             $this->whereAdd("
822                 $tn_p.id IN (
823                     SELECT 
824                         DISTINCT(user_id) FROM $tn_gm
825                     LEFT JOIN
826                         $tn_g
827                     ON
828                         $tn_g.id = $tn_gm.group_id
829                     WHERE 
830                         $tn_g.name = '{$v}'
831                 )"
832             );
833         }
834         
835         // #2307 Search Country!!
836         if (!empty($q['query']['in_country'])) {
837             // DB_DataObject::debugLevel(1);
838             $inc = $q['query']['in_country'];
839             $this->whereAdd("$tn_p.countries LIKE '%{$inc}%'");
840         }
841         
842         if (!empty($q['query']['not_in_directory'])) { 
843             // it's a Person list..
844             // DB_DATaobjecT::debugLevel(1);
845             
846             // specific to project directory which is single comp. login
847             //
848             $owncomp = DB_DataObject::Factory('core_company');
849             $owncomp->get('comptype', 'OWNER');
850             if ($q['company_id'] == $owncomp->id) {
851                 $this->active =1;
852             }
853             
854             
855
856             if ( $q['query']['not_in_directory'] > -1) {
857                 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
858                 // can list current - so that it does not break!!!
859                 $this->whereAdd("$tn_p.id NOT IN 
860                     ( SELECT distinct person_id FROM $tn_pd WHERE
861                         project_id = " . $q['query']['not_in_directory'] . " AND 
862                         company_id = " . $this->company_id . ')');
863             }
864         }
865            
866         if (!empty($q['query']['role'])) { 
867             // it's a Person list..
868             // DB_DATaobjecT::debugLevel(1);
869             
870             // specific to project directory which is single comp. login
871             //
872             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
873                 // can list current - so that it does not break!!!
874             $this->whereAdd("$tn_p.id IN 
875                     ( SELECT distinct person_id FROM $tn_pd WHERE
876                         role = '". $this->escape($q['query']['role']) ."'
877             )");
878         
879         }
880         
881         
882         if (!empty($q['query']['project_member_of'])) {
883                // this is also a flag to return if they are a member..
884             //DB_DataObject::debugLevel(1);
885             $do = DB_DataObject::factory('ProjectDirectory');
886             $do->project_id = $q['query']['project_member_of'];
887             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
888             $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
889             $this->selectAdd("IF($tn_pd.id IS NULL, 0,  $tn_pd.id )  as is_member");
890                 
891                 
892             if (!empty($q['query']['project_member_filter'])) {
893                 $this->having('is_member !=0');
894             
895             }
896             
897         }
898         
899         if(!empty($q['query']['name'])){
900             $this->whereAdd("
901                 {$this->tableName()}.name LIKE '%{$this->escape($q['query']['name'])}%'
902             ");
903         }
904          if(!empty($q['query']['name_starts'])){
905             $this->whereAdd("
906                 {$this->tableName()}.name LIKE '{$this->escape($q['query']['name_starts'])}%'
907             ");
908         }
909         
910         if (!empty($q['query']['search'])) {
911             
912             // use our magic search builder...
913             
914              require_once 'Text/SearchParser.php';
915             $x = new Text_SearchParser($q['query']['search']);
916             
917             $props = array(
918                     "$tn_p.name",
919                     "$tn_p.email",
920                     "$tn_p.role",
921                     "$tn_p.phone",
922                     "$tn_p.remarks",
923                     "join_company_id_id.name"
924             );
925             $tbcols = $this->table();
926             foreach(array('firstname','lastname') as $k) {
927                 if (isset($tbcols[$k])) {
928                     $props[] = "{$tn_p}.{$k}";
929                 }
930             }
931             
932             
933             
934             
935             $str =  $x->toSQL(array(
936                 'default' => $props,
937                 'map' => array(
938                     'company' => 'join_company_id_id.name',
939                     //'country' => 'Clipping.country',
940                     //  'media' => 'Clipping.media_name',
941                 ),
942                 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
943
944             ));
945             
946             
947             $this->whereAdd($str); /*
948                         $tn_p.name LIKE '%$s%'  OR
949                         $tn_p.email LIKE '%$s%'  OR
950                         $tn_p.role LIKE '%$s%'  OR
951                         $tn_p.phone LIKE '%$s%' OR
952                         $tn_p.remarks LIKE '%$s%' 
953                         
954                     ");*/
955         }
956         
957         // project directory rules -- this may distrupt things.
958         $p = DB_DataObject::factory('ProjectDirectory');
959         // if project directories are set up, then we can apply project query rules..
960         if ($p->count()) {
961             $p->autoJoin();
962             $pids = $p->projects($au);
963             if (isset($q['query']['project_id'])) {   
964                 $pid = (int)$q['query']['project_id'];
965                 if (!in_array($pid, $pids)) {
966                     $roo->jerr("Project not in users valid projects");
967                 }
968                 $pids = array($pid);
969             }
970             // project roles..
971             //if (empty($q['_anyrole'])) {  // should be project_directry_role
972             //    $p->whereAdd("{$p->tableName()}.role != ''");
973             // }
974             if (!empty($q['query']['role'])) {  // should be project_directry_role
975                 $role = $this->escape($q['query']['role']); 
976                
977                 $p->whereAdd("{$p->tableName()}.role LIKE '%{$role}%'");
978                  
979             }
980             
981             if (!$roo->hasPerm('Core.Projects_All', 'S')) {
982                 $peps = $p->people($pids);
983                 $this->whereAddIn("{$tn}.id", $peps, 'int');
984             }
985         }    
986         
987         // fixme - this needs a more generic fix - it was from the mtrack_person code...
988         if (isset($q['query']['ticket_id'])) {  
989             // find out what state the ticket is in.
990             $t = DB_DataObject::Factory('mtrack_ticket');
991             $t->autoJoin();
992             $t->get($q['query']['ticket_id']);
993             
994             if (!$this->checkPerm('S', $au)) {
995                 $roo->jerr("permssion denied to query state of ticket");
996             }
997             
998             $p = DB_DataObject::factory('ProjectDirectory');
999             $pids = array($t->project_id);
1000            
1001             $peps = $p->people($pids);
1002             
1003             $this->whereAddIn($this->tableName().'.id', $peps, 'int');
1004             
1005             //$this->whereAdd('join_prole != ''");
1006             
1007         }
1008         
1009         /*
1010          * Seems we never expose oath_key, so...
1011          */
1012         $this->selectAdd("
1013             CASE WHEN core_person.oath_key != '' THEN
1014                 TRUE
1015             ELSE
1016                 FALSE
1017             END AS has_oath_key
1018         ");
1019         
1020     }
1021     
1022     function setFromRoo($ar, $roo)
1023     {
1024         $this->setFrom($ar);
1025         
1026         if(!empty($ar['_enable_oath_key'])){
1027             $this->generateOathKey();
1028         }
1029         
1030         if (!empty($ar['passwd1'])) {
1031             $this->setPassword($ar['passwd1']);
1032         }
1033         
1034         if (    $this->id &&
1035                 ($this->email == $roo->old->email)&&
1036                 ($this->company_id == $roo->old->company_id)
1037             ) {
1038             return true;
1039         }
1040         if (empty($this->email)) {
1041             return true;
1042         }
1043         // this only applies to our owner company..
1044         $c = $this->company();
1045         if (empty($c->comptype_name) || $c->comptype_name != 'OWNER') {
1046             return true;
1047         }
1048         
1049         
1050         $xx = DB_Dataobject::factory($this->tableName());
1051         $xx->setFrom(array(
1052             'email' => $this->email,
1053            // 'company_id' => $x->company_id
1054         ));
1055         
1056         if ($xx->count()) {
1057             return "Duplicate Email found";
1058         }
1059         
1060         return true;
1061     }
1062     /**
1063      *
1064      * before Delete - delete significant dependancies..
1065      * this is called after checkPerm..
1066      */
1067     
1068     function beforeDelete($dependants_array, $roo)
1069     {
1070         
1071         $e = DB_DataObject::Factory('Events');
1072         $e->whereAdd('person_id = ' . $this->id);
1073         $e->delete(true);
1074         
1075         // anything else?  
1076         
1077     }
1078     
1079     
1080     /***
1081      * Check if the a user has access to modify this item.
1082      * @param String $lvl Level (eg. Core.Projects)
1083      * @param Pman_Core_DataObjects_Person $au The authenticated user.
1084      * @param boolean $changes alllow changes???
1085      *
1086      * @return false if no access..
1087      */
1088     function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
1089     {
1090          
1091        // do we have an empty system..
1092         if ($au && $au->id == -1) {
1093             return true;
1094         }
1095         // if not authenticated... do not allow in???
1096         if (!$au ) {
1097             return false;
1098         }
1099         
1100         // determine if it's staff!!!
1101         $owncomp = DB_DataObject::Factory('core_company');
1102         $owncomp->get('comptype', 'OWNER');
1103         $isStaff = ($au->company_id ==  $owncomp->id);
1104        
1105        
1106         if (!$isStaff) {
1107             
1108             // - can not change company!!!
1109             if ($changes && 
1110                 isset($changes['company_id']) && 
1111                 $changes['company_id'] != $au->company_id) {
1112                 return false;
1113             }
1114             // can only set new emails..
1115             if ($changes && 
1116                     !empty($this->email) && 
1117                     isset($changes['email']) && 
1118                     $changes['email'] != $this->email) {
1119                 return false;
1120             }
1121             
1122             
1123             // mtrack had the idea that all 'S' should be allowed.. - but filtered later..
1124             // ???? do we want this?
1125             
1126             // edit self... - what about other staff members...
1127             
1128             //return $this->company_id == $au->company_id;
1129         }
1130         
1131          
1132         // yes, only owner company can mess with this...
1133         
1134         
1135         
1136     
1137         switch ($lvl) {
1138             // extra case change passwod?
1139             case 'P': //??? password
1140                 // standard perms -- for editing + if the user is dowing them selves..
1141                 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
1142                 return $ret || $au->id == $this->id;
1143             
1144             default:                
1145                 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
1146         
1147         }
1148         return false;
1149     }
1150     
1151     function beforeInsert($req, $roo)
1152     {
1153         $p = DB_DataObject::factory('core_person');
1154         if ($roo->authUser->id > -1 ||  $p->count() > 1) {
1155             return;
1156         }
1157         $c = DB_DAtaObject::Factory('core_company');
1158         $tc =$c->count();
1159         if (!$tc || $tc> 1) {
1160             $roo->jerr("can not create initial user as multiple companies already exist");
1161         }
1162         $c->find(true);
1163         $this->company_id = $c->id;
1164         
1165     }
1166     
1167     function onInsert($req, $roo)
1168     {
1169          
1170         $p = DB_DataObject::factory('core_person');
1171         if ($roo->authUser->id < 0 && $p->count() == 1) {
1172             // this seems a bit risky...
1173             
1174             $g = DB_DataObject::factory('core_group');
1175             $g->initGroups();
1176             
1177             $g->type = 0;
1178             $g->get('name', 'Administrators');
1179             
1180             $p = DB_DataObject::factory('core_group_member');
1181             $p->group_id = $g->id;
1182             $p->user_id = $this->id;     
1183             if (!$p->count()) {
1184                 $p->insert();
1185                 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
1186             }
1187             $this->login();
1188         }
1189         if (!empty($req['project_id_addto'])) {
1190             $pd = DB_DataObject::factory('ProjectDirectory');
1191             $pd->project_id = $req['project_id_addto'];
1192             $pd->person_id = $this->id; 
1193             $pd->ispm =0;
1194             $pd->office_id = $this->office_id;
1195             $pd->company_id = $this->company_id;
1196             $pd->insert();
1197         }
1198         
1199     }
1200     
1201     function importFromArray($roo, $persons, $opts)
1202     {
1203         if (empty($opts['prefix'])) {
1204             $roo->jerr("opts[prefix] is empty - you can not just create passwords based on the user names");
1205         }
1206         
1207         if (!is_array($persons) || empty($persons)) {
1208             $roo->jerr("error in the person data. - empty on not valid");
1209         }
1210         DB_DataObject::factory('core_group')->initGroups();
1211         
1212         foreach($persons as $person){
1213             $p = DB_DataObject::factory('core_person');
1214             if($p->get('name', $person['name'])){
1215                 continue;
1216             }
1217             $p->setFrom($person);
1218             
1219             $companies = DB_DataObject::factory('core_company');
1220             if(!$companies->get('comptype', 'OWNER')){
1221                 $roo->jerr("Missing OWNER companies!");
1222             }
1223             $p->company_id = $companies->pid();
1224             // strip the 'spaces etc.. make lowercase..
1225             $name = strtolower(str_replace(' ', '', $person['name']));
1226             $p->setPassword("{$opts['prefix']}{$name}");
1227             $p->insert();
1228             // set up groups
1229             // if $person->groups is set.. then
1230             // add this person to that group eg. groups : [ 'Administrator' ] 
1231             if(!empty($person['groups'])){
1232                 $groups = DB_DataObject::factory('core_group');
1233                 if(!$groups->get('name', $person['groups'])){
1234                     $roo->jerr("Missing groups : {$person['groups']}");
1235                 }
1236                 $gm = DB_DataObject::factory('core_group_member');
1237                 $gm->change($p, $groups, true);
1238             }
1239             
1240             $p->onInsert(array(), $roo);
1241         }
1242     }
1243     
1244     // this is for the To: "{getEmailName()}" <email@address>
1245     // not good for Dear XXXX, - use {person.firstname} for that.
1246     function getEmailName()
1247     {
1248         $name = array();
1249         
1250         if(!empty($this->honor)){
1251             array_push($name, $this->honor);
1252         }
1253         
1254         if(!empty($this->name)){
1255             array_push($name, $this->name);
1256             
1257             return implode(' ', $name);
1258         }
1259         
1260         if(!empty($this->firstname) || !empty($this->lastname)){
1261             array_push($name, $this->firstname);
1262             array_push($name, $this->lastname);
1263             
1264             $name = array_filter($name);
1265             
1266             return implode(' ', $name);
1267         }
1268         
1269         return $this->email;
1270     }
1271     
1272     function sesPrefix()
1273     {
1274         $ff= HTML_FlexyFramework::get();
1275         
1276         $appname = empty($ff->appNameShort) ? $ff->project : $ff->project . '-' . $ff->appNameShort;
1277         
1278         $dname = method_exists($this, 'getDatabaseConnection') ? $this->getDatabaseConnection()->dsn['database'] : $this->databaseNickname();
1279         
1280         $sesPrefix = $appname.'-' .get_class($this) .'-' . $dname;
1281
1282         return $sesPrefix;
1283     }
1284     
1285     function loginPublic()
1286     {
1287         $this->isAuth(); // force session start..
1288          
1289         $db = $this->getDatabaseConnection();
1290         
1291         $ff = HTML_FlexyFramework::get();
1292         
1293         if(empty($ff->Pman) || empty($ff->Pman['login_public'])){
1294             return false;
1295         }
1296         
1297         $sesPrefix = $ff->Pman['login_public'] . '-' .get_class($this) .'-'.$db->dsn['database'] ;
1298         
1299         $p = DB_DAtaObject::Factory($this->tableName());
1300         $p->get($this->pid());
1301         
1302         $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$p->toArray());
1303         
1304         return true;
1305     }
1306     
1307     function toRooSingleArray($au, $q)
1308     {
1309         $ret = $this->toArray();
1310         
1311         $core_person = DB_DataObject::factory('core_person');
1312         $core_person->selectAdd('core_person.oath_key AS oath_key');
1313         $core_person->get($this->id);
1314         
1315         $ret['has_oath_key'] = (empty($core_person->oath_key)) ? 0 : 1;
1316         
1317         return $ret;
1318         
1319     }
1320     
1321     function beforeUpdate($old, $q, $roo)
1322     {
1323         if(!empty($q['_generate_oath_key'])){
1324             $o = clone($this);
1325             $this->generateOathKey();
1326             $this->update($o);
1327             $roo->jok('OK');
1328         }
1329         
1330         if(!empty($q['_to_qr_code'])){
1331             $qrcode = $this->generateQRCode();
1332             
1333             if(empty($qrcode)){
1334                 $roo->jerr('Fail to generate QR Code');
1335             }
1336             
1337             $roo->jdata($qrcode);
1338         }
1339     }
1340     
1341     function generateOathKey()
1342     {
1343         $hex = bin2hex(openssl_random_pseudo_bytes(10));
1344         
1345         require 'Base32.php';
1346         
1347         $base32 = new Base32();
1348         
1349         $this->oath_key = $base32->base32_encode($hex);
1350         
1351         return $this->oath_key;
1352         
1353     }
1354     
1355     function generateQRCode()
1356     {
1357         if(empty($this->oath_key)){
1358             return false;
1359         }
1360         
1361         $issuer = (empty($this->name)) ? rawurlencode('ROOJS') : rawurlencode($this->name);
1362         
1363         $uri = "otpauth://totp/{$issuer}:{$this->email}?secret={$this->oath_key}&issuer={$issuer}&algorithm=SHA1&digits=6&period=30";
1364         
1365         require_once 'Image/QRCode.php';
1366         
1367         $qrcode = new Image_QRCode();
1368         
1369         $image = $qrcode->makeCode($uri, array(
1370             'output_type' => 'return'
1371         ));
1372         
1373         ob_start();
1374         imagepng($image);
1375         $base64 = base64_encode(ob_get_contents());
1376         ob_end_clean();
1377         
1378         return "data:image/png;base64,{$base64}";
1379     }
1380     
1381  }