3 * Table Definition for Person
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
8 class Pman_Core_DataObjects_Core_person extends DB_DataObject
11 /* the code below is auto generated do not remove the above tag */
13 public $__table = 'core_person'; // table name
14 public $id; // int(11) not_null primary_key auto_increment
15 public $email; // string(128) not_null
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
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)
36 public $active; // int(11) not_null
37 public $deleted_by; // int(11) not_null
38 public $deleted_dt; // datetime(19) binary
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 ;
47 public $phone_mobile; // varchar(32) NOT NULL DEFAULT '';
48 public $phone_direct; // varchar(32) NOT NULL DEFAULT '';
49 public $countries; // VARCHAR(128) NULL;
51 /* the code above is auto generated do not remove the tag below */
54 static $authUser = false;
59 // this might be a Person in some old code?
60 $p = DB_DataObject::Factory('core_person');
61 $p->get($this->owner_id);
70 * FIXME !!!! -- USE Pman_Core_Mailer !!!!!
76 function buildMail($templateFile, $args)
79 $args = (array) $args;
80 $content = clone($this);
82 foreach((array)$args as $k=>$v) {
86 $ff = HTML_FlexyFramework::get();
89 //?? is this really the place for this???
92 empty($args['no_auth']) &&
93 !in_array($templateFile, array(
94 // templates that can be sent without authentication.
100 $content->authUser = $this->getAuthUser();
101 if (!$content->authUser) {
102 return PEAR::raiseError("Not authenticated");
106 // should handle x-forwarded...
108 $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
109 $_SERVER["HTTP_HOST"] :
110 (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
112 /* use the regex compiler, as it doesnt parse <tags */
115 'compiler' => 'Flexy',
117 'filters' => array('SimpleTags','Mail'),
123 if (!empty($args['templateDir'])) {
124 $tops['templateDir'] = $args['templateDir'];
129 require_once 'HTML/Template/Flexy.php';
130 $template = new HTML_Template_Flexy( $tops );
131 $template->compile("mail/$templateFile.txt");
133 /* use variables from this object to ouput data. */
134 $mailtext = $template->bufferedOutputObject($content);
137 // if a html file with the same name exists, use that as the body
138 // I've no idea where this code went, it was here before..
139 if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
140 $tops['nonHTML'] = false;
141 $template = new HTML_Template_Flexy( $tops );
142 $template->compile("mail/$templateFile.html");
143 $htmlbody = $template->bufferedOutputObject($content);
149 //echo "<PRE>";print_R($mailtext);
150 //print_R($mailtext);exit;
151 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
152 require_once 'Mail/mimeDecode.php';
153 require_once 'Mail.php';
155 $decoder = new Mail_mimeDecode($mailtext);
156 $parts = $decoder->getSendArray();
158 if (is_a($parts,'PEAR_Error')) {
160 //echo "PROBLEM: {$parts->message}";
163 list($recipents,$headers,$body) = $parts;
164 $recipents = array($this->email);
165 if (!empty($content->bcc) && is_array($content->bcc)) {
166 $recipents =array_merge($recipents, $content->bcc);
168 $headers['Date'] = date('r');
170 if ($htmlbody !== false) {
171 require_once 'Mail/mime.php';
172 $mime = new Mail_mime(array('eol' => "\n"));
173 $mime->setTXTBody($body);
174 $mime->setHTMLBody($htmlbody);
175 // I think there might be code in mediaoutreach toEmail somewhere
176 // h embeds images here..
177 $body = $mime->get();
178 $headers = $mime->headers($headers);
182 'recipients' => $recipents,
183 'headers' => $headers,
191 * - user must be authenticate or args[no_auth] = true
192 * or template = password_[reset|welcome]
195 function sendTemplate($templateFile, $args)
197 $ar = $this->buildMail($templateFile, $args);
199 //print_r($recipents);exit;
200 $mailOptions = PEAR::getStaticProperty('Mail','options');
201 $mail = Mail::factory("SMTP",$mailOptions);
203 if (PEAR::isError($mail)) {
206 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
207 $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
208 error_reporting($oe);
216 function getEmailFrom()
218 if (empty($this->name)) {
222 return '"' . addslashes($this->name) . '" <' . $this->email . '>';
225 function toEventString()
227 return empty($this->name) ? $this->email : $this->name;
230 function verifyAuth()
232 $ff= HTML_FlexyFramework::get();
233 if (!empty($ff->Pman['auth_comptype']) &&
234 (!$this->company_id || ($ff->Pman['auth_comptype'] != $this->company()->comptype))
237 $sesPrefix = $this->sesPrefix();
239 self::$authUser = false;
240 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
244 //$ff->page->jerr("Login not permited to outside companies");
251 // ---------------- authentication / passwords and keys stuff ----------------
254 // do not start a session if we are using http auth...
255 if (empty($_SERVER['PHP_AUTH_USER']) && php_sapi_name() != "cli") {
259 $ff= HTML_FlexyFramework::get();
261 $sesPrefix = $this->sesPrefix();
263 if (self::$authUser) {
264 return self::$authUser;
268 if (!empty($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
270 $a = unserialize($_SESSION[get_class($this)][$sesPrefix .'-auth']);
271 $u = DB_DataObject::factory($this->tableName());
273 if ($a->id && $u->get($a->id)) { //&& strlen($u->passwd)) {
274 if ($u->verifyAuth()) {
275 self::$authUser = $u;
279 unset($_SESSION[get_class($this)][$sesPrefix .'-auth']);
280 unset($_SESSION[get_class($this)][$sesPrefix .'-timeout']);
281 setcookie('Pman.timeout', -1, time() + (30*60), '/');
286 $u = DB_DataObject::factory($this->tableName());
288 if (!empty($_SERVER['PHP_AUTH_USER'])
290 !empty($_SERVER['PHP_AUTH_PW'])
292 $u->get('email', $_SERVER['PHP_AUTH_USER'])
294 $u->checkPassword($_SERVER['PHP_AUTH_PW'])
296 // logged in via http auth
297 // http auth will not need session...
298 //$_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize($u);
299 self::$authUser = $u;
303 if (!$this->canInitializeSystem()) {
304 // die("can not init");
309 $auto_auth_allow = false;
310 if (!empty($ff->Pman['local_autoauth']) && $ff->Pman['local_autoauth'] === true) {
311 $auto_auth_allow = true;
313 if ( !empty($ff->Pman['local_autoauth'])
315 !empty($_SERVER['SERVER_ADDR']) &&
316 !empty($_SERVER['REMOTE_ADDR']) &&
319 $_SERVER['SERVER_ADDR'] == '127.0.0.1' &&
320 $_SERVER['REMOTE_ADDR'] == '127.0.0.1'
324 $_SERVER['SERVER_ADDR'] == '::1' &&
325 $_SERVER['REMOTE_ADDR'] == '::1'
330 $auto_auth_allow = true;
334 if (empty($_SERVER['PATH_INFO']) || $_SERVER['PATH_INFO'] == '/Login') {
335 $auto_auth_allow = false;
337 //var_dump($auto_auth_allow);
339 $default_admin = false;
340 if ($auto_auth_allow) {
341 $group = DB_DataObject::factory('core_group');
342 $group->get('name', 'Administrators');
344 $member = DB_DataObject::factory('core_group_member');
346 $member->group_id = $group->id;
348 join_user_id_id.id IS NOT NULL
350 if($member->find(true)){
351 $default_admin = DB_DataObject::factory($this->tableName());
352 $default_admin->autoJoin();
353 if(!$default_admin->get($member->user_id)){
354 $default_admin = false;
359 //var_dump($ff->Pman['local_autoauth']); var_dump($_SERVER); exit;
360 $u = DB_DataObject::factory($this->tableName());
362 $ff = HTML_FlexyFramework::get();
364 if ($auto_auth_allow &&
365 ($default_admin || $u->get('email', $ff->Pman['local_autoauth']))
368 $user = $default_admin ? $default_admin->toArray() : $u->toArray();
370 // if we request other URLS.. then we get auto logged in..
371 self::$authUser = $default_admin ? $default_admin : $u;;
372 //$_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object) $user);
376 //var_dump(session_id());
377 //var_dump($_SESSION[__CLASS__]);
379 //if (!empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
382 //die("got this far?");
383 // not in session or not matched...
384 $u = DB_DataObject::factory($this->tableName());
385 $u->whereAdd(' LENGTH(passwd) > 0');
387 if (empty($_SESSION[get_class($this)]) || !is_array($_SESSION[get_class($this)])) {
388 $_SESSION[get_class($this)] = array();
390 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $n;
391 if (class_exists('PEAR')) {
392 $error = PEAR::getStaticProperty('DB_DataObject','lastError');
394 die($error->toString()); // not really a good thing to do...
397 if (!$n){ // authenticated as there are no users in the system...
404 function canInitializeSystem()
407 return !strcasecmp(get_class($this) , __CLASS__);
410 function getAuthUser()
412 if (!$this->isAuth()) {
416 $ff= HTML_FlexyFramework::get();
418 $sesPrefix = $this->sesPrefix();
420 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
422 if (self::$authUser) {
424 if (isset($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
425 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
426 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
428 // not really sure why it's cloned..
429 return clone (self::$authUser);
436 if (!$this->canInitializeSystem()) {
442 if (empty( $_SESSION[get_class($this)][$sesPrefix .'-empty'] )) {
443 $u = DB_DataObject::factory($this->tableName());
444 $u->whereAdd(' LENGTH(passwd) > 0');
445 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $u->count();
450 isset( $_SESSION[get_class($this)][$sesPrefix .'-empty'] ) &&
451 $_SESSION[get_class($this)][$sesPrefix .'-empty'] < 1
454 // fake person - open system..
455 //$ce = DB_DataObject::factory('core_enum');
459 $u = DB_DataObject::factory($this->tableName());
462 // if a company has been created fill that in in company_id_id
463 $c = DB_DAtaObject::factory('core_company')->lookupOwner();
465 $u->company_id_id = $c->pid();
466 $u->company_id = $c->pid();
476 $this->isAuth(); // force session start..
477 if (!$this->verifyAuth()) { // check for company valid..
481 // open up iptables at login..
482 $dbname = $this->databaseNickname();
483 touch( '/tmp/run_pman_admin_iptables-'.$dbname);
485 // refresh admin group if we are logged in as one..
486 //DB_DataObject::debugLevel(1);
487 $g = DB_DataObject::factory('core_group');
489 $g->get('name', 'Administrators');
490 $gm = DB_DataObject::Factory('core_group_member');
491 if (in_array($g->id,$gm->listGroupMembership($this))) {
492 // refresh admin groups.
493 $gr = DB_DataObject::Factory('core_group_right');
494 $gr->applyDefs($g, 0);
497 $sesPrefix = $this->sesPrefix();
499 // we should not store the whole data in the session - otherwise it get's huge.
500 $p = DB_DAtaObject::Factory($this->tableName());
501 $p->get($this->pid());
505 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
506 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
508 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
509 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$d);
511 $pp = DB_DAtaObject::Factory($this->tableName());
512 $pp->get($this->pid());
515 self::$authUser = $pp;
516 // ensure it's written so that ajax calls can fetch it..
523 $this->isAuth(); // force session start..
525 $sesPrefix = $this->sesPrefix();
526 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = -1;
527 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
528 self::$authUser = false;
531 function genPassKey ($t)
533 return md5($this->email . $t. $this->passwd);
535 function simpleAuthKey($m = 0)
537 $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
539 return md5(implode(',' , array($month, $this->email , $this->passwd, $this->id)));
542 * When we generate autologin urls:
543 * eg. /Somesite/Test/12
545 * /Somesite/Test/12/{datetime}/{sha256(url + expires_datetime + password)}
547 * eg. genAutoLoginURL($sub, $expires)
549 function genAutoLoginURL($url, $expires = false)
551 $expires = $expires === false ? strtotime("NOW + 1 WEEK") : $expires;
552 //echo serialize(array($url, $expires, $this->email, $this->passwd));
553 //echo hash('sha256', serialize(array($url, $expires, $this->email, $this->passwd)));
555 return $url.'/'.$this->id .'/'.$expires.'/'.
558 array($url, $expires, $this->email,$this->passwd)
564 function validateAutoLogin($called)
566 $bits = explode("/",$called);
567 if (count($bits) < 4) {
568 return false; // unrelated.
570 $hash = array_pop($bits);
571 $time = array_pop($bits);
573 $id = array_pop($bits);
574 if (!is_numeric($time) || !is_numeric($id)) {
575 return false; // wrong format.
577 $u = DB_DataObject::Factory($this->tableName());
579 $url = implode("/", $bits);
580 if ($time < time()) {
583 //echo serialize(array('/'.$url, $time, $u->email, $u->passwd));
584 //echo hash('sha256', serialize(array('/'.$url, $time, $u->email, $u->passwd)));
585 if ($hash == hash('sha256', serialize(array('/'.$url, $time*1, $u->email, $u->passwd)))) {
593 function checkTwoFactorAuthentication($val)
597 // also used in login
598 require_once 'System.php';
602 empty($this->oath_key)
607 $oathtool = System::which('oathtool');
613 $cmd = "{$oathtool} --totp --base32 " . escapeshellarg($this->oath_key);
615 $password = exec($cmd);
617 return ($password == $val) ? true : false;
620 function checkPassword($val)
622 if (substr($this->passwd,0,1) == '$') {
623 if (function_exists('pasword_verify')) {
624 return password_verify($val, $this->passwd);
626 return crypt($val,$this->passwd) == $this->passwd ;
628 // old style md5 passwords...- cant be used with courier....
629 return md5($val) == $this->passwd;
632 function setPassword($value)
634 if (function_exists('pasword_hash')) {
635 return password_hash($value);
639 while(strlen($salt)<9) {
640 $salt.=chr(rand(64,126));
641 //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
643 $this->passwd = crypt($value, '$1$'. $salt. '$');
648 function generatePassword($length = 5) // genearte a password (add set 'rawPasswd' to it's value)
650 require_once 'Text/Password.php';
651 $this->rawPasswd = strtr(ucfirst(Text_Password::create($length)).ucfirst(Text_Password::create($length)), array(
652 "a"=>"4", "e"=>"3", "i"=>"1", "o"=>"0", "s"=>"5", "t"=>"7"));
653 $this->setPassword($this->rawPasswd);
654 return $this->rawPasswd;
659 if (empty($this->company_id)) {
662 $x = DB_DataObject::factory('core_company');
664 $x->get($this->company_id);
667 function loadCompany()
669 $this->company = $this->company();
674 return $this->active;
676 function authUserName($n) // set username prior to acheck user exists query.
679 $this->whereAdd('LENGTH(passwd) > 1');
684 if (!func_num_args()) {
687 $ar = func_get_args();
688 $val = array_shift($ar);
689 if ($val == $this->lang) {
699 function authUserArray()
701 $aur = $this->toArray();
707 //DB_DataObject::debugLevel(1);
708 $c = DB_Dataobject::factory('core_company');
709 $im = DB_Dataobject::factory('Images');
710 $c->joinAdd($im, 'LEFT');
712 $c->selectAs($c, 'company_id_%s');
713 $c->selectAs($im, 'company_id_logo_id_%s');
714 $c->id = $this->company_id;
718 $aur = array_merge( $c->toArray(),$aur);
720 if (empty($c->company_id_logo_id_id)) {
722 $im = DB_Dataobject::factory('Images');
723 $im->ontable = DB_DataObject::factory('core_company')->tableName();
725 $im->imgtype = 'LOGO';
728 $im->selectAs($im, 'company_id_logo_id_%s');
729 if ($im->find(true)) {
731 foreach($im->toArray() as $k=>$v) {
732 if (!preg_match('/^company_id_logo_id_/', $k)) {
741 $aur['perms'] = $this->getPerms();
742 $g = DB_DataObject::Factory('core_group_member');
743 $aur['groups'] = $g->listGroupMembership($this, 'name');
746 $aur['dailykey'] = '';
747 $aur['oath_key'] = '';
749 $aur['oath_key_enable'] = !empty($this->oath_key);
750 $aur['require_oath'] = 1;
752 $s = DB_DataObject::Factory('core_setting');
753 $oath_require = $s->lookup('core', 'two_factor_auth_required');
754 $aur['require_oath'] = $oath_require ? $oath_require->val : 0;
756 $aur['core_person_settings'] = array();
758 $core_person_settings = DB_DataObject::factory('core_person_settings');
759 $core_person_settings->setFrom(array(
760 'person_id' => $this->id
763 $aur['core_person_settings'] = $core_person_settings->fetchAll('scope', 'data');
768 // ----------PERMS------ ----------------
771 //DB_DataObject::debugLevel(1);
772 // find out all the groups they are a member of.. + Default..
774 // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
776 $g = DB_DataObject::Factory('core_group_right');
782 return $g->adminRights(); // system is not set up - so they get full rights.
784 //DB_DataObject::debugLevel(1);
785 $g = DB_DataObject::Factory('core_group_member');
786 $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
788 // add the current user to the admin group..
789 $g = DB_DataObject::Factory('core_group');
790 if ($g->get('name', 'Administrators')) {
791 $gm = DB_DataObject::Factory('core_group_member');
792 $gm->group_id = $g->id;
793 $gm->user_id = $this->id;
799 // ------ STANDARD PERMISSION HANDLING.
800 $isOwner = $this->company()->comptype == 'OWNER';
801 $g = DB_DataObject::Factory('core_group_member');
802 $grps = $g->listGroupMembership($this);
804 $isAdmin = $g->inAdmin; //??? what???
805 //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
806 // the load all the perms for those groups, and add them all together..
807 // then load all those
808 $g = DB_DataObject::Factory('core_group_right');
809 $ret = $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
810 //echo '<PRE>';print_r($ret);
816 *Basic group fetching - probably needs to filter by type eventually.
818 *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
821 function groups($what=false)
823 $g = DB_DataObject::Factory('core_group_member');
824 $grps = $g->listGroupMembership($this);
825 $g = DB_DataObject::Factory('core_group');
826 $g->whereAddIn('id', $grps, 'int');
827 return $g->fetchAll($what);
833 function hasPerm($name, $lvl)
835 static $pcache = array();
837 if (!isset($pcache[$this->id])) {
838 $pcache[$this->id] = $this->getPerms();
841 // echo "<PRE>";print_r($pcache[$au->id]);
842 // var_dump($pcache[$au->id]);
843 if (empty($pcache[$this->id][$name])) {
847 return strpos($pcache[$this->id][$name], $lvl) > -1;
851 // ------------ROO HOOKS------------------------------------
852 function applyFilters($q, $au, $roo)
854 //DB_DataObject::DebugLevel(1);
855 if(!empty($q['_to_qr_code'])){
856 $person = DB_DataObject::factory('Core_person');
857 $person->id = $q['id'];
859 if(!$person->find(true)) {
860 $roo->jerr('_invalid_person');
863 $hash = $this->generateOathKey();
865 $_SESSION[__CLASS__] =
866 isset($_SESSION[__CLASS__]) ?
867 $_SESSION[__CLASS__] : array();
868 $_SESSION[__CLASS__]['oath'] =
869 isset($_SESSION[__CLASS__]['oath']) ?
870 $_SESSION[__CLASS__]['oath'] : array();
872 $_SESSION[__CLASS__]['oath'][$person->id] = $hash;
874 $qrcode = $person->generateQRCode($hash);
877 $roo->jerr('Fail to generate QR Code');
883 'issuer' => $person->qrCodeIssuer()
887 if(!empty($q['two_factor_auth_code'])) {
888 $person = DB_DataObject::factory('core_person');
889 $person->get($q['id']);
891 $person->oath_key = $_SESSION[__CLASS__]['oath'][$person->id];
893 if($person->checkTwoFactorAuthentication($q['two_factor_auth_code'])) {
895 unset($_SESSION[__CLASS__]['oath'][$person->id]);
899 $roo->jerr('_invalid_auth_code');
902 if(!empty($q['oath_key_disable'])) {
903 $person = DB_DataObject::factory('core_person');
904 $person->get($q['id']);
908 $person->oath_key = '';
914 if (!empty($q['query']['is_owner'])) {
915 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
918 if (!empty($q['query']['person_not_internal'])) {
919 $this->whereAdd(" join_company_id_id.isOwner = 0 ");
922 if (!empty($q['query']['person_internal_only_all'])) {
925 // must be internal and not current user (need for distribution list)
926 // user has a projectdirectory entry and role is not blank.
927 //DB_DataObject::DebugLevel(1);
928 $pd = DB_DataObject::factory('ProjectDirectory');
929 $pd->whereAdd("role != ''");
931 $pd->selectAdd('distinct(person_id) as person_id');
932 $roled = $pd->fetchAll('person_id');
934 {$this->tableName()}.id IN (".implode(',', $roled) . ")
936 $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
939 // -- for distribution
940 if (!empty($q['query']['person_internal_only'])) {
941 // must be internal and not current user (need for distribution list)
942 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
944 //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
945 // ".id != ".$au->id);
946 $this->whereAdd("{$this->tableName()}.id != {$au->id}");
949 if (!empty($q['query']['comptype_or_company_id'])) {
950 // DB_DataObject::debugLevel(1);
951 $bits = explode(',', $q['query']['comptype_or_company_id']);
952 $id = (int) array_pop($bits);
953 $ct = $this->escape($bits[0]);
955 $this->whereAdd(" join_company_id_id.comptype = '$ct' OR {$this->tableName()}.company_id = $id");
961 if (!empty($q['query']['person_inactive'])) {
962 // DB_Dataobject::debugLevel(1);
965 $tn_p = $this->tableName();
966 $tn_gm = DB_DataObject::Factory('core_group_member')->tableName();
967 $tn_g = DB_DataObject::Factory('core_group')->tableName();
969 ///---------------- Group views --------
970 if (!empty($q['query']['in_group'])) {
971 // DB_DataObject::debugLevel(1);
972 $ing = (int) $q['query']['in_group'];
973 if ($q['query']['in_group'] == -1) {
975 // list all staff who are not in a group.
976 $this->whereAdd("{$this->tableName()}.id NOT IN (
977 SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
978 $tn_g ON $tn_g.id = $tn_gm.group_id)");
982 $this->whereAdd("$tn_p.id IN (
983 SELECT distinct(user_id) FROM $tn_gm
984 WHERE group_id = $ing
990 if(!empty($q['in_group_name'])){
992 $v = $this->escape($q['in_group_name']);
997 DISTINCT(user_id) FROM $tn_gm
1001 $tn_g.id = $tn_gm.group_id
1007 if(!empty($q['in_group_starts'])){
1009 $v = $this->escape($q['in_group_starts']);
1014 DISTINCT(user_id) FROM $tn_gm
1018 $tn_g.id = $tn_gm.group_id
1020 $tn_g.name LIKE '{$v}%'
1027 // #2307 Search Country!!
1028 if (!empty($q['query']['in_country'])) {
1029 // DB_DataObject::debugLevel(1);
1030 $inc = $q['query']['in_country'];
1031 $this->whereAdd("$tn_p.countries LIKE '%{$inc}%'");
1034 if (!empty($q['query']['not_in_directory'])) {
1035 // it's a Person list..
1036 // DB_DATaobjecT::debugLevel(1);
1038 // specific to project directory which is single comp. login
1040 $owncomp = DB_DataObject::Factory('core_company');
1041 $owncomp->get('comptype', 'OWNER');
1042 if ($q['company_id'] == $owncomp->id) {
1048 if ( $q['query']['not_in_directory'] > -1) {
1049 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1050 // can list current - so that it does not break!!!
1051 $this->whereAdd("$tn_p.id NOT IN
1052 ( SELECT distinct person_id FROM $tn_pd WHERE
1053 project_id = " . $q['query']['not_in_directory'] . " AND
1054 company_id = " . $this->company_id . ')');
1058 if (!empty($q['query']['role'])) {
1059 // it's a Person list..
1060 // DB_DATaobjecT::debugLevel(1);
1062 // specific to project directory which is single comp. login
1064 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1065 // can list current - so that it does not break!!!
1066 $this->whereAdd("$tn_p.id IN
1067 ( SELECT distinct person_id FROM $tn_pd WHERE
1068 role = '". $this->escape($q['query']['role']) ."'
1074 if (!empty($q['query']['project_member_of'])) {
1075 // this is also a flag to return if they are a member..
1076 //DB_DataObject::debugLevel(1);
1077 $do = DB_DataObject::factory('ProjectDirectory');
1078 $do->project_id = $q['query']['project_member_of'];
1079 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1080 $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
1081 $this->selectAdd("IF($tn_pd.id IS NULL, 0, $tn_pd.id ) as is_member");
1084 if (!empty($q['query']['project_member_filter'])) {
1085 $this->having('is_member !=0');
1091 if(!empty($q['query']['name'])){
1093 {$this->tableName()}.name LIKE '%{$this->escape($q['query']['name'])}%'
1097 if(!empty($q['query']['name_or_email'])){
1098 $v = $this->escape($q['query']['name_or_email']);
1100 {$this->tableName()}.name LIKE '%{$v}%'
1102 {$this->tableName()}.email LIKE '%{$v}%'
1105 if(!empty($q['query']['name_starts'])){
1107 {$this->tableName()}.name LIKE '{$this->escape($q['query']['name_starts'])}%'
1111 if (!empty($q['query']['search'])) {
1113 // use our magic search builder...
1115 require_once 'Text/SearchParser.php';
1116 $x = new Text_SearchParser($q['query']['search']);
1124 "join_company_id_id.name"
1126 $tbcols = $this->table();
1127 foreach(array('firstname','lastname') as $k) {
1128 if (isset($tbcols[$k])) {
1129 $props[] = "{$tn_p}.{$k}";
1136 $str = $x->toSQL(array(
1137 'default' => $props,
1139 'company' => 'join_company_id_id.name',
1140 //'country' => 'Clipping.country',
1141 // 'media' => 'Clipping.media_name',
1143 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
1148 $this->whereAdd($str); /*
1149 $tn_p.name LIKE '%$s%' OR
1150 $tn_p.email LIKE '%$s%' OR
1151 $tn_p.role LIKE '%$s%' OR
1152 $tn_p.phone LIKE '%$s%' OR
1153 $tn_p.remarks LIKE '%$s%'
1158 // project directory rules -- this may distrupt things.
1159 $p = DB_DataObject::factory('ProjectDirectory');
1160 // if project directories are set up, then we can apply project query rules..
1163 $pids = $p->projects($au);
1164 if (isset($q['query']['project_id'])) {
1165 $pid = (int)$q['query']['project_id'];
1166 if (!in_array($pid, $pids)) {
1167 $roo->jerr("Project not in users valid projects");
1169 $pids = array($pid);
1172 //if (empty($q['_anyrole'])) { // should be project_directry_role
1173 // $p->whereAdd("{$p->tableName()}.role != ''");
1175 if (!empty($q['query']['role'])) { // should be project_directry_role
1176 $role = $this->escape($q['query']['role']);
1178 $p->whereAdd("{$p->tableName()}.role LIKE '%{$role}%'");
1182 if (!$roo->hasPerm('Core.Projects_All', 'S')) {
1183 $peps = $p->people($pids);
1184 $this->whereAddIn("{$this->tableName()}.id", $peps, 'int');
1188 // fixme - this needs a more generic fix - it was from the mtrack_person code...
1189 if (isset($q['query']['ticket_id'])) {
1190 // find out what state the ticket is in.
1191 $t = DB_DataObject::Factory('mtrack_ticket');
1193 $t->get($q['query']['ticket_id']);
1195 if (!$this->checkPerm('S', $au)) {
1196 $roo->jerr("permssion denied to query state of ticket");
1199 $p = DB_DataObject::factory('ProjectDirectory');
1200 $pids = array($t->project_id);
1202 $peps = $p->people($pids);
1204 $this->whereAddIn($this->tableName().'.id', $peps, 'int');
1206 //$this->whereAdd('join_prole != ''");
1211 * Seems we never expose oath_key / passwd, so...
1214 if($this->tableName() == 'core_person'){
1215 $this->_extra_cols = array('length_passwd', 'length_oath_key');
1218 LENGTH({$this->tableName()}.passwd) AS length_passwd,
1219 LENGTH({$this->tableName()}.oath_key) AS length_oath_key
1222 if (isset($q['_with_group_membership'])) {
1223 $this->selectAddGroupMemberships();
1228 function selectAddGroupMemberships()
1234 GROUP_CONCAT( CASE WHEN core_group.display_name = '' THEN core_group.name ELSE core_group.display_name END separator '\n')
1240 core_group.id = core_group_member.group_id
1242 core_group_member.user_id = core_person.id
1244 core_group.display_name ASC
1245 ), '') as member_of");
1248 function setFromRoo($ar, $roo)
1250 $this->setFrom($ar);
1252 if(!empty($ar['_enable_oath_key'])){
1253 $oath_key = $this->generateOathKey();
1256 if (!empty($ar['passwd1'])) {
1257 $this->setPassword($ar['passwd1']);
1261 ($this->email == $roo->old->email)&&
1262 ($this->company_id == $roo->old->company_id)
1266 if (empty($this->email)) {
1269 // this only applies to our owner company..
1270 $c = $this->company();
1271 if (empty($c) || empty($c->comptype_name) || $c->comptype_name != 'OWNER') {
1276 $xx = DB_Dataobject::factory($this->tableName());
1278 'email' => $this->email,
1279 // 'company_id' => $x->company_id
1283 return "Duplicate Email found";
1290 * before Delete - delete significant dependancies..
1291 * this is called after checkPerm..
1294 function beforeDelete($dependants_array, $roo)
1296 //delete group membership except for admin group..
1297 // if they are a member of admin group do not delete anything.
1298 $default_admin = false;
1300 $e = DB_DataObject::Factory('Events');
1301 $e->whereAdd('person_id = ' . $this->id);
1303 $g = DB_DataObject::Factory('core_group');
1304 $g->get('name', 'Administrators'); // select * from core_group where name = 'Administrators'
1306 $p = DB_DataObject::Factory('core_group_member');
1308 'user_id' => $this->id,
1309 'group_id' => $g->id
1313 $roo->jerr("Please remove this user from the Administrator group before deleting");
1317 $p = DB_DataObject::Factory('core_group_member');
1318 $p->user_id = $this->id;
1319 $mem = $p->fetchAll(); // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1320 $e->logDeletedRecord($mem);
1322 foreach($mem as $p) {
1326 $e = DB_DataObject::Factory('Events');
1327 $e->person_id = $this->id;
1328 $eve = $e->fetchAll(); // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1330 $e->logDeletedRecord($eve);
1331 foreach($eve as $e) {
1342 * Check if the a user has access to modify this item.
1343 * @param String $lvl Level (eg. Core.Projects)
1344 * @param Pman_Core_DataObjects_Person $au The authenticated user.
1345 * @param boolean $changes alllow changes???
1347 * @return false if no access..
1349 function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
1352 // do we have an empty system..
1353 if ($au && $au->id == -1) {
1356 // if not authenticated... do not allow in???
1361 // determine if it's staff!!!
1362 $owncomp = DB_DataObject::Factory('core_company');
1363 $owncomp->get('comptype', 'OWNER');
1364 $isStaff = ($au->company_id == $owncomp->id);
1369 // - can not change company!!!
1371 isset($changes['company_id']) &&
1372 $changes['company_id'] != $au->company_id) {
1375 // can only set new emails..
1377 !empty($this->email) &&
1378 isset($changes['email']) &&
1379 $changes['email'] != $this->email) {
1384 // mtrack had the idea that all 'S' should be allowed.. - but filtered later..
1385 // ???? do we want this?
1387 // edit self... - what about other staff members...
1389 //return $this->company_id == $au->company_id;
1393 // yes, only owner company can mess with this...
1399 // extra case change passwod?
1400 case 'P': //??? password
1401 // standard perms -- for editing + if the user is dowing them selves..
1402 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
1403 return $ret || $au->id == $this->id;
1406 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
1412 function beforeInsert($req, $roo)
1414 $p = DB_DataObject::factory('core_person');
1415 if ($roo->authUser->id > -1 || $p->count() > 1) {
1418 $c = DB_DataObject::Factory('core_company');
1421 if (!$tc || $tc> 1) {
1422 $roo->jerr("can not create initial user as multiple companies already exist");
1425 $this->company_id = $c->id;
1426 $this->email = trim($this->email);
1430 function onInsert($req, $roo)
1433 $p = DB_DataObject::factory('core_person');
1434 if ($roo->authUser->id < 0 && $p->count() == 1) {
1435 // this seems a bit risky...
1437 $g = DB_DataObject::factory('core_group');
1441 $g->get('name', 'Administrators');
1443 $p = DB_DataObject::factory('core_group_member');
1444 $p->group_id = $g->id;
1445 $p->user_id = $this->id;
1448 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
1452 if (!empty($req['project_id_addto'])) {
1453 $pd = DB_DataObject::factory('ProjectDirectory');
1454 $pd->project_id = $req['project_id_addto'];
1455 $pd->person_id = $this->id;
1457 $pd->office_id = $this->office_id;
1458 $pd->company_id = $this->company_id;
1464 function importFromArray($roo, $persons, $opts)
1466 if (empty($opts['prefix'])) {
1467 $roo->jerr("opts[prefix] is empty - you can not just create passwords based on the user names");
1470 if (!is_array($persons) || empty($persons)) {
1471 $roo->jerr("error in the person data. - empty on not valid");
1473 DB_DataObject::factory('core_group')->initGroups();
1475 foreach($persons as $person){
1476 $p = DB_DataObject::factory('core_person');
1477 if($p->get('name', $person['name'])){
1480 $p->setFrom($person);
1482 $companies = DB_DataObject::factory('core_company');
1483 if(!$companies->get('comptype', 'OWNER')){
1484 $roo->jerr("Missing OWNER companies!");
1486 $p->company_id = $companies->pid();
1487 // strip the 'spaces etc.. make lowercase..
1488 $name = strtolower(str_replace(' ', '', $person['name']));
1489 $p->setPassword("{$opts['prefix']}{$name}");
1492 // if $person->groups is set.. then
1493 // add this person to that group eg. groups : [ 'Administrator' ]
1494 if(!empty($person['groups'])){
1495 $groups = DB_DataObject::factory('core_group');
1496 if(!$groups->get('name', $person['groups'])){
1497 $roo->jerr("Missing groups : {$person['groups']}");
1499 $gm = DB_DataObject::factory('core_group_member');
1500 $gm->change($p, $groups, true);
1503 $p->onInsert(array(), $roo);
1507 // this is for the To: "{getEmailName()}" <email@address>
1508 // not good for Dear XXXX, - use {person.firstname} for that.
1509 function getEmailName()
1513 if(!empty($this->honor)){
1514 array_push($name, $this->honor);
1517 if(!empty($this->name)){
1518 array_push($name, $this->name);
1520 return implode(' ', $name);
1523 if(!empty($this->firstname) || !empty($this->lastname)){
1524 array_push($name, $this->firstname);
1525 array_push($name, $this->lastname);
1527 $name = array_filter($name);
1529 return implode(' ', $name);
1532 return $this->email;
1535 function sesPrefix()
1537 $ff= HTML_FlexyFramework::get();
1539 $appname = empty($ff->appNameShort) ? $ff->project : $ff->project . '-' . $ff->appNameShort;
1541 $dname = method_exists($this, 'getDatabaseConnection') ? $this->getDatabaseConnection()->dsn['database'] : $this->databaseNickname();
1543 $sesPrefix = $appname.'-' .get_class($this) .'-' . $dname;
1548 function loginPublic() // used where???
1550 $this->isAuth(); // force session start..
1552 $db = $this->getDatabaseConnection();
1554 $ff = HTML_FlexyFramework::get();
1556 if(empty($ff->Pman) || empty($ff->Pman['login_public'])){
1560 $sesPrefix = $ff->Pman['login_public'] . '-' .get_class($this) .'-'.$db->dsn['database'] ;
1562 $p = DB_DAtaObject::Factory($this->tableName());
1563 $p->get($this->pid());
1565 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$p->toArray());
1570 function beforeUpdate($old, $q, $roo)
1572 $this->email = trim($this->email);
1575 function generateOathKey()
1577 require 'Base32.php';
1579 $base32 = new Base32();
1581 return $base32->base32_encode(bin2hex(openssl_random_pseudo_bytes(10)));
1584 function generateQRCode($hash)
1587 empty($this->email) &&
1593 $issuer = rawurlencode($this->qrCodeIssuer());
1595 $uri = "otpauth://totp/{$issuer}:{$this->email}?secret={$hash}&issuer={$issuer}&algorithm=SHA1&digits=6&period=30";
1597 require_once 'Image/QRCode.php';
1599 $qrcode = new Image_QRCode();
1601 $image = $qrcode->makeCode($uri, array(
1602 'output_type' => 'return'
1607 $base64 = base64_encode(ob_get_contents());
1610 return "data:image/png;base64,{$base64}";
1613 function qrCodeIssuer()
1615 $pg= HTML_FlexyFramework::get()->page;
1617 $issuer = (empty($pg->company->name)) ? 'ROOJS' : "{$pg->company->name}";
1622 static function test_ADMIN_PASSWORD_RESET($pg, $to)
1624 $ff = HTML_FlexyFramework::get();
1625 $person = DB_DataObject::Factory('core_person');
1629 'HTTP_HOST' => $_SERVER['SERVER_NAME'],
1630 'person' => $person,
1631 'authFrom' => 'FAKE_LINK',
1632 'authKey' => 'FAKE_KEY',
1634 'rcpts' => $to->email,