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;
53 /* the code above is auto generated do not remove the tag below */
56 static $authUser = false;
61 // this might be a Person in some old code?
62 $p = DB_DataObject::Factory('core_person');
63 $p->get($this->owner_id);
72 * FIXME !!!! -- USE Pman_Core_Mailer !!!!!
78 function buildMail($templateFile, $args)
81 $args = (array) $args;
82 $content = clone($this);
84 foreach((array)$args as $k=>$v) {
88 $ff = HTML_FlexyFramework::get();
91 //?? is this really the place for this???
94 empty($args['no_auth']) &&
95 !in_array($templateFile, array(
96 // templates that can be sent without authentication.
102 $content->authUser = $this->getAuthUser();
103 if (!$content->authUser) {
104 return PEAR::raiseError("Not authenticated");
108 // should handle x-forwarded...
110 $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
111 $_SERVER["HTTP_HOST"] :
112 (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
114 /* use the regex compiler, as it doesnt parse <tags */
117 'compiler' => 'Flexy',
119 'filters' => array('SimpleTags','Mail'),
125 if (!empty($args['templateDir'])) {
126 $tops['templateDir'] = $args['templateDir'];
131 require_once 'HTML/Template/Flexy.php';
132 $template = new HTML_Template_Flexy( $tops );
133 $template->compile("mail/$templateFile.txt");
135 /* use variables from this object to ouput data. */
136 $mailtext = $template->bufferedOutputObject($content);
139 // if a html file with the same name exists, use that as the body
140 // I've no idea where this code went, it was here before..
141 if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
142 $tops['nonHTML'] = false;
143 $template = new HTML_Template_Flexy( $tops );
144 $template->compile("mail/$templateFile.html");
145 $htmlbody = $template->bufferedOutputObject($content);
151 //echo "<PRE>";print_R($mailtext);
152 //print_R($mailtext);exit;
153 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
154 require_once 'Mail/mimeDecode.php';
155 require_once 'Mail.php';
157 $decoder = new Mail_mimeDecode($mailtext);
158 $parts = $decoder->getSendArray();
160 if (is_a($parts,'PEAR_Error')) {
162 //echo "PROBLEM: {$parts->message}";
165 list($recipents,$headers,$body) = $parts;
166 $recipents = array($this->email);
167 if (!empty($content->bcc) && is_array($content->bcc)) {
168 $recipents =array_merge($recipents, $content->bcc);
170 $headers['Date'] = date('r');
172 if ($htmlbody !== false) {
173 require_once 'Mail/mime.php';
174 $mime = new Mail_mime(array('eol' => "\n"));
175 $mime->setTXTBody($body);
176 $mime->setHTMLBody($htmlbody);
177 // I think there might be code in mediaoutreach toEmail somewhere
178 // h embeds images here..
179 $body = $mime->get();
180 $headers = $mime->headers($headers);
184 'recipients' => $recipents,
185 'headers' => $headers,
193 * - user must be authenticate or args[no_auth] = true
194 * or template = password_[reset|welcome]
197 function sendTemplate($templateFile, $args)
199 $ar = $this->buildMail($templateFile, $args);
201 //print_r($recipents);exit;
202 $mailOptions = PEAR::getStaticProperty('Mail','options');
203 $mail = Mail::factory("SMTP",$mailOptions);
205 if (PEAR::isError($mail)) {
208 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
209 $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
210 error_reporting($oe);
218 function getEmailFrom()
220 if (empty($this->name)) {
224 return '"' . addslashes($this->name) . '" <' . $this->email . '>';
227 function toEventString()
229 return empty($this->name) ? $this->email : $this->name;
232 function verifyAuth()
234 $ff= HTML_FlexyFramework::get();
235 if (!empty($ff->Pman['auth_comptype']) &&
236 (!$this->company_id || ($ff->Pman['auth_comptype'] != $this->company()->comptype))
239 $sesPrefix = $this->sesPrefix();
241 self::$authUser = false;
242 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
246 //$ff->page->jerr("Login not permited to outside companies");
253 // ---------------- authentication / passwords and keys stuff ----------------
256 // do not start a session if we are using http auth...
257 // we have a situation where the app is behind a http access and is also login
258 // need to work out a way to handle that.
260 if (php_sapi_name() != "cli" && empty($_SERVER['PHP_AUTH_USER']) && !empty($ff->disable_http_auth)) {
266 $sesPrefix = $this->sesPrefix();
268 if (self::$authUser) {
269 return self::$authUser;
273 if (!empty($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
275 $a = unserialize($_SESSION[get_class($this)][$sesPrefix .'-auth']);
276 $u = DB_DataObject::factory($this->tableName());
278 if ($a->id && $u->get($a->id)) { //&& strlen($u->passwd)) {
279 if ($u->verifyAuth()) {
280 self::$authUser = $u;
284 unset($_SESSION[get_class($this)][$sesPrefix .'-auth']);
285 unset($_SESSION[get_class($this)][$sesPrefix .'-timeout']);
286 setcookie('Pman.timeout', -1, time() + (30*60), '/');
291 $u = DB_DataObject::factory($this->tableName());
293 if (empty($_COOKIE['PHPSESSID']) // http auth requests should not have this...
295 !empty($_SERVER['PHP_AUTH_USER'])
297 !empty($_SERVER['PHP_AUTH_PW'])
299 $u->get('email', $_SERVER['PHP_AUTH_USER'])
301 $u->checkPassword($_SERVER['PHP_AUTH_PW'])
303 // logged in via http auth
304 // http auth will not need session...
305 //$_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize($u);
306 self::$authUser = $u;
310 // at this point all http auth stuff is done, so we can init session
314 if (!$this->canInitializeSystem()) {
315 // die("can not init");
320 $auto_auth_allow = false;
321 if (!empty($ff->Pman['local_autoauth']) && $ff->Pman['local_autoauth'] === true) {
322 $auto_auth_allow = true;
324 if ( !empty($ff->Pman['local_autoauth'])
326 !empty($_SERVER['SERVER_ADDR']) &&
327 !empty($_SERVER['REMOTE_ADDR']) &&
330 $_SERVER['SERVER_ADDR'] == '127.0.0.1' &&
331 $_SERVER['REMOTE_ADDR'] == '127.0.0.1'
335 $_SERVER['SERVER_ADDR'] == '::1' &&
336 $_SERVER['REMOTE_ADDR'] == '::1'
341 $auto_auth_allow = true;
345 if (empty($_SERVER['PATH_INFO']) || $_SERVER['PATH_INFO'] == '/Login') {
346 $auto_auth_allow = false;
348 //var_dump($auto_auth_allow);
350 $default_admin = false;
351 if ($auto_auth_allow) {
352 $group = DB_DataObject::factory('core_group');
353 $group->get('name', 'Administrators');
355 $member = DB_DataObject::factory('core_group_member');
357 $member->group_id = $group->id;
359 join_user_id_id.id IS NOT NULL
361 if($member->find(true)){
362 $default_admin = DB_DataObject::factory($this->tableName());
363 $default_admin->autoJoin();
364 if(!$default_admin->get($member->user_id)){
365 $default_admin = false;
370 //var_dump($ff->Pman['local_autoauth']); var_dump($_SERVER); exit;
371 $u = DB_DataObject::factory($this->tableName());
373 $ff = HTML_FlexyFramework::get();
375 if ($auto_auth_allow &&
376 ($default_admin || $u->get('email', $ff->Pman['local_autoauth']))
379 $user = $default_admin ? $default_admin->toArray() : $u->toArray();
381 // if we request other URLS.. then we get auto logged in..
382 self::$authUser = $default_admin ? $default_admin : $u;;
383 //$_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object) $user);
387 //var_dump(session_id());
388 //var_dump($_SESSION[__CLASS__]);
390 //if (!empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
393 //die("got this far?");
394 // not in session or not matched...
395 $u = DB_DataObject::factory($this->tableName());
396 $u->whereAdd(' LENGTH(passwd) > 0');
398 if (empty($_SESSION[get_class($this)]) || !is_array($_SESSION[get_class($this)])) {
399 $_SESSION[get_class($this)] = array();
401 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $n;
402 if (class_exists('PEAR')) {
403 $error = PEAR::getStaticProperty('DB_DataObject','lastError');
405 die($error->toString()); // not really a good thing to do...
408 if (!$n){ // authenticated as there are no users in the system...
415 function canInitializeSystem()
418 return !strcasecmp(get_class($this) , __CLASS__);
421 function getAuthUser()
423 if (!$this->isAuth()) {
427 $ff= HTML_FlexyFramework::get();
429 $sesPrefix = $this->sesPrefix();
431 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
433 if (self::$authUser) {
435 if (isset($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
436 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
437 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
439 // not really sure why it's cloned..
440 return clone (self::$authUser);
447 if (!$this->canInitializeSystem()) {
453 if (empty( $_SESSION[get_class($this)][$sesPrefix .'-empty'] )) {
454 $u = DB_DataObject::factory($this->tableName());
455 $u->whereAdd(' LENGTH(passwd) > 0');
456 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $u->count();
461 isset( $_SESSION[get_class($this)][$sesPrefix .'-empty'] ) &&
462 $_SESSION[get_class($this)][$sesPrefix .'-empty'] < 1
465 // fake person - open system..
466 //$ce = DB_DataObject::factory('core_enum');
470 $u = DB_DataObject::factory($this->tableName());
473 // if a company has been created fill that in in company_id_id
474 $c = DB_DAtaObject::factory('core_company')->lookupOwner();
476 $u->company_id_id = $c->pid();
477 $u->company_id = $c->pid();
487 $this->isAuth(); // force session start..
488 if (!$this->verifyAuth()) { // check for company valid..
492 // open up iptables at login..
493 $dbname = $this->databaseNickname();
494 touch( '/tmp/run_pman_admin_iptables-'.$dbname);
496 // refresh admin group if we are logged in as one..
497 //DB_DataObject::debugLevel(1);
498 $g = DB_DataObject::factory('core_group');
500 $g->get('name', 'Administrators');
501 $gm = DB_DataObject::Factory('core_group_member');
502 if (in_array($g->id,$gm->listGroupMembership($this))) {
503 // refresh admin groups.
504 $gr = DB_DataObject::Factory('core_group_right');
505 $gr->applyDefs($g, 0);
508 $sesPrefix = $this->sesPrefix();
510 // we should not store the whole data in the session - otherwise it get's huge.
511 $p = DB_DAtaObject::Factory($this->tableName());
512 $p->get($this->pid());
516 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
517 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
519 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
520 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$d);
522 $pp = DB_DAtaObject::Factory($this->tableName());
523 $pp->get($this->pid());
526 self::$authUser = $pp;
527 // ensure it's written so that ajax calls can fetch it..
534 $this->isAuth(); // force session start..
536 $sesPrefix = $this->sesPrefix();
537 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = -1;
538 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
539 self::$authUser = false;
542 function genPassKey ($t)
544 return md5($this->email . $t. $this->passwd);
546 function simpleAuthKey($m = 0)
548 $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
550 return md5(implode(',' , array($month, $this->email , $this->passwd, $this->id)));
553 * When we generate autologin urls:
554 * eg. /Somesite/Test/12
556 * /Somesite/Test/12/{datetime}/{sha256(url + expires_datetime + password)}
558 * eg. genAutoLoginURL($sub, $expires)
560 function genAutoLoginURL($url, $expires = false)
562 $expires = $expires === false ? strtotime("NOW + 1 WEEK") : $expires;
563 //echo serialize(array($url, $expires, $this->email, $this->passwd));
564 //echo hash('sha256', serialize(array($url, $expires, $this->email, $this->passwd)));
566 return $url.'/'.$this->id .'/'.$expires.'/'.
569 array($url, $expires, $this->email,$this->passwd)
575 function validateAutoLogin($called)
577 $bits = explode("/",$called);
578 if (count($bits) < 4) {
579 return false; // unrelated.
581 $hash = array_pop($bits);
582 $time = array_pop($bits);
584 $id = array_pop($bits);
585 if (!is_numeric($time) || !is_numeric($id)) {
586 return false; // wrong format.
588 $u = DB_DataObject::Factory($this->tableName());
590 $url = implode("/", $bits);
591 if ($time < time()) {
594 //echo serialize(array('/'.$url, $time, $u->email, $u->passwd));
595 //echo hash('sha256', serialize(array('/'.$url, $time, $u->email, $u->passwd)));
596 if ($hash == hash('sha256', serialize(array('/'.$url, $time*1, $u->email, $u->passwd)))) {
604 function checkTwoFactorAuthentication($val)
608 // also used in login
609 require_once 'System.php';
613 empty($this->oath_key)
618 $oathtool = System::which('oathtool');
624 $cmd = "{$oathtool} --totp --base32 " . escapeshellarg($this->oath_key);
626 $password = exec($cmd);
628 return ($password == $val) ? true : false;
631 function checkPassword($val)
633 if (substr($this->passwd,0,1) == '$') {
634 if (function_exists('pasword_verify')) {
635 return password_verify($val, $this->passwd);
637 return crypt($val,$this->passwd) == $this->passwd ;
639 // old style md5 passwords...- cant be used with courier....
640 return md5($val) == $this->passwd;
643 function setPassword($value)
645 if (function_exists('pasword_hash')) {
646 return password_hash($value);
650 while(strlen($salt)<9) {
651 $salt.=chr(rand(64,126));
652 //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
654 $this->passwd = crypt($value, '$1$'. $salt. '$');
659 function generatePassword($length = 5) // genearte a password (add set 'rawPasswd' to it's value)
661 require_once 'Text/Password.php';
662 $this->rawPasswd = strtr(ucfirst(Text_Password::create($length)).ucfirst(Text_Password::create($length)), array(
663 "a"=>"4", "e"=>"3", "i"=>"1", "o"=>"0", "s"=>"5", "t"=>"7"));
664 $this->setPassword($this->rawPasswd);
665 return $this->rawPasswd;
670 if (empty($this->company_id)) {
673 $x = DB_DataObject::factory('core_company');
675 $x->get($this->company_id);
678 function loadCompany()
680 $this->company = $this->company();
685 return $this->active;
687 function authUserName($n) // set username prior to acheck user exists query.
690 $this->whereAdd('LENGTH(passwd) > 1');
695 if (!func_num_args()) {
698 $ar = func_get_args();
699 $val = array_shift($ar);
700 if ($val == $this->lang) {
710 function authUserArray()
712 $aur = $this->toArray();
718 //DB_DataObject::debugLevel(1);
719 $c = DB_Dataobject::factory('core_company');
720 $im = DB_Dataobject::factory('Images');
721 $c->joinAdd($im, 'LEFT');
723 $c->selectAs($c, 'company_id_%s');
724 $c->selectAs($im, 'company_id_logo_id_%s');
725 $c->id = $this->company_id;
729 $aur = array_merge( $c->toArray(),$aur);
731 if (empty($c->company_id_logo_id_id)) {
733 $im = DB_Dataobject::factory('Images');
734 $im->ontable = DB_DataObject::factory('core_company')->tableName();
736 $im->imgtype = 'LOGO';
739 $im->selectAs($im, 'company_id_logo_id_%s');
740 if ($im->find(true)) {
742 foreach($im->toArray() as $k=>$v) {
743 if (!preg_match('/^company_id_logo_id_/', $k)) {
752 $aur['perms'] = $this->getPerms();
753 $g = DB_DataObject::Factory('core_group_member');
754 $aur['groups'] = $g->listGroupMembership($this, 'name');
757 $aur['dailykey'] = '';
758 $aur['oath_key'] = '';
760 $aur['oath_key_enable'] = !empty($this->oath_key);
761 $aur['require_oath'] = 1;
763 $s = DB_DataObject::Factory('core_setting');
764 $oath_require = $s->lookup('core', 'two_factor_auth_required');
765 $aur['require_oath'] = $oath_require ? $oath_require->val : 0;
767 $aur['core_person_settings'] = array();
769 $core_person_settings = DB_DataObject::factory('core_person_settings');
770 $core_person_settings->setFrom(array(
771 'person_id' => $this->id
774 $aur['core_person_settings'] = $core_person_settings->fetchAll('scope', 'data');
779 // ----------PERMS------ ----------------
782 //DB_DataObject::debugLevel(1);
783 // find out all the groups they are a member of.. + Default..
785 // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
787 $g = DB_DataObject::Factory('core_group_right');
793 return $g->adminRights(); // system is not set up - so they get full rights.
795 //DB_DataObject::debugLevel(1);
796 $g = DB_DataObject::Factory('core_group_member');
797 $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
799 // add the current user to the admin group..
800 $g = DB_DataObject::Factory('core_group');
801 if ($g->get('name', 'Administrators')) {
802 $gm = DB_DataObject::Factory('core_group_member');
803 $gm->group_id = $g->id;
804 $gm->user_id = $this->id;
810 // ------ STANDARD PERMISSION HANDLING.
811 $isOwner = $this->company()->comptype == 'OWNER';
812 $g = DB_DataObject::Factory('core_group_member');
813 $grps = $g->listGroupMembership($this);
815 $isAdmin = $g->inAdmin; //??? what???
816 //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
817 // the load all the perms for those groups, and add them all together..
818 // then load all those
819 $g = DB_DataObject::Factory('core_group_right');
820 $ret = $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
821 //echo '<PRE>';print_r($ret);
827 *Basic group fetching - probably needs to filter by type eventually.
829 *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
832 function groups($what=false)
834 $g = DB_DataObject::Factory('core_group_member');
835 $grps = $g->listGroupMembership($this);
836 $g = DB_DataObject::Factory('core_group');
837 $g->whereAddIn('id', $grps, 'int');
838 return $g->fetchAll($what);
844 function hasPerm($name, $lvl)
846 static $pcache = array();
848 if (!isset($pcache[$this->id])) {
849 $pcache[$this->id] = $this->getPerms();
852 // echo "<PRE>";print_r($pcache[$au->id]);
853 // var_dump($pcache[$au->id]);
854 if (empty($pcache[$this->id][$name])) {
858 return strpos($pcache[$this->id][$name], $lvl) > -1;
862 // ------------ROO HOOKS------------------------------------
863 function applyFilters($q, $au, $roo)
865 //DB_DataObject::DebugLevel(1);
866 if(!empty($q['_to_qr_code'])){
867 $person = DB_DataObject::factory('Core_person');
868 $person->id = $q['id'];
870 if(!$person->find(true)) {
871 $roo->jerr('_invalid_person');
874 $hash = $this->generateOathKey();
876 $_SESSION[__CLASS__] =
877 isset($_SESSION[__CLASS__]) ?
878 $_SESSION[__CLASS__] : array();
879 $_SESSION[__CLASS__]['oath'] =
880 isset($_SESSION[__CLASS__]['oath']) ?
881 $_SESSION[__CLASS__]['oath'] : array();
883 $_SESSION[__CLASS__]['oath'][$person->id] = $hash;
885 $qrcode = $person->generateQRCode($hash);
888 $roo->jerr('Fail to generate QR Code');
894 'issuer' => $person->qrCodeIssuer()
898 if(!empty($q['two_factor_auth_code'])) {
899 $person = DB_DataObject::factory('core_person');
900 $person->get($q['id']);
902 $person->oath_key = $_SESSION[__CLASS__]['oath'][$person->id];
904 if($person->checkTwoFactorAuthentication($q['two_factor_auth_code'])) {
906 unset($_SESSION[__CLASS__]['oath'][$person->id]);
910 $roo->jerr('_invalid_auth_code');
913 if(!empty($q['oath_key_disable'])) {
914 $person = DB_DataObject::factory('core_person');
915 $person->get($q['id']);
919 $person->oath_key = '';
925 if (!empty($q['query']['is_owner'])) {
926 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
929 if (!empty($q['query']['person_not_internal'])) {
930 $this->whereAdd(" join_company_id_id.isOwner = 0 ");
933 if (!empty($q['query']['person_internal_only_all'])) {
936 // must be internal and not current user (need for distribution list)
937 // user has a projectdirectory entry and role is not blank.
938 //DB_DataObject::DebugLevel(1);
939 $pd = DB_DataObject::factory('ProjectDirectory');
940 $pd->whereAdd("role != ''");
942 $pd->selectAdd('distinct(person_id) as person_id');
943 $roled = $pd->fetchAll('person_id');
945 {$this->tableName()}.id IN (".implode(',', $roled) . ")
947 $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
950 // -- for distribution
951 if (!empty($q['query']['person_internal_only'])) {
952 // must be internal and not current user (need for distribution list)
953 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
955 //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
956 // ".id != ".$au->id);
957 $this->whereAdd("{$this->tableName()}.id != {$au->id}");
960 if (!empty($q['query']['comptype_or_company_id'])) {
961 // DB_DataObject::debugLevel(1);
962 $bits = explode(',', $q['query']['comptype_or_company_id']);
963 $id = (int) array_pop($bits);
964 $ct = $this->escape($bits[0]);
966 $this->whereAdd(" join_company_id_id.comptype = '$ct' OR {$this->tableName()}.company_id = $id");
972 if (!empty($q['query']['person_inactive'])) {
973 // DB_Dataobject::debugLevel(1);
976 $tn_p = $this->tableName();
977 $tn_gm = DB_DataObject::Factory('core_group_member')->tableName();
978 $tn_g = DB_DataObject::Factory('core_group')->tableName();
980 ///---------------- Group views --------
981 if (!empty($q['query']['in_group'])) {
982 // DB_DataObject::debugLevel(1);
983 $ing = (int) $q['query']['in_group'];
984 if ($q['query']['in_group'] == -1) {
986 // list all staff who are not in a group.
987 $this->whereAdd("{$this->tableName()}.id NOT IN (
988 SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
989 $tn_g ON $tn_g.id = $tn_gm.group_id)");
993 $this->whereAdd("$tn_p.id IN (
994 SELECT distinct(user_id) FROM $tn_gm
995 WHERE group_id = $ing
1001 if(!empty($q['in_group_name'])){
1003 $v = $this->escape($q['in_group_name']);
1008 DISTINCT(user_id) FROM $tn_gm
1012 $tn_g.id = $tn_gm.group_id
1018 if(!empty($q['in_group_starts'])){
1020 $v = $this->escape($q['in_group_starts']);
1025 DISTINCT(user_id) FROM $tn_gm
1029 $tn_g.id = $tn_gm.group_id
1031 $tn_g.name LIKE '{$v}%'
1038 // #2307 Search Country!!
1039 if (!empty($q['query']['in_country'])) {
1040 // DB_DataObject::debugLevel(1);
1041 $inc = $q['query']['in_country'];
1042 $this->whereAdd("$tn_p.countries LIKE '%{$inc}%'");
1045 if (!empty($q['query']['not_in_directory'])) {
1046 // it's a Person list..
1047 // DB_DATaobjecT::debugLevel(1);
1049 // specific to project directory which is single comp. login
1051 $owncomp = DB_DataObject::Factory('core_company');
1052 $owncomp->get('comptype', 'OWNER');
1053 if ($q['company_id'] == $owncomp->id) {
1059 if ( $q['query']['not_in_directory'] > -1) {
1060 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1061 // can list current - so that it does not break!!!
1062 $this->whereAdd("$tn_p.id NOT IN
1063 ( SELECT distinct person_id FROM $tn_pd WHERE
1064 project_id = " . $q['query']['not_in_directory'] . " AND
1065 company_id = " . $this->company_id . ')');
1069 if (!empty($q['query']['role'])) {
1070 // it's a Person list..
1071 // DB_DATaobjecT::debugLevel(1);
1073 // specific to project directory which is single comp. login
1075 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1076 // can list current - so that it does not break!!!
1077 $this->whereAdd("$tn_p.id IN
1078 ( SELECT distinct person_id FROM $tn_pd WHERE
1079 role = '". $this->escape($q['query']['role']) ."'
1085 if (!empty($q['query']['project_member_of'])) {
1086 // this is also a flag to return if they are a member..
1087 //DB_DataObject::debugLevel(1);
1088 $do = DB_DataObject::factory('ProjectDirectory');
1089 $do->project_id = $q['query']['project_member_of'];
1090 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
1091 $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
1092 $this->selectAdd("IF($tn_pd.id IS NULL, 0, $tn_pd.id ) as is_member");
1095 if (!empty($q['query']['project_member_filter'])) {
1096 $this->having('is_member !=0');
1102 if(!empty($q['query']['name'])){
1104 {$this->tableName()}.name LIKE '%{$this->escape($q['query']['name'])}%'
1108 if(!empty($q['query']['name_or_email'])){
1109 $v = $this->escape($q['query']['name_or_email']);
1111 {$this->tableName()}.name LIKE '%{$v}%'
1113 {$this->tableName()}.email LIKE '%{$v}%'
1116 if(!empty($q['query']['name_starts'])){
1118 {$this->tableName()}.name LIKE '{$this->escape($q['query']['name_starts'])}%'
1122 if (!empty($q['query']['search'])) {
1124 // use our magic search builder...
1126 require_once 'Text/SearchParser.php';
1127 $x = new Text_SearchParser($q['query']['search']);
1135 "join_company_id_id.name"
1137 $tbcols = $this->table();
1138 foreach(array('firstname','lastname') as $k) {
1139 if (isset($tbcols[$k])) {
1140 $props[] = "{$tn_p}.{$k}";
1147 $str = $x->toSQL(array(
1148 'default' => $props,
1150 'company' => 'join_company_id_id.name',
1151 //'country' => 'Clipping.country',
1152 // 'media' => 'Clipping.media_name',
1154 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
1159 $this->whereAdd($str); /*
1160 $tn_p.name LIKE '%$s%' OR
1161 $tn_p.email LIKE '%$s%' OR
1162 $tn_p.role LIKE '%$s%' OR
1163 $tn_p.phone LIKE '%$s%' OR
1164 $tn_p.remarks LIKE '%$s%'
1169 // project directory rules -- this may distrupt things.
1170 $p = DB_DataObject::factory('ProjectDirectory');
1171 // if project directories are set up, then we can apply project query rules..
1174 $pids = $p->projects($au);
1175 if (isset($q['query']['project_id'])) {
1176 $pid = (int)$q['query']['project_id'];
1177 if (!in_array($pid, $pids)) {
1178 $roo->jerr("Project not in users valid projects");
1180 $pids = array($pid);
1183 //if (empty($q['_anyrole'])) { // should be project_directry_role
1184 // $p->whereAdd("{$p->tableName()}.role != ''");
1186 if (!empty($q['query']['role'])) { // should be project_directry_role
1187 $role = $this->escape($q['query']['role']);
1189 $p->whereAdd("{$p->tableName()}.role LIKE '%{$role}%'");
1193 if (!$roo->hasPerm('Core.Projects_All', 'S')) {
1194 $peps = $p->people($pids);
1195 $this->whereAddIn("{$this->tableName()}.id", $peps, 'int');
1199 // fixme - this needs a more generic fix - it was from the mtrack_person code...
1200 if (isset($q['query']['ticket_id'])) {
1201 // find out what state the ticket is in.
1202 $t = DB_DataObject::Factory('mtrack_ticket');
1204 $t->get($q['query']['ticket_id']);
1206 if (!$this->checkPerm('S', $au)) {
1207 $roo->jerr("permssion denied to query state of ticket");
1210 $p = DB_DataObject::factory('ProjectDirectory');
1211 $pids = array($t->project_id);
1213 $peps = $p->people($pids);
1215 $this->whereAddIn($this->tableName().'.id', $peps, 'int');
1217 //$this->whereAdd('join_prole != ''");
1222 * Seems we never expose oath_key / passwd, so...
1225 if($this->tableName() == 'core_person'){
1226 $this->_extra_cols = array('length_passwd', 'length_oath_key');
1229 LENGTH({$this->tableName()}.passwd) AS length_passwd,
1230 LENGTH({$this->tableName()}.oath_key) AS length_oath_key
1233 if (isset($q['_with_group_membership'])) {
1234 $this->selectAddGroupMemberships();
1239 function selectAddGroupMemberships()
1245 GROUP_CONCAT( CASE WHEN core_group.display_name = '' THEN core_group.name ELSE core_group.display_name END separator '\n')
1251 core_group.id = core_group_member.group_id
1253 core_group_member.user_id = core_person.id
1255 core_group.display_name ASC
1256 ), '') as member_of");
1259 function setFromRoo($ar, $roo)
1261 $this->setFrom($ar);
1263 if(!empty($ar['_enable_oath_key'])){
1264 $oath_key = $this->generateOathKey();
1267 if (!empty($ar['passwd1'])) {
1268 $this->setPassword($ar['passwd1']);
1272 ($this->email == $roo->old->email)&&
1273 ($this->company_id == $roo->old->company_id)
1277 if (empty($this->email)) {
1280 // this only applies to our owner company..
1281 $c = $this->company();
1282 if (empty($c) || empty($c->comptype_name) || $c->comptype_name != 'OWNER') {
1287 $xx = DB_Dataobject::factory($this->tableName());
1289 'email' => $this->email,
1290 // 'company_id' => $x->company_id
1294 return "Duplicate Email found";
1301 * before Delete - delete significant dependancies..
1302 * this is called after checkPerm..
1305 function beforeDelete($dependants_array, $roo)
1307 //delete group membership except for admin group..
1308 // if they are a member of admin group do not delete anything.
1309 $default_admin = false;
1311 $e = DB_DataObject::Factory('Events');
1312 $e->whereAdd('person_id = ' . $this->id);
1314 $g = DB_DataObject::Factory('core_group');
1315 $g->get('name', 'Administrators'); // select * from core_group where name = 'Administrators'
1317 $p = DB_DataObject::Factory('core_group_member');
1319 'user_id' => $this->id,
1320 'group_id' => $g->id
1324 $roo->jerr("Please remove this user from the Administrator group before deleting");
1328 $p = DB_DataObject::Factory('core_group_member');
1329 $p->user_id = $this->id;
1330 $mem = $p->fetchAll(); // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1331 $e->logDeletedRecord($mem);
1333 foreach($mem as $p) {
1337 $e = DB_DataObject::Factory('Events');
1338 $e->person_id = $this->id;
1339 $eve = $e->fetchAll(); // fetch all the rows and set the $mem variable to the rows data, just like mysqli_fetch_assoc
1341 $e->logDeletedRecord($eve);
1342 foreach($eve as $e) {
1353 * Check if the a user has access to modify this item.
1354 * @param String $lvl Level (eg. Core.Projects)
1355 * @param Pman_Core_DataObjects_Person $au The authenticated user.
1356 * @param boolean $changes alllow changes???
1358 * @return false if no access..
1360 function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
1363 // do we have an empty system..
1364 if ($au && $au->id == -1) {
1367 // if not authenticated... do not allow in???
1372 // determine if it's staff!!!
1373 $owncomp = DB_DataObject::Factory('core_company');
1374 $owncomp->get('comptype', 'OWNER');
1375 $isStaff = ($au->company_id == $owncomp->id);
1380 // - can not change company!!!
1382 isset($changes['company_id']) &&
1383 $changes['company_id'] != $au->company_id) {
1386 // can only set new emails..
1388 !empty($this->email) &&
1389 isset($changes['email']) &&
1390 $changes['email'] != $this->email) {
1395 // mtrack had the idea that all 'S' should be allowed.. - but filtered later..
1396 // ???? do we want this?
1398 // edit self... - what about other staff members...
1400 //return $this->company_id == $au->company_id;
1404 // yes, only owner company can mess with this...
1410 // extra case change passwod?
1411 case 'P': //??? password
1412 // standard perms -- for editing + if the user is dowing them selves..
1413 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
1414 return $ret || $au->id == $this->id;
1417 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
1423 function beforeInsert($req, $roo)
1425 $p = DB_DataObject::factory('core_person');
1426 if ($roo->authUser->id > -1 || $p->count() > 1) {
1429 $c = DB_DataObject::Factory('core_company');
1432 if (!$tc || $tc> 1) {
1433 $roo->jerr("can not create initial user as multiple companies already exist");
1436 $this->company_id = $c->id;
1437 $this->email = trim($this->email);
1441 function onInsert($req, $roo)
1444 $p = DB_DataObject::factory('core_person');
1445 if ($roo->authUser->id < 0 && $p->count() == 1) {
1446 // this seems a bit risky...
1448 $g = DB_DataObject::factory('core_group');
1452 $g->get('name', 'Administrators');
1454 $p = DB_DataObject::factory('core_group_member');
1455 $p->group_id = $g->id;
1456 $p->user_id = $this->id;
1459 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
1463 if (!empty($req['project_id_addto'])) {
1464 $pd = DB_DataObject::factory('ProjectDirectory');
1465 $pd->project_id = $req['project_id_addto'];
1466 $pd->person_id = $this->id;
1468 $pd->office_id = $this->office_id;
1469 $pd->company_id = $this->company_id;
1475 function importFromArray($roo, $persons, $opts)
1477 if (empty($opts['prefix'])) {
1478 $roo->jerr("opts[prefix] is empty - you can not just create passwords based on the user names");
1481 if (!is_array($persons) || empty($persons)) {
1482 $roo->jerr("error in the person data. - empty on not valid");
1484 DB_DataObject::factory('core_group')->initGroups();
1486 foreach($persons as $person){
1487 $p = DB_DataObject::factory('core_person');
1488 if($p->get('name', $person['name'])){
1491 $p->setFrom($person);
1493 $companies = DB_DataObject::factory('core_company');
1494 if(!$companies->get('comptype', 'OWNER')){
1495 $roo->jerr("Missing OWNER companies!");
1497 $p->company_id = $companies->pid();
1498 // strip the 'spaces etc.. make lowercase..
1499 $name = strtolower(str_replace(' ', '', $person['name']));
1500 $p->setPassword("{$opts['prefix']}{$name}");
1503 // if $person->groups is set.. then
1504 // add this person to that group eg. groups : [ 'Administrator' ]
1505 if(!empty($person['groups'])){
1506 $groups = DB_DataObject::factory('core_group');
1507 if(!$groups->get('name', $person['groups'])){
1508 $roo->jerr("Missing groups : {$person['groups']}");
1510 $gm = DB_DataObject::factory('core_group_member');
1511 $gm->change($p, $groups, true);
1514 $p->onInsert(array(), $roo);
1518 // this is for the To: "{getEmailName()}" <email@address>
1519 // not good for Dear XXXX, - use {person.firstname} for that.
1520 function getEmailName()
1524 if(!empty($this->honor)){
1525 array_push($name, $this->honor);
1528 if(!empty($this->name)){
1529 array_push($name, $this->name);
1531 return implode(' ', $name);
1534 if(!empty($this->firstname) || !empty($this->lastname)){
1535 array_push($name, $this->firstname);
1536 array_push($name, $this->lastname);
1538 $name = array_filter($name);
1540 return implode(' ', $name);
1543 return $this->email;
1546 function sesPrefix()
1548 $ff= HTML_FlexyFramework::get();
1550 $appname = empty($ff->appNameShort) ? $ff->project : $ff->project . '-' . $ff->appNameShort;
1552 $dname = method_exists($this, 'getDatabaseConnection') ? $this->getDatabaseConnection()->dsn['database'] : $this->databaseNickname();
1554 $sesPrefix = $appname.'-' .get_class($this) .'-' . $dname;
1559 function loginPublic() // used where???
1561 $this->isAuth(); // force session start..
1563 $db = $this->getDatabaseConnection();
1565 $ff = HTML_FlexyFramework::get();
1567 if(empty($ff->Pman) || empty($ff->Pman['login_public'])){
1571 $sesPrefix = $ff->Pman['login_public'] . '-' .get_class($this) .'-'.$db->dsn['database'] ;
1573 $p = DB_DAtaObject::Factory($this->tableName());
1574 $p->get($this->pid());
1576 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$p->toArray());
1581 function beforeUpdate($old, $q, $roo)
1583 $this->email = trim($this->email);
1586 function generateOathKey()
1588 require 'Base32.php';
1590 $base32 = new Base32();
1592 return $base32->base32_encode(bin2hex(openssl_random_pseudo_bytes(10)));
1595 function generateQRCode($hash)
1598 empty($this->email) &&
1604 $issuer = rawurlencode($this->qrCodeIssuer());
1606 $uri = "otpauth://totp/{$issuer}:{$this->email}?secret={$hash}&issuer={$issuer}&algorithm=SHA1&digits=6&period=30";
1608 require_once 'Image/QRCode.php';
1610 $qrcode = new Image_QRCode();
1612 $image = $qrcode->makeCode($uri, array(
1613 'output_type' => 'return'
1618 $base64 = base64_encode(ob_get_contents());
1621 return "data:image/png;base64,{$base64}";
1624 function qrCodeIssuer()
1626 $pg= HTML_FlexyFramework::get()->page;
1628 $issuer = (empty($pg->company->name)) ? 'ROOJS' : "{$pg->company->name}";
1633 static function test_ADMIN_PASSWORD_RESET($pg, $to)
1635 $ff = HTML_FlexyFramework::get();
1636 $person = DB_DataObject::Factory('core_person');
1640 'HTTP_HOST' => $_SERVER['SERVER_NAME'],
1641 'person' => $person,
1642 'authFrom' => 'FAKE_LINK',
1643 'authKey' => 'FAKE_KEY',
1645 'rcpts' => $to->email,