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