DataObjects/Core_person_signup.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     
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             // force a logout - without a check on the isAuth - as this is called from there..
241             $db = $this->getDatabaseConnection();
242             $sesPrefix = $ff->appNameShort .'-'.get_class($this) .'-'.$db->dsn['database'] ;
243             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
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         $db = $this->getDatabaseConnection();
257         // we combine db + project names,
258         // otherwise if projects use different 'auth' objects
259         // then we get unserialize issues.
260         $ff= HTML_FlexyFramework::get();
261         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
262         
263         
264         @session_start();
265          
266         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
267             // in session...
268             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
269             
270             $u = DB_DataObject::factory('Person');
271             if ($u->get($a->id)) { //&& strlen($u->passwd)) {
272               
273                 return $u->verifyAuth();
274                 
275    
276                 return true;
277             }
278             
279             unset($_SESSION[__CLASS__][$sesPrefix .'-auth']);
280             
281         }
282         // local auth - 
283         $default_admin = false;
284         if (!empty($ff->Pman['local_autoauth']) && 
285             ($ff->Pman['local_autoauth'] === true) &&
286             (!empty($_SERVER['SERVER_ADDR'])) &&
287             ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
288             ($_SERVER['REMOTE_ADDR'] == '127.0.0.1')
289         ) {
290             $group = DB_DataObject::factory('Groups');
291             $group->get('name', 'Administrators');
292             
293             $member = DB_DataObject::factory('group_members');
294             $member->autoJoin();
295             $member->group_id = $group->id;
296             $member->whereAdd("
297                 join_user_id_id.id IS NOT NULL
298             ");
299             if($member->find(true)){
300                 $default_admin = DB_DataObject::factory('Person');
301                 if(!$default_admin->get($member->user_id)){
302                     $default_admin = false;
303                 }
304             }
305         }
306         
307         //var_dump($ff->Pman['local_autoauth']);         var_dump($_SERVER); exit;
308         $u = DB_DataObject::factory('Person');
309         $ff = HTML_FlexyFramework::get();
310         if (!empty($ff->Pman['local_autoauth']) && 
311             (!empty($_SERVER['SERVER_ADDR'])) &&
312             ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
313             ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') &&
314             ($default_admin ||  $u->get('email', $ff->Pman['local_autoauth']))
315         ) {
316             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($default_admin ? $default_admin : $u);
317             return true;
318         }
319            
320         // http basic auth..
321         $u = DB_DataObject::factory('Person');
322
323         if (!empty($_SERVER['PHP_AUTH_USER']) 
324             &&
325             !empty($_SERVER['PHP_AUTH_PW'])
326             &&
327             $u->get('email', $_SERVER['PHP_AUTH_USER'])
328             &&
329             $u->checkPassword($_SERVER['PHP_AUTH_PW'])
330            ) {
331             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
332             return true; 
333         }
334         //var_dump(session_id());
335         //var_dump($_SESSION[__CLASS__]);
336         
337         //if (!empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
338         //    return false;
339         //}
340         //die("got this far?");
341         // not in session or not matched...
342         $u = DB_DataObject::factory('Person');
343         $u->whereAdd(' LENGTH(passwd) > 0');
344         $n = $u->count();
345         $_SESSION[__CLASS__][$sesPrefix .'-empty']  = $n;
346         $error =  PEAR::getStaticProperty('DB_DataObject','lastError');
347         if ($error) {
348             die($error->toString()); // not really a good thing to do...
349         }
350         if (!$n){ // authenticated as there are no users in the system...
351             return true;
352         }
353         
354         return false;
355         
356     }
357     function getAuthUser()
358     {
359         if (!$this->isAuth()) {
360             return false;
361         }
362         $db = $this->getDatabaseConnection();
363         
364         $ff= HTML_FlexyFramework::get();
365         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
366
367         
368         
369         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
370             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
371             
372             $u = DB_DataObject::factory('Person');
373             if ($u->get($a->id)) { /// && strlen($u->passwd)) {
374                 return clone($u);
375             }
376             unset($_SESSION[__CLASS__][$sesPrefix .'-auth']);
377         }
378         
379         if (empty(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
380             $u = DB_DataObject::factory('Person');
381             $u->whereAdd(' LENGTH(passwd) > 0');
382             $_SESSION[__CLASS__][$sesPrefix .'-empty']  = $u->count();
383         }
384                 
385              
386         if (isset(   $_SESSION[__CLASS__][$sesPrefix .'-empty'] ) && $_SESSION[__CLASS__][$sesPrefix .'-empty']  < 1) {
387             
388             // fake person - open system..
389             //$ce = DB_DataObject::factory('core_enum');
390             //$ce->initEnums();
391             
392             
393             $u = DB_DataObject::factory('Person');
394             $u->id = -1;
395             
396             // if a company has been created fill that in in company_id_id
397             $c = DB_DAtaObject::factory('Companies')->lookupOwner();
398             if ($c) {
399                 $u->company_id_id = $c->pid();
400                 $u->company_id = $c->pid();
401             }
402             
403             return $u;
404             
405         }
406         return false;
407     }     
408     function login()
409     {
410         $this->isAuth(); // force session start..
411         if (!$this->verifyAuth()) {
412             return false;
413         }
414         $db = $this->getDatabaseConnection();
415         
416         
417         // open up iptables at login..
418         $dbname = $this->database();
419         touch( '/tmp/run_pman_admin_iptables-'.$dbname);
420          
421         // refresh admin group if we are logged in as one..
422         //DB_DataObject::debugLevel(1);
423         $g = DB_DataObject::factory('Groups');
424         $g->type = 0;
425         $g->get('name', 'Administrators');
426         $gm = DB_DataObject::Factory('group_members');
427         if (in_array($g->id,$gm->listGroupMembership($this))) {
428             // refresh admin groups.
429             $gr = DB_DataObject::Factory('group_rights');
430             $gr->applyDefs($g, 0);
431         }
432         $ff= HTML_FlexyFramework::get();
433         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
434
435
436         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
437         
438     }
439     function logout()
440     {
441         $this->isAuth(); // force session start..
442         $db = $this->getDatabaseConnection();
443         $ff= HTML_FlexyFramework::get();
444         $sesPrefix = $ff->appNameShort .'-' .get_class($this) .'-'.$db->dsn['database'] ;
445
446         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
447        
448         
449        
450         
451     }    
452     function genPassKey ($t) 
453     {
454         return md5($this->email . $t. $this->passwd);
455     }
456     function simpleAuthKey($m = 0)
457     {
458         $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
459         
460         return md5(implode(',' ,  array($month, $this->email , $this->passwd, $this->id)));
461     } 
462     function checkPassword($val)
463     {
464         
465         if (substr($this->passwd,0,1) == '$') {
466             return crypt($val,$this->passwd) == $this->passwd ;
467         }
468         // old style md5 passwords...- cant be used with courier....
469         return md5($val) == $this->passwd;
470     }
471     function setPassword($value) 
472     {
473         $salt='';
474         while(strlen($salt)<9) {
475             $salt.=chr(rand(64,126));
476             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
477         }
478         $this->passwd = crypt($value, '$1$'. $salt. '$');
479        
480        
481     }      
482     
483     function generatePassword() // genearte a password (add set 'rawPasswd' to it's value)
484     {
485         require_once 'Text/Password.php';
486         $this->rawPasswd = strtr(ucfirst(Text_Password::create(5)).ucfirst(Text_Password::create(5)), array(
487         "a"=>"4", "e"=>"3",  "i"=>"1",  "o"=>"0", "s"=>"5",  "t"=>"7"));
488         $this->setPassword($this->rawPasswd);
489         return $this->rawPasswd;
490     }
491     
492     function company()
493     {
494         $x = DB_DataObject::factory('Companies');
495         $x->autoJoin();
496         $x->get($this->company_id);
497         return $x;
498     }
499     function loadCompany()
500     {
501         $this->company = $this->company();
502     }
503     
504     function active()
505     { 
506         return $this->active;
507     }
508     function authUserName($n) // set username prior to acheck user exists query.
509     {
510         
511         $this->whereAdd('LENGTH(passwd) > 1'); 
512         $this->email = $n;
513     }
514     function lang()
515     {
516         if (!func_num_args()) {
517             return $this->lang;
518         }
519         $val = array_shift(func_get_args());
520         if ($val == $this->lang) {
521             return;
522         }
523         $uu = clone($this);
524         $this->lang = $val;
525         $this->update($uu);
526         return $this->lang;
527     }
528             
529     
530     function authUserArray()
531     {
532         
533         $aur = $this->toArray();
534         
535         if ($this->id < 1) {
536             return $aur;
537         }
538         
539         
540         //DB_DataObject::debugLevel(1);
541         $c = DB_Dataobject::factory('Companies');
542         $im = DB_Dataobject::factory('Images');
543         $c->joinAdd($im, 'LEFT');
544         $c->selectAdd();
545         $c->selectAs($c, 'company_id_%s');
546         $c->selectAs($im, 'company_id_logo_id_%s');
547         $c->id = $this->company_id;
548         $c->limit(1);
549         $c->find(true);
550         
551         $aur = array_merge( $c->toArray(),$aur);
552         
553         if (empty($c->company_id_logo_id_id))  {
554                  
555             $im = DB_Dataobject::factory('Images');
556             $im->ontable = 'Companies';
557             $im->onid = $c->id;
558             $im->imgtype = 'LOGO';
559             $im->limit(1);
560             $im->selectAdd();
561             $im->selectAs($im,  'company_id_logo_id_%s');
562             if ($im->find(true)) {
563                     
564                 foreach($im->toArray() as $k=>$v) {
565                     $aur[$k] = $v;
566                 }
567             }
568         }
569       
570         // perms + groups.
571         $aur['perms']  = $this->getPerms();
572         $g = DB_DataObject::Factory('group_members');
573         $aur['groups']  = $g->listGroupMembership($this, 'name');
574         
575         $aur['passwd'] = '';
576         $aur['dailykey'] = '';
577         
578         
579         
580         return $aur;
581     }
582     
583     //   ----------PERMS------  ----------------
584     function getPerms() 
585     {
586          //DB_DataObject::debugLevel(1);
587         // find out all the groups they are a member of.. + Default..
588         
589         // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
590         
591         $g = DB_DataObject::Factory('group_rights');
592         if (!$g->count()) {
593             $g->genDefault();
594         }
595         
596         if ($this->id < 0) {
597             return $g->adminRights(); // system is not set up - so they get full rights.
598         }
599         //DB_DataObject::debugLevel(1);
600         $g = DB_DataObject::Factory('group_members');
601         $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
602         if (!$g->count()) {
603             // add the current user to the admin group..
604             $g = DB_DataObject::Factory('Groups');
605             if ($g->get('name', 'Administrators')) {
606                 $gm = DB_DataObject::Factory('group_members');
607                 $gm->group_id = $g->id;
608                 $gm->user_id = $this->id;
609                 $gm->insert();
610             }
611             
612         }
613         
614         // ------ STANDARD PERMISSION HANDLING.
615         $isOwner = $this->company()->comptype == 'OWNER';
616         $g = DB_DataObject::Factory('group_members');
617         $grps = $g->listGroupMembership($this);
618        //var_dump($grps);
619         $isAdmin = $g->inAdmin;
620         //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
621         // the load all the perms for those groups, and add them all together..
622         // then load all those 
623         $g = DB_DataObject::Factory('group_rights');
624         $ret =  $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
625         //echo '<PRE>';print_r($ret);
626         return $ret;
627          
628         
629     }
630     /**
631      *Basic group fetching - probably needs to filter by type eventually.
632      *
633      *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
634      */
635     
636     function groups($what=false)
637     {
638         $g = DB_DataObject::Factory('group_members');
639         $grps = $g->listGroupMembership($this);
640         $g = DB_DataObject::Factory('Groups');
641         $g->whereAddIn('id', $grps, 'int');
642         return $g->fetchAll($what);
643         
644     }
645     
646     
647     
648     function hasPerm($name, $lvl) 
649     {
650         static $pcache = array();
651         
652         if (!isset($pcache[$this->id])) {
653             $pcache[$this->id] = $this->getPerms();
654         }
655        // echo "<PRE>";print_r($pcache[$au->id]);
656        // var_dump($pcache[$au->id]);
657         if (empty($pcache[$this->id][$name])) {
658             return false;
659         }
660         
661         return strpos($pcache[$this->id][$name], $lvl) > -1;
662         
663     }    
664     
665     //  ------------ROO HOOKS------------------------------------
666     function applyFilters($q, $au, $roo)
667     {
668         //DB_DataObject::DebugLevel(1);
669         
670         if (!empty($q['query']['is_owner'])) {
671             $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
672         }
673         
674         if (!empty($q['query']['person_not_internal'])) {
675             $this->whereAdd(" join_company_id_id.isOwner = 0 ");
676         }
677         
678         if (!empty($q['query']['person_internal_only_all'])) {
679             
680             
681             // must be internal and not current user (need for distribution list)
682             // user has a projectdirectory entry and role is not blank.
683             //DB_DataObject::DebugLevel(1);
684             $pd = DB_DataObject::factory('ProjectDirectory');
685             $pd->whereAdd("role != ''");
686             $pd->selectAdd();
687             $pd->selectAdd('distinct(person_id) as person_id');
688             $roled = $pd->fetchAll('person_id');
689             $rs = $roled  ? "  OR
690                     {$this->tableName()}.id IN (".implode(',', $roled) . ") 
691                     " : '';
692             $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
693             
694         }
695         // -- for distribution
696         if (!empty($q['query']['person_internal_only'])) {
697             // must be internal and not current user (need for distribution list)
698             $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
699             
700             //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
701             //    ".id  != ".$au->id);
702             $this->whereAdd("Person.id != {$au->id}");
703         } 
704         
705         if (!empty($q['query']['comptype_or_company_id'])) {
706            // DB_DataObject::debugLevel(1);
707             $bits = explode(',', $q['query']['comptype_or_company_id']);
708             $id = (int) array_pop($bits);
709             $ct = $this->escape($bits[0]);
710             
711             $this->whereAdd(" join_company_id_id.comptype = '$ct' OR Person.company_id = $id");
712             
713         }
714         
715         
716         // staff list..
717         if (!empty($q['query']['person_inactive'])) {
718            // DB_Dataobject::debugLevel(1);
719             $this->active = 1;
720         }
721         $tn_p = $this->tableName();
722         $tn_gm = DB_DataObject::Factory('group_members')->tableName();
723         $tn_g = DB_DataObject::Factory('Groups')->tableName();
724
725         ///---------------- Group views --------
726         if (!empty($q['query']['in_group'])) {
727             // DB_DataObject::debugLevel(1);
728             $ing = (int) $q['query']['in_group'];
729             if ($q['query']['in_group'] == -1) {
730              
731                 // list all staff who are not in a group.
732                 $this->whereAdd("Person.id NOT IN (
733                     SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
734                         $tn_g ON $tn_g.id = $tn_gm.group_id
735                         WHERE $tn_g.type = ".$q['query']['type']."
736                     )");
737                 
738                 
739             } else {
740                 
741                 $this->whereAdd("$tn_p.id IN (
742                     SELECT distinct(user_id) FROM $tn_gm
743                         WHERE group_id = $ing
744                     )");
745                }
746             
747         }
748         
749         // #2307 Search Country!!
750         if (!empty($q['query']['in_country'])) {
751             // DB_DataObject::debugLevel(1);
752             $inc = $q['query']['in_country'];
753             $this->whereAdd("$tn_p.countries LIKE '%{$inc}%'");
754         }
755         
756         if (!empty($q['query']['not_in_directory'])) { 
757             // it's a Person list..
758             // DB_DATaobjecT::debugLevel(1);
759             
760             // specific to project directory which is single comp. login
761             //
762             $owncomp = DB_DataObject::Factory('Companies');
763             $owncomp->get('comptype', 'OWNER');
764             if ($q['company_id'] == $owncomp->id) {
765                 $this->active =1;
766             }
767             
768             
769
770             if ( $q['query']['not_in_directory'] > -1) {
771                 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
772                 // can list current - so that it does not break!!!
773                 $this->whereAdd("$tn_p.id NOT IN 
774                     ( SELECT distinct person_id FROM $tn_pd WHERE
775                         project_id = " . $q['query']['not_in_directory'] . " AND 
776                         company_id = " . $this->company_id . ')');
777             }
778         }
779            
780         if (!empty($q['query']['role'])) { 
781             // it's a Person list..
782             // DB_DATaobjecT::debugLevel(1);
783             
784             // specific to project directory which is single comp. login
785             //
786             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
787                 // can list current - so that it does not break!!!
788             $this->whereAdd("$tn_p.id IN 
789                     ( SELECT distinct person_id FROM $tn_pd WHERE
790                         role = '". $this->escape($q['query']['role']) ."'
791             )");
792         
793         }
794         
795         
796         if (!empty($q['query']['project_member_of'])) {
797                // this is also a flag to return if they are a member..
798             //DB_DataObject::debugLevel(1);
799             $do = DB_DataObject::factory('ProjectDirectory');
800             $do->project_id = $q['query']['project_member_of'];
801             $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
802             $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
803             $this->selectAdd("IF($tn_pd.id IS NULL, 0,  $tn_pd.id )  as is_member");
804                 
805                 
806             if (!empty($q['query']['project_member_filter'])) {
807                 $this->having('is_member !=0');
808             
809             }
810             
811         }
812         
813         if(!empty($q['query']['name'])){
814             $this->whereAdd("
815                 Person.name LIKE '%{$this->escape($q['query']['name'])}%'
816             ");
817         }
818         
819         if (!empty($q['query']['search'])) {
820             
821             // use our magic search builder...
822             
823              require_once 'Text/SearchParser.php';
824             $x = new Text_SearchParser($q['query']['search']);
825             
826             $props = array(
827                     "$tn_p.name",
828                     "$tn_p.email",
829                     "$tn_p.role",
830                     "$tn_p.phone",
831                     "$tn_p.remarks",
832                     "join_company_id_id.name"
833             );
834             
835             $str =  $x->toSQL(array(
836                 'default' => $props,
837                 'map' => array(
838                     'company' => 'join_company_id_id.name',
839                     //'country' => 'Clipping.country',
840                     //  'media' => 'Clipping.media_name',
841                 ),
842                 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
843
844             ));
845             
846             
847             $this->whereAdd($str); /*
848                         $tn_p.name LIKE '%$s%'  OR
849                         $tn_p.email LIKE '%$s%'  OR
850                         $tn_p.role LIKE '%$s%'  OR
851                         $tn_p.phone LIKE '%$s%' OR
852                         $tn_p.remarks LIKE '%$s%' 
853                         
854                     ");*/
855         }
856         
857     }
858     function setFromRoo($ar, $roo)
859     {
860         $this->setFrom($ar);
861         if (!empty($ar['passwd1'])) {
862             $this->setPassword($ar['passwd1']);
863         }
864         
865         
866         if (    $this->id &&
867                 ($this->email == $roo->old->email)&&
868                 ($this->company_id == $roo->old->company_id)
869             ) {
870             return true;
871         }
872         if (empty($this->email)) {
873             return true;
874         }
875         $xx = DB_Dataobject::factory('Person');
876         $xx->setFrom(array(
877             'email' => $this->email,
878            // 'company_id' => $x->company_id
879         ));
880         
881         if ($xx->count()) {
882             return "Duplicate Email found";
883         }
884         return true;
885     }
886     /**
887      *
888      * before Delete - delete significant dependancies..
889      * this is called after checkPerm..
890      */
891     
892     function beforeDelete()
893     {
894         
895         $e = DB_DataObject::Factory('Events');
896         $e->whereAdd('person_id = ' . $this->id);
897         $e->delete(true);
898         
899         // anything else?  
900         
901     }
902     
903     
904     /***
905      * Check if the a user has access to modify this item.
906      * @param String $lvl Level (eg. Core.Projects)
907      * @param Pman_Core_DataObjects_Person $au The authenticated user.
908      * @param boolean $changes alllow changes???
909      *
910      * @return false if no access..
911      */
912     function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
913     {
914          
915        // do we have an empty system..
916         if ($au && $au->id == -1) {
917             return true;
918         }
919         
920         // determine if it's staff!!!
921          
922         if ($au->company()->comptype != 'OWNER') {
923             
924             // - can not change company!!!
925             if ($changes && 
926                 isset($changes['company_id']) && 
927                 $changes['company_id'] != $au->company_id) {
928                 return false;
929             }
930             // can only set new emails..
931             if ($changes && 
932                     !empty($this->email) && 
933                     isset($changes['email']) && 
934                     $changes['email'] != $this->email) {
935                 return false;
936             }
937             
938             // edit self... - what about other staff members...
939             
940             return $this->company_id == $au->company_id;
941         }
942          
943          
944         // yes, only owner company can mess with this...
945         $owncomp = DB_DataObject::Factory('Companies');
946         $owncomp->get('comptype', 'OWNER');
947         
948         $isStaff = ($this->company_id ==  $owncomp->id);
949         
950     
951         switch ($lvl) {
952             // extra case change passwod?
953             case 'P': //??? password
954                 // standard perms -- for editing + if the user is dowing them selves..
955                 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
956                 return $ret || $au->id == $this->id;
957             
958             default:                
959                 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
960         
961         }
962         return false;
963     }
964     
965     function onInsert($req, $roo)
966     {
967          
968         $p = DB_DataObject::factory('person');
969         if ($roo->authUser->id < 0 && $p->count() == 1) {
970             // this seems a bit risky...
971             
972             $g = DB_DataObject::factory('Groups');
973             $g->initGroups();
974             
975             $g->type = 0;
976             $g->get('name', 'Administrators');
977             
978             $p = DB_DataObject::factory('group_members');
979             $p->group_id = $g->id;
980             $p->user_id = $this->id;     
981             if (!$p->count()) {
982                 $p->insert();
983                 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
984             }
985             $this->login();
986         }
987         if (!empty($req['project_id_addto'])) {
988             $pd = DB_DataObject::factory('ProjectDirectory');
989             $pd->project_id = $req['project_id_addto'];
990             $pd->person_id = $this->id; 
991             $pd->ispm =0;
992             $pd->office_id = $this->office_id;
993             $pd->company_id = $this->company_id;
994             $pd->insert();
995         }
996         
997     }
998     
999     function importFromArray($roo, $persons, $opts)
1000     {
1001         if (empty($opts['prefix'])) {
1002             $roo->jerr("opts[prefix] is empty - you can not just create passwords based on the user names");
1003         }
1004         
1005         if (!is_array($persons) || empty($persons)) {
1006             $roo->jerr("error in the person data. - empty on not valid");
1007         }
1008         DB_DataObject::factory('groups')->initGroups();
1009         
1010         foreach($persons as $person){
1011             $p = DB_DataObject::factory('person');
1012             if($p->get('name', $person['name'])){
1013                 continue;
1014             }
1015             $p->setFrom($person);
1016             
1017             $companies = DB_DataObject::factory('companies');
1018             if(!$companies->get('comptype', 'OWNER')){
1019                 $roo->jerr("Missing OWNER companies!");
1020             }
1021             $p->company_id = $companies->pid();
1022             // strip the 'spaces etc.. make lowercase..
1023             $name = strtolower(str_replace(' ', '', $person['name']));
1024             $p->setPassword("{$opts['prefix']}{$name}");
1025             $p->insert();
1026             // set up groups
1027             // if $person->groups is set.. then
1028             // add this person to that group eg. groups : [ 'Administrator' ] 
1029             if(!empty($person['groups'])){
1030                 $groups = DB_DataObject::factory('groups');
1031                 if(!$groups->get('name', $person['groups'])){
1032                     $roo->jerr("Missing groups : {$person['groups']}");
1033                 }
1034                 $gm = DB_DataObject::factory('group_members');
1035                 $gm->change($p, $groups, true);
1036             }
1037             
1038             $p->onInsert(array(), $roo);
1039         }
1040     }
1041     
1042     function getEmailName()
1043     {
1044         $name = array();
1045         
1046         if(!empty($this->honor)){
1047             array_push($name, $this->honor);
1048         }
1049         
1050         if(!empty($this->name)){
1051             array_push($name, $this->name);
1052             
1053             return implode(' ', $name);
1054         }
1055         
1056         if(!empty($this->firstname) || !empty($this->lastname)){
1057             array_push($name, $this->firstname);
1058             array_push($name, $this->lastname);
1059             
1060             $name = array_filter($name);
1061             
1062             return $name;
1063         }
1064         
1065         return $this->email;
1066     }
1067     
1068  }