3 * Table Definition for Person
5 require_once 'DB/DataObject.php';
7 class Pman_Core_DataObjects_Person extends DB_DataObject
10 /* the code below is auto generated do not remove the above tag */
12 public $__table = 'Person'; // table name
13 public $id; // int(11) not_null primary_key auto_increment
14 public $email; // string(128) not_null
16 public $company_id; // int(11)
17 public $office_id; // int(11)
18 public $name; // string(128) not_null
19 public $firstname; // string(128) not_null
20 public $lastname; // string(128) not_null
21 public $phone; // string(32) not_null
22 public $fax; // string(32) not_null
24 public $role; // string(32) not_null
25 public $remarks; // blob(65535) not_null blob
26 public $passwd; // string(64) not_null
27 public $owner_id; // int(11) not_null
28 public $lang; // string(8)
29 public $no_reset_sent; // int(11)
30 public $action_type; // string(32)
31 public $project_id; // int(11)
34 public $active; // int(11) not_null
35 public $deleted_by; // int(11) not_null
36 public $deleted_dt; // datetime(19) binary
39 public $name_facebook; // VARCHAR(128) NULL;
40 public $url_blog; // VARCHAR(256) NULL ;
41 public $url_twitter; // VARCHAR(256) NULL ;
42 public $url_linkedin; // VARCHAR(256) NULL ;
44 public $phone_mobile; // varchar(32) NOT NULL DEFAULT '';
45 public $phone_direct; // varchar(32) NOT NULL DEFAULT '';
47 /* the code above is auto generated do not remove the tag below */
52 $p = DB_DataObject::Factory('Person');
53 $p->get($this->owner_id);
62 * FIXME !!!! -- USE Pman_Core_Mailer !!!!!
68 function buildMail($templateFile, $args)
71 $args = (array) $args;
72 $content = clone($this);
74 foreach((array)$args as $k=>$v) {
78 $ff = HTML_FlexyFramework::get();
81 //?? is this really the place for this???
84 empty($args['no_auth']) &&
85 !in_array($templateFile, array(
86 // templates that can be sent without authentication.
92 $content->authUser = $this->getAuthUser();
93 if (!$content->authUser) {
94 return PEAR::raiseError("Not authenticated");
98 // should handle x-forwarded...
100 $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
101 $_SERVER["HTTP_HOST"] :
102 (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
104 /* use the regex compiler, as it doesnt parse <tags */
107 'compiler' => 'Flexy',
109 'filters' => array('SimpleTags','Mail'),
115 if (!empty($args['templateDir'])) {
116 $tops['templateDir'] = $args['templateDir'];
121 require_once 'HTML/Template/Flexy.php';
122 $template = new HTML_Template_Flexy( $tops );
123 $template->compile("mail/$templateFile.txt");
125 /* use variables from this object to ouput data. */
126 $mailtext = $template->bufferedOutputObject($content);
129 // if a html file with the same name exists, use that as the body
130 // I've no idea where this code went, it was here before..
131 if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
132 $tops['nonHTML'] = false;
133 $template = new HTML_Template_Flexy( $tops );
134 $template->compile("mail/$templateFile.html");
135 $htmlbody = $template->bufferedOutputObject($content);
141 //echo "<PRE>";print_R($mailtext);
142 //print_R($mailtext);exit;
143 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
144 require_once 'Mail/mimeDecode.php';
145 require_once 'Mail.php';
147 $decoder = new Mail_mimeDecode($mailtext);
148 $parts = $decoder->getSendArray();
150 if (PEAR::isError($parts)) {
152 //echo "PROBLEM: {$parts->message}";
155 list($recipents,$headers,$body) = $parts;
156 $recipents = array($this->email);
157 if (!empty($content->bcc) && is_array($content->bcc)) {
158 $recipents =array_merge($recipents, $content->bcc);
160 $headers['Date'] = date('r');
162 if ($htmlbody !== false) {
163 require_once 'Mail/mime.php';
164 $mime = new Mail_mime(array('eol' => "\n"));
165 $mime->setTXTBody($body);
166 $mime->setHTMLBody($htmlbody);
167 // I think there might be code in mediaoutreach toEmail somewhere
168 // h embeds images here..
169 $body = $mime->get();
170 $headers = $mime->headers($headers);
177 'recipients' => $recipents,
178 'headers' => $headers,
188 * - user must be authenticate or args[no_auth] = true
189 * or template = password_[reset|welcome]
192 function sendTemplate($templateFile, $args)
195 $ar = $this->buildMail($templateFile, $args);
198 //print_r($recipents);exit;
199 $mailOptions = PEAR::getStaticProperty('Mail','options');
200 $mail = Mail::factory("SMTP",$mailOptions);
202 if (PEAR::isError($mail)) {
205 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
206 $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
207 error_reporting($oe);
216 function getEmailFrom()
218 return '"' . addslashes($this->name) . '" <' . $this->email . '>';
220 function toEventString()
222 return empty($this->name) ? $this->email : $this->name;
224 function verifyAuth()
226 $ff= HTML_FlexyFramework::get();
227 if (!empty($ff->Pman['auth_comptype']) && $ff->Pman['auth_comptype'] != $this->company()->comptype) {
228 $ff->page->jerr("Login not permited to outside companies");
235 // ---------------- authentication / passwords and keys stuff ----------------
238 $db = $this->getDatabaseConnection();
239 // we combine db + project names,
240 // otherwise if projects use different 'auth' objects
241 // then we get unserialize issues.
242 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
246 if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
248 $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
250 $u = DB_DataObject::factory('Person');
251 if ($u->get($a->id)) { //&& strlen($u->passwd)) {
257 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
261 $u = DB_DataObject::factory('Person');
262 $ff = HTML_FlexyFramework::get();
263 if (!empty($ff->Pman['local_autoauth']) &&
264 (!empty($_SERVER['SERVER_ADDR'])) &&
265 ($_SERVER['SERVER_ADDR'] == '127.0.0.1') &&
266 ($_SERVER['REMOTE_ADDR'] == '127.0.0.1') &&
267 $u->get('email', $ff->Pman['local_autoauth'])
269 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
274 $u = DB_DataObject::factory('Person');
276 if (!empty($_SERVER['PHP_AUTH_USER'])
278 !empty($_SERVER['PHP_AUTH_PW'])
280 $u->get('email', $_SERVER['PHP_AUTH_USER'])
282 $u->checkPassword($_SERVER['PHP_AUTH_PW'])
284 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($u);
288 if (!empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
292 // not in session or not matched...
293 $u = DB_DataObject::factory('Person');
294 $u->whereAdd(' LENGTH(passwd) > 0');
296 $_SESSION[__CLASS__][$sesPrefix .'-empty'] = $n;
297 $error = PEAR::getStaticProperty('DB_DataObject','lastError');
299 die($error->toString()); // not really a good thing to do...
301 if (!$n){ // authenticated as there are no users in the system...
308 function getAuthUser()
310 if (!$this->isAuth()) {
313 $db = $this->getDatabaseConnection();
314 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
318 if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
319 $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
321 $u = DB_DataObject::factory('Person');
322 if ($u->get($a->id)) { /// && strlen($u->passwd)) {
328 if (empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
329 $u = DB_DataObject::factory('Person');
330 $u->whereAdd(' LENGTH(passwd) > 0');
331 $_SESSION[__CLASS__][$sesPrefix .'-empty'] = $u->count();
335 if (empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
337 // fake person - open system..
338 //$ce = DB_DataObject::factory('core_enum');
342 $u = DB_DataObject::factory('Person');
351 $this->isAuth(); // force session start..
353 $db = $this->getDatabaseConnection();
356 // open up iptables at login..
357 $dbname = $this->database();
358 touch( '/tmp/run_pman_admin_iptables-'.$dbname);
360 // refresh admin group if we are logged in as one..
361 //DB_DataObject::debugLevel(1);
362 $g = DB_DataObject::factory('Groups');
364 $g->get('name', 'Administrators');
365 $gm = DB_DataObject::Factory('group_members');
366 if (in_array($g->id,$gm->listGroupMembership($this))) {
367 // refresh admin groups.
368 $gr = DB_DataObject::Factory('group_rights');
369 $gr->applyDefs($g, 0);
372 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
373 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
378 $this->isAuth(); // force session start..
379 $db = $this->getDatabaseConnection();
380 $sesPrefix = get_class($this) .'-'.$db->dsn['database'] ;
381 $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
384 function genPassKey ($t)
386 return md5($this->email . $t. $this->passwd);
388 function simpleAuthKey($m = 0)
390 $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
392 return md5(implode(',' , array($month, $this->email , $this->passwd, $this->id)));
394 function checkPassword($val)
397 if (substr($this->passwd,0,1) == '$') {
398 return crypt($val,$this->passwd) == $this->passwd ;
400 // old style md5 passwords...- cant be used with courier....
401 return md5($val) == $this->passwd;
403 function setPassword($value)
406 while(strlen($salt)<9) {
407 $salt.=chr(rand(64,126));
408 //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
410 $this->passwd = crypt($value, '$1$'. $salt. '$');
415 function generatePassword() // genearte a password (add set 'rawPasswd' to it's value)
417 require_once 'Text/Password.php';
418 $this->rawPasswd = strtr(ucfirst(Text_Password::create(5)).ucfirst(Text_Password::create(5)), array(
419 "a"=>"4", "e"=>"3", "i"=>"1", "o"=>"0", "s"=>"5", "t"=>"7"));
420 $this->setPassword($this->rawPasswd);
421 return $this->rawPasswd;
426 $x = DB_DataObject::factory('Companies');
428 $x->get($this->company_id);
431 function loadCompany()
433 $this->company = $this->company();
438 return $this->active;
440 function authUserName($n) // set username prior to acheck user exists query.
443 $this->whereAdd('LENGTH(passwd) > 1');
448 if ($val == $this->lang) {
458 function authUserArray()
461 $aur = $this->toArray();
468 //DB_DataObject::debugLevel(1);
469 $c = DB_Dataobject::factory('Companies');
470 $im = DB_Dataobject::factory('Images');
471 $c->joinAdd($im, 'LEFT');
473 $c->selectAs($c, 'company_id_%s');
474 $c->selectAs($im, 'company_id_logo_id_%s');
475 $c->id = $this->company_id;
479 $aur = array_merge( $c->toArray(),$aur);
481 if (empty($c->company_id_logo_id_id)) {
483 $im = DB_Dataobject::factory('Images');
484 $im->ontable = 'Companies';
486 $im->imgtype = 'LOGO';
489 $im->selectAs($im, 'company_id_logo_id_%s');
490 if ($im->find(true)) {
492 foreach($im->toArray() as $k=>$v) {
499 $aur['perms'] = $this->getPerms();
500 $g = DB_DataObject::Factory('group_members');
501 $aur['groups'] = $g->listGroupMembership($this, 'name');
504 $aur['dailykey'] = '';
511 // ----------PERMS------ ----------------
514 //DB_DataObject::debugLevel(1);
515 // find out all the groups they are a member of.. + Default..
517 // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
519 $g = DB_DataObject::Factory('group_rights');
525 return $g->adminRights(); // system is not set up - so they get full rights.
527 //DB_DataObject::debugLevel(1);
528 $g = DB_DataObject::Factory('group_members');
529 $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
531 // add the current user to the admin group..
532 $g = DB_DataObject::Factory('Groups');
533 if ($g->get('name', 'Administrators')) {
534 $gm = DB_DataObject::Factory('group_members');
535 $gm->group_id = $g->id;
536 $gm->user_id = $this->id;
542 // ------ STANDARD PERMISSION HANDLING.
543 $isOwner = $this->company()->comptype == 'OWNER';
544 $g = DB_DataObject::Factory('group_members');
545 $grps = $g->listGroupMembership($this);
547 $isAdmin = $g->inAdmin;
548 //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
549 // the load all the perms for those groups, and add them all together..
550 // then load all those
551 $g = DB_DataObject::Factory('group_rights');
552 $ret = $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
553 //echo '<PRE>';print_r($ret);
559 *Basic group fetching - probably needs to filter by type eventually.
561 *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
564 function groups($what=false)
566 $g = DB_DataObject::Factory('group_members');
567 $grps = $g->listGroupMembership($this);
568 $g = DB_DataObject::Factory('Groups');
569 $g->whereAddIn('id', $grps, 'int');
570 return $g->fetchAll($what);
576 function hasPerm($name, $lvl)
578 static $pcache = array();
580 if (!isset($pcache[$this->id])) {
581 $pcache[$this->id] = $this->getPerms();
583 // echo "<PRE>";print_r($pcache[$au->id]);
584 // var_dump($pcache[$au->id]);
585 if (empty($pcache[$this->id][$name])) {
589 return strpos($pcache[$this->id][$name], $lvl) > -1;
593 // ------------ROO HOOKS------------------------------------
594 function applyFilters($q, $au, $roo)
596 //DB_DataObject::DebugLevel(1);
597 if (!empty($q['query']['person_not_internal'])) {
598 $this->whereAdd(" join_company_id_id.isOwner = 0 ");
602 if (!empty($q['query']['person_internal_only_all'])) {
605 // must be internal and not current user (need for distribution list)
606 // user has a projectdirectory entry and role is not blank.
607 //DB_DataObject::DebugLevel(1);
608 $pd = DB_DataObject::factory('ProjectDirectory');
609 $pd->whereAdd("role != ''");
611 $pd->selectAdd('distinct(person_id) as person_id');
612 $roled = $pd->fetchAll('person_id');
614 {$this->tableName()}.id IN (".implode(',', $roled) . ")
616 $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
619 // -- for distribution
620 if (!empty($q['query']['person_internal_only'])) {
621 // must be internal and not current user (need for distribution list)
622 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
624 //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
625 // ".id != ".$au->id);
626 $this->whereAdd("Person.id != {$au->id}");
629 if (!empty($q['query']['comptype_or_company_id'])) {
630 // DB_DataObject::debugLevel(1);
631 $bits = explode(',', $q['query']['comptype_or_company_id']);
632 $id = (int) array_pop($bits);
633 $ct = $this->escape($bits[0]);
635 $this->whereAdd(" join_company_id_id.comptype = '$ct' OR Person.company_id = $id");
641 if (!empty($q['query']['person_inactive'])) {
642 // DB_Dataobject::debugLevel(1);
645 $tn_p = $this->tableName();
646 $tn_gm = DB_DataObject::Factory('group_members')->tableName();
647 $tn_g = DB_DataObject::Factory('Groups')->tableName();
649 ///---------------- Group views --------
650 if (!empty($q['query']['in_group'])) {
651 // DB_DataObject::debugLevel(1);
652 $ing = (int) $q['query']['in_group'];
653 if ($q['query']['in_group'] == -1) {
655 // list all staff who are not in a group.
656 $this->whereAdd("Person.id NOT IN (
657 SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
658 $tn_g ON $tn_g.id = $tn_gm.group_id
659 WHERE $tn_g.type = ".$q['query']['type']."
665 $this->whereAdd("$tn_p.id IN (
666 SELECT distinct(user_id) FROM $tn_gm
667 WHERE group_id = $ing
673 if (!empty($q['query']['not_in_directory'])) {
674 // it's a Person list..
675 // DB_DATaobjecT::debugLevel(1);
677 // specific to project directory which is single comp. login
679 $owncomp = DB_DataObject::Factory('Companies');
680 $owncomp->get('comptype', 'OWNER');
681 if ($q['company_id'] == $owncomp->id) {
687 if ( $q['query']['not_in_directory'] > -1) {
688 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
689 // can list current - so that it does not break!!!
690 $this->whereAdd("$tn_p.id NOT IN
691 ( SELECT distinct person_id FROM $tn_pd WHERE
692 project_id = " . $q['query']['not_in_directory'] . " AND
693 company_id = " . $this->company_id . ')');
697 if (!empty($q['query']['role'])) {
698 // it's a Person list..
699 // DB_DATaobjecT::debugLevel(1);
701 // specific to project directory which is single comp. login
703 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
704 // can list current - so that it does not break!!!
705 $this->whereAdd("$tn_p.id IN
706 ( SELECT distinct person_id FROM $tn_pd WHERE
707 role = '". $this->escape($q['query']['role']) ."'
713 if (!empty($q['query']['project_member_of'])) {
714 // this is also a flag to return if they are a member..
715 //DB_DataObject::debugLevel(1);
716 $do = DB_DataObject::factory('ProjectDirectory');
717 $do->project_id = $q['query']['project_member_of'];
718 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
719 $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
720 $this->selectAdd("IF($tn_pd.id IS NULL, 0, $tn_pd.id ) as is_member");
723 if (!empty($q['query']['project_member_filter'])) {
724 $this->having('is_member !=0');
730 if (!empty($q['query']['search'])) {
731 $s = $this->escape($q['query']['search']);
733 $tn_p.name LIKE '%$s%' OR
734 $tn_p.email LIKE '%$s%' OR
735 $tn_p.role LIKE '%$s%' OR
736 $tn_p.phone LIKE '%$s%' OR
737 $tn_p.remarks LIKE '%$s%'
744 function setFromRoo($ar, $roo)
747 if (!empty($ar['passwd1'])) {
748 $this->setPassword($ar['passwd1']);
753 ($this->email == $roo->old->email)&&
754 ($this->company_id == $roo->old->company_id)
758 if (empty($this->email)) {
761 $xx = DB_Dataobject::factory('Person');
763 'email' => $this->email,
764 // 'company_id' => $x->company_id
768 return "Duplicate Email found";
774 * before Delete - delete significant dependancies..
775 * this is called after checkPerm..
778 function beforeDelete()
781 $e = DB_DataObject::Factory('Events');
782 $e->whereAdd('person_id = ' . $this->id);
791 * Check if the a user has access to modify this item.
792 * @param String $lvl Level (eg. Core.Projects)
793 * @param Pman_Core_DataObjects_Person $au The authenticated user.
794 * @param boolean $changes alllow changes???
796 * @return false if no access..
798 function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
801 // do we have an empty system..
802 if ($au && $au->id == -1) {
806 // determine if it's staff!!!
808 if ($au->company()->comptype != 'OWNER') {
810 // - can not change company!!!
812 isset($changes['company_id']) &&
813 $changes['company_id'] != $au->company_id) {
816 // can only set new emails..
818 !empty($this->email) &&
819 isset($changes['email']) &&
820 $changes['email'] != $this->email) {
824 // edit self... - what about other staff members...
826 return $this->company_id == $au->company_id;
830 // yes, only owner company can mess with this...
831 $owncomp = DB_DataObject::Factory('Companies');
832 $owncomp->get('comptype', 'OWNER');
834 $isStaff = ($this->company_id == $owncomp->id);
838 // extra case change passwod?
839 case 'P': //??? password
840 // standard perms -- for editing + if the user is dowing them selves..
841 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
842 return $ret || $au->id == $this->id;
845 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
850 function onInsert($req, $roo)
853 $p = DB_DataObject::factory('person');
854 if ($roo->authUser->id < 0 && $p->count() == 1) {
855 // this seems a bit risky...
857 $g = DB_DataObject::factory('Groups');
861 $g->get('name', 'Administrators');
863 $p = DB_DataObject::factory('group_members');
864 $p->group_id = $g->id;
865 $p->user_id = $this->id;
868 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
872 if (!empty($req['project_id_addto'])) {
873 $pd = DB_DataObject::factory('ProjectDirectory');
874 $pd->project_id = $req['project_id_addto'];
875 $pd->person_id = $this->id;
877 $pd->office_id = $this->office_id;
878 $pd->company_id = $this->company_id;