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 */
56 $p = DB_DataObject::Factory($this->tableName());
57 $p->get($this->owner_id);
66 * FIXME !!!! -- USE Pman_Core_Mailer !!!!!
72 function buildMail($templateFile, $args)
75 $args = (array) $args;
76 $content = clone($this);
78 foreach((array)$args as $k=>$v) {
82 $ff = HTML_FlexyFramework::get();
85 //?? is this really the place for this???
88 empty($args['no_auth']) &&
89 !in_array($templateFile, array(
90 // templates that can be sent without authentication.
96 $content->authUser = $this->getAuthUser();
97 if (!$content->authUser) {
98 return PEAR::raiseError("Not authenticated");
102 // should handle x-forwarded...
104 $content->HTTP_HOST = isset($_SERVER["HTTP_HOST"]) ?
105 $_SERVER["HTTP_HOST"] :
106 (isset($ff->HTTP_HOST) ? $ff->HTTP_HOST : 'localhost');
108 /* use the regex compiler, as it doesnt parse <tags */
111 'compiler' => 'Flexy',
113 'filters' => array('SimpleTags','Mail'),
119 if (!empty($args['templateDir'])) {
120 $tops['templateDir'] = $args['templateDir'];
125 require_once 'HTML/Template/Flexy.php';
126 $template = new HTML_Template_Flexy( $tops );
127 $template->compile("mail/$templateFile.txt");
129 /* use variables from this object to ouput data. */
130 $mailtext = $template->bufferedOutputObject($content);
133 // if a html file with the same name exists, use that as the body
134 // I've no idea where this code went, it was here before..
135 if (false !== $template->resolvePath ( "mail/$templateFile.html" )) {
136 $tops['nonHTML'] = false;
137 $template = new HTML_Template_Flexy( $tops );
138 $template->compile("mail/$templateFile.html");
139 $htmlbody = $template->bufferedOutputObject($content);
145 //echo "<PRE>";print_R($mailtext);
146 //print_R($mailtext);exit;
147 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
148 require_once 'Mail/mimeDecode.php';
149 require_once 'Mail.php';
151 $decoder = new Mail_mimeDecode($mailtext);
152 $parts = $decoder->getSendArray();
154 if (is_a($parts,'PEAR_Error')) {
156 //echo "PROBLEM: {$parts->message}";
159 list($recipents,$headers,$body) = $parts;
160 $recipents = array($this->email);
161 if (!empty($content->bcc) && is_array($content->bcc)) {
162 $recipents =array_merge($recipents, $content->bcc);
164 $headers['Date'] = date('r');
166 if ($htmlbody !== false) {
167 require_once 'Mail/mime.php';
168 $mime = new Mail_mime(array('eol' => "\n"));
169 $mime->setTXTBody($body);
170 $mime->setHTMLBody($htmlbody);
171 // I think there might be code in mediaoutreach toEmail somewhere
172 // h embeds images here..
173 $body = $mime->get();
174 $headers = $mime->headers($headers);
181 'recipients' => $recipents,
182 'headers' => $headers,
192 * - user must be authenticate or args[no_auth] = true
193 * or template = password_[reset|welcome]
196 function sendTemplate($templateFile, $args)
199 $ar = $this->buildMail($templateFile, $args);
202 //print_r($recipents);exit;
203 $mailOptions = PEAR::getStaticProperty('Mail','options');
204 $mail = Mail::factory("SMTP",$mailOptions);
206 if (PEAR::isError($mail)) {
209 $oe = error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT);
210 $ret = $mail->send($ar['recipients'],$ar['headers'],$ar['body']);
211 error_reporting($oe);
220 function getEmailFrom()
222 if (empty($this->name)) {
226 return '"' . addslashes($this->name) . '" <' . $this->email . '>';
229 function toEventString()
231 return empty($this->name) ? $this->email : $this->name;
234 function verifyAuth()
236 $ff= HTML_FlexyFramework::get();
237 if (!empty($ff->Pman['auth_comptype']) &&
238 (!$this->company_id || ($ff->Pman['auth_comptype'] != $this->company()->comptype))
241 $sesPrefix = $this->sesPrefix();
243 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
247 //$ff->page->jerr("Login not permited to outside companies");
254 // ---------------- authentication / passwords and keys stuff ----------------
260 $ff= HTML_FlexyFramework::get();
262 $sesPrefix = $this->sesPrefix();
264 if (!empty($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
266 $a = unserialize($_SESSION[get_class($this)][$sesPrefix .'-auth']);
268 $u = DB_DataObject::factory($this->tableName());
269 if ($a->id && $u->get($a->id)) { //&& strlen($u->passwd)) {
271 return $u->verifyAuth(); // got authentication...
276 unset($_SESSION[get_class($this)][$sesPrefix .'-auth']);
277 unset($_SESSION[get_class($this)][$sesPrefix .'-timeout']);
278 setcookie('Pman.timeout', -1, time() + (30*60), '/');
283 $u = DB_DataObject::factory($this->tableName());
285 if (!empty($_SERVER['PHP_AUTH_USER'])
287 !empty($_SERVER['PHP_AUTH_PW'])
289 $u->get('email', $_SERVER['PHP_AUTH_USER'])
291 $u->checkPassword($_SERVER['PHP_AUTH_PW'])
293 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize($u);
297 if (!$this->canInitializeSystem()) {
298 // die("can not init");
304 $default_admin = false;
305 if (!empty($ff->Pman['local_autoauth']) &&
306 ($ff->Pman['local_autoauth'] === true) &&
307 (!empty($_SERVER['SERVER_ADDR'])) &&
310 $_SERVER['SERVER_ADDR'] == '127.0.0.1' &&
311 $_SERVER['REMOTE_ADDR'] == '127.0.0.1'
315 $_SERVER['SERVER_ADDR'] == '::1' &&
316 $_SERVER['REMOTE_ADDR'] == '::1'
320 $group = DB_DataObject::factory('core_group');
321 $group->get('name', 'Administrators');
323 $member = DB_DataObject::factory('core_group_member');
325 $member->group_id = $group->id;
327 join_user_id_id.id IS NOT NULL
329 if($member->find(true)){
330 $default_admin = DB_DataObject::factory($this->tableName());
331 if(!$default_admin->get($member->user_id)){
332 $default_admin = false;
337 //var_dump($ff->Pman['local_autoauth']); var_dump($_SERVER); exit;
338 $u = DB_DataObject::factory($this->tableName());
339 $ff = HTML_FlexyFramework::get();
341 if (!empty($ff->Pman['local_autoauth']) &&
342 (!empty($_SERVER['SERVER_ADDR'])) &&
345 $_SERVER['SERVER_ADDR'] == '127.0.0.1' &&
346 $_SERVER['REMOTE_ADDR'] == '127.0.0.1'
350 $_SERVER['SERVER_ADDR'] == '::1' &&
351 $_SERVER['REMOTE_ADDR'] == '::1'
354 ($default_admin || $u->get('email', $ff->Pman['local_autoauth']))
357 $user = $default_admin ? $default_admin->toArray() : $u->toArray();
359 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object) $user);
363 //var_dump(session_id());
364 //var_dump($_SESSION[__CLASS__]);
366 //if (!empty( $_SESSION[__CLASS__][$sesPrefix .'-empty'] )) {
369 //die("got this far?");
370 // not in session or not matched...
371 $u = DB_DataObject::factory($this->tableName());
372 $u->whereAdd(' LENGTH(passwd) > 0');
374 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $n;
375 if (class_exists('PEAR')) {
376 $error = PEAR::getStaticProperty('DB_DataObject','lastError');
378 die($error->toString()); // not really a good thing to do...
381 if (!$n){ // authenticated as there are no users in the system...
389 function canInitializeSystem()
392 return !strcasecmp(get_class($this) , __CLASS__);
395 function getAuthUser()
397 if (!$this->isAuth()) {
401 $ff= HTML_FlexyFramework::get();
403 $sesPrefix = $this->sesPrefix();
405 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
407 if (!empty($_SESSION[get_class($this)][$sesPrefix .'-auth'])) {
408 $a = unserialize($_SESSION[get_class($this)][$sesPrefix .'-auth']);
410 $u = DB_DataObject::factory($this->tableName()); // allow extending this ...
412 if ($u->get($a->id)) { /// && strlen($u->passwd)) { // should work out the pid .. really..
414 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
415 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
421 unset($_SESSION[get_class($this)][$sesPrefix .'-auth']);
422 unset($_SESSION[get_class($this)][$sesPrefix .'-timeout']);
423 setcookie('Pman.timeout', -1, time() + (30*60), '/');
429 if (!$this->canInitializeSystem()) {
435 if (empty( $_SESSION[get_class($this)][$sesPrefix .'-empty'] )) {
436 $u = DB_DataObject::factory($this->tableName());
437 $u->whereAdd(' LENGTH(passwd) > 0');
438 $_SESSION[get_class($this)][$sesPrefix .'-empty'] = $u->count();
442 if (isset( $_SESSION[get_class($this)][$sesPrefix .'-empty'] ) && $_SESSION[get_class($this)][$sesPrefix .'-empty'] < 1) {
444 // fake person - open system..
445 //$ce = DB_DataObject::factory('core_enum');
449 $u = DB_DataObject::factory($this->tableName());
452 // if a company has been created fill that in in company_id_id
453 $c = DB_DAtaObject::factory('core_company')->lookupOwner();
455 $u->company_id_id = $c->pid();
456 $u->company_id = $c->pid();
466 $this->isAuth(); // force session start..
467 if (!$this->verifyAuth()) { // check for company valid..
471 // open up iptables at login..
472 $dbname = $this->databaseNickname();
473 touch( '/tmp/run_pman_admin_iptables-'.$dbname);
475 // refresh admin group if we are logged in as one..
476 //DB_DataObject::debugLevel(1);
477 $g = DB_DataObject::factory('core_group');
479 $g->get('name', 'Administrators');
480 $gm = DB_DataObject::Factory('core_group_member');
481 if (in_array($g->id,$gm->listGroupMembership($this))) {
482 // refresh admin groups.
483 $gr = DB_DataObject::Factory('core_group_right');
484 $gr->applyDefs($g, 0);
487 $sesPrefix = $this->sesPrefix();
489 // we should not store the whole data in the session - otherwise it get's huge.
490 $p = DB_DAtaObject::Factory($this->tableName());
491 $p->get($this->pid());
495 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = time() + (30*60); // eg. 30 minutes
496 setcookie('Pman.timeout', time() + (30*60), time() + (30*60), '/');
498 //var_dump(array(get_class($this),$sesPrefix .'-auth'));
499 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$d);
500 // ensure it's written so that ajax calls can fetch it..
507 $this->isAuth(); // force session start..
509 $sesPrefix = $this->sesPrefix();
511 $_SESSION[get_class($this)][$sesPrefix .'-auth-timeout'] = -1;
513 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = "";
516 function genPassKey ($t)
518 return md5($this->email . $t. $this->passwd);
520 function simpleAuthKey($m = 0)
522 $month = $m > -1 ? date('Y-m') : date('Y-m', strtotime('LAST MONTH'));
524 return md5(implode(',' , array($month, $this->email , $this->passwd, $this->id)));
527 function checkTwoFactorAuthentication($val)
529 require_once 'System.php';
531 $oathtool = System::which('oathtool');
537 $cmd = "{$oathtool} --totp --base32 {$this->oath_key}";
539 $password = exec($cmd);
541 return ($password == $val) ? true : false;
544 function checkPassword($val)
546 if (substr($this->passwd,0,1) == '$') {
547 if (function_exists('pasword_verify')) {
548 return password_verify($val, $this->passwd);
550 return crypt($val,$this->passwd) == $this->passwd ;
552 // old style md5 passwords...- cant be used with courier....
553 return md5($val) == $this->passwd;
556 function setPassword($value)
558 if (function_exists('pasword_hash')) {
559 return password_hash($value);
563 while(strlen($salt)<9) {
564 $salt.=chr(rand(64,126));
565 //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
567 $this->passwd = crypt($value, '$1$'. $salt. '$');
572 function generatePassword($length = 5) // genearte a password (add set 'rawPasswd' to it's value)
574 require_once 'Text/Password.php';
575 $this->rawPasswd = strtr(ucfirst(Text_Password::create($length)).ucfirst(Text_Password::create($length)), array(
576 "a"=>"4", "e"=>"3", "i"=>"1", "o"=>"0", "s"=>"5", "t"=>"7"));
577 $this->setPassword($this->rawPasswd);
578 return $this->rawPasswd;
583 $x = DB_DataObject::factory('core_company');
585 $x->get($this->company_id);
588 function loadCompany()
590 $this->company = $this->company();
595 return $this->active;
597 function authUserName($n) // set username prior to acheck user exists query.
600 $this->whereAdd('LENGTH(passwd) > 1');
605 if (!func_num_args()) {
608 $val = array_shift(func_get_args());
609 if ($val == $this->lang) {
619 function authUserArray()
622 $aur = $this->toArray();
629 //DB_DataObject::debugLevel(1);
630 $c = DB_Dataobject::factory('core_company');
631 $im = DB_Dataobject::factory('Images');
632 $c->joinAdd($im, 'LEFT');
634 $c->selectAs($c, 'company_id_%s');
635 $c->selectAs($im, 'company_id_logo_id_%s');
636 $c->id = $this->company_id;
640 $aur = array_merge( $c->toArray(),$aur);
642 if (empty($c->company_id_logo_id_id)) {
644 $im = DB_Dataobject::factory('Images');
645 $im->ontable = DB_DataObject::factory('core_company')->tableName();
647 $im->imgtype = 'LOGO';
650 $im->selectAs($im, 'company_id_logo_id_%s');
651 if ($im->find(true)) {
653 foreach($im->toArray() as $k=>$v) {
660 $aur['perms'] = $this->getPerms();
661 $g = DB_DataObject::Factory('core_group_member');
662 $aur['groups'] = $g->listGroupMembership($this, 'name');
665 $aur['dailykey'] = '';
666 $aur['oath_key'] = '';
672 // ----------PERMS------ ----------------
675 //DB_DataObject::debugLevel(1);
676 // find out all the groups they are a member of.. + Default..
678 // ------ INIITIALIZE IF NO GROUPS ARE SET UP.
680 $g = DB_DataObject::Factory('core_group_right');
686 return $g->adminRights(); // system is not set up - so they get full rights.
688 //DB_DataObject::debugLevel(1);
689 $g = DB_DataObject::Factory('core_group_member');
690 $g->whereAdd('group_id is NOT NULL AND user_id IS NOT NULL');
692 // add the current user to the admin group..
693 $g = DB_DataObject::Factory('core_group');
694 if ($g->get('name', 'Administrators')) {
695 $gm = DB_DataObject::Factory('core_group_member');
696 $gm->group_id = $g->id;
697 $gm->user_id = $this->id;
703 // ------ STANDARD PERMISSION HANDLING.
704 $isOwner = $this->company()->comptype == 'OWNER';
705 $g = DB_DataObject::Factory('core_group_member');
706 $grps = $g->listGroupMembership($this);
708 $isAdmin = $g->inAdmin; //??? what???
709 //echo '<PRE>'; print_r($grps);var_dump($isAdmin);
710 // the load all the perms for those groups, and add them all together..
711 // then load all those
712 $g = DB_DataObject::Factory('core_group_right');
713 $ret = $g->listPermsFromGroupIds($grps, $isAdmin, $isOwner);
714 //echo '<PRE>';print_r($ret);
720 *Basic group fetching - probably needs to filter by type eventually.
722 *@param String $what - fetchall() argument - eg. 'name' returns names of all groups that they are members of.
725 function groups($what=false)
727 $g = DB_DataObject::Factory('core_group_member');
728 $grps = $g->listGroupMembership($this);
729 $g = DB_DataObject::Factory('core_group');
730 $g->whereAddIn('id', $grps, 'int');
731 return $g->fetchAll($what);
737 function hasPerm($name, $lvl)
739 static $pcache = array();
741 if (!isset($pcache[$this->id])) {
742 $pcache[$this->id] = $this->getPerms();
745 // echo "<PRE>";print_r($pcache[$au->id]);
746 // var_dump($pcache[$au->id]);
747 if (empty($pcache[$this->id][$name])) {
751 return strpos($pcache[$this->id][$name], $lvl) > -1;
755 // ------------ROO HOOKS------------------------------------
756 function applyFilters($q, $au, $roo)
758 //DB_DataObject::DebugLevel(1);
760 if (!empty($q['query']['is_owner'])) {
761 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
764 if (!empty($q['query']['person_not_internal'])) {
765 $this->whereAdd(" join_company_id_id.isOwner = 0 ");
768 if (!empty($q['query']['person_internal_only_all'])) {
771 // must be internal and not current user (need for distribution list)
772 // user has a projectdirectory entry and role is not blank.
773 //DB_DataObject::DebugLevel(1);
774 $pd = DB_DataObject::factory('ProjectDirectory');
775 $pd->whereAdd("role != ''");
777 $pd->selectAdd('distinct(person_id) as person_id');
778 $roled = $pd->fetchAll('person_id');
780 {$this->tableName()}.id IN (".implode(',', $roled) . ")
782 $this->whereAdd(" join_company_id_id.comptype = 'OWNER' $rs ");
785 // -- for distribution
786 if (!empty($q['query']['person_internal_only'])) {
787 // must be internal and not current user (need for distribution list)
788 $this->whereAdd(" join_company_id_id.comptype = 'OWNER'");
790 //$this->whereAdd(($this->tableName() == 'Person' ? 'Person' : "join_person_id_id") .
791 // ".id != ".$au->id);
792 $this->whereAdd("{$this->tableName()}.id != {$au->id}");
795 if (!empty($q['query']['comptype_or_company_id'])) {
796 // DB_DataObject::debugLevel(1);
797 $bits = explode(',', $q['query']['comptype_or_company_id']);
798 $id = (int) array_pop($bits);
799 $ct = $this->escape($bits[0]);
801 $this->whereAdd(" join_company_id_id.comptype = '$ct' OR {$this->tableName()}.company_id = $id");
807 if (!empty($q['query']['person_inactive'])) {
808 // DB_Dataobject::debugLevel(1);
811 $tn_p = $this->tableName();
812 $tn_gm = DB_DataObject::Factory('core_group_member')->tableName();
813 $tn_g = DB_DataObject::Factory('core_group')->tableName();
815 ///---------------- Group views --------
816 if (!empty($q['query']['in_group'])) {
817 // DB_DataObject::debugLevel(1);
818 $ing = (int) $q['query']['in_group'];
819 if ($q['query']['in_group'] == -1) {
821 // list all staff who are not in a group.
822 $this->whereAdd("{$this->tableName()}.id NOT IN (
823 SELECT distinct(user_id) FROM $tn_gm LEFT JOIN
824 $tn_g ON $tn_g.id = $tn_gm.group_id
825 WHERE $tn_g.type = ".$q['query']['type']."
831 $this->whereAdd("$tn_p.id IN (
832 SELECT distinct(user_id) FROM $tn_gm
833 WHERE group_id = $ing
839 if(!empty($q['in_group_name'])){
841 $v = $this->escape($q['in_group_name']);
846 DISTINCT(user_id) FROM $tn_gm
850 $tn_g.id = $tn_gm.group_id
857 // #2307 Search Country!!
858 if (!empty($q['query']['in_country'])) {
859 // DB_DataObject::debugLevel(1);
860 $inc = $q['query']['in_country'];
861 $this->whereAdd("$tn_p.countries LIKE '%{$inc}%'");
864 if (!empty($q['query']['not_in_directory'])) {
865 // it's a Person list..
866 // DB_DATaobjecT::debugLevel(1);
868 // specific to project directory which is single comp. login
870 $owncomp = DB_DataObject::Factory('core_company');
871 $owncomp->get('comptype', 'OWNER');
872 if ($q['company_id'] == $owncomp->id) {
878 if ( $q['query']['not_in_directory'] > -1) {
879 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
880 // can list current - so that it does not break!!!
881 $this->whereAdd("$tn_p.id NOT IN
882 ( SELECT distinct person_id FROM $tn_pd WHERE
883 project_id = " . $q['query']['not_in_directory'] . " AND
884 company_id = " . $this->company_id . ')');
888 if (!empty($q['query']['role'])) {
889 // it's a Person list..
890 // DB_DATaobjecT::debugLevel(1);
892 // specific to project directory which is single comp. login
894 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
895 // can list current - so that it does not break!!!
896 $this->whereAdd("$tn_p.id IN
897 ( SELECT distinct person_id FROM $tn_pd WHERE
898 role = '". $this->escape($q['query']['role']) ."'
904 if (!empty($q['query']['project_member_of'])) {
905 // this is also a flag to return if they are a member..
906 //DB_DataObject::debugLevel(1);
907 $do = DB_DataObject::factory('ProjectDirectory');
908 $do->project_id = $q['query']['project_member_of'];
909 $tn_pd = DB_DataObject::Factory('ProjectDirectory')->tableName();
910 $this->joinAdd($do,array('joinType' => 'LEFT', 'useWhereAsOn' => true));
911 $this->selectAdd("IF($tn_pd.id IS NULL, 0, $tn_pd.id ) as is_member");
914 if (!empty($q['query']['project_member_filter'])) {
915 $this->having('is_member !=0');
921 if(!empty($q['query']['name'])){
923 {$this->tableName()}.name LIKE '%{$this->escape($q['query']['name'])}%'
926 if(!empty($q['query']['name_starts'])){
928 {$this->tableName()}.name LIKE '{$this->escape($q['query']['name_starts'])}%'
932 if (!empty($q['query']['search'])) {
934 // use our magic search builder...
936 require_once 'Text/SearchParser.php';
937 $x = new Text_SearchParser($q['query']['search']);
945 "join_company_id_id.name"
947 $tbcols = $this->table();
948 foreach(array('firstname','lastname') as $k) {
949 if (isset($tbcols[$k])) {
950 $props[] = "{$tn_p}.{$k}";
957 $str = $x->toSQL(array(
960 'company' => 'join_company_id_id.name',
961 //'country' => 'Clipping.country',
962 // 'media' => 'Clipping.media_name',
964 'escape' => array($this->getDatabaseConnection(), 'escapeSimple'), /// pear db or mdb object..
969 $this->whereAdd($str); /*
970 $tn_p.name LIKE '%$s%' OR
971 $tn_p.email LIKE '%$s%' OR
972 $tn_p.role LIKE '%$s%' OR
973 $tn_p.phone LIKE '%$s%' OR
974 $tn_p.remarks LIKE '%$s%'
979 // project directory rules -- this may distrupt things.
980 $p = DB_DataObject::factory('ProjectDirectory');
981 // if project directories are set up, then we can apply project query rules..
984 $pids = $p->projects($au);
985 if (isset($q['query']['project_id'])) {
986 $pid = (int)$q['query']['project_id'];
987 if (!in_array($pid, $pids)) {
988 $roo->jerr("Project not in users valid projects");
993 //if (empty($q['_anyrole'])) { // should be project_directry_role
994 // $p->whereAdd("{$p->tableName()}.role != ''");
996 if (!empty($q['query']['role'])) { // should be project_directry_role
997 $role = $this->escape($q['query']['role']);
999 $p->whereAdd("{$p->tableName()}.role LIKE '%{$role}%'");
1003 if (!$roo->hasPerm('Core.Projects_All', 'S')) {
1004 $peps = $p->people($pids);
1005 $this->whereAddIn("{$tn}.id", $peps, 'int');
1009 // fixme - this needs a more generic fix - it was from the mtrack_person code...
1010 if (isset($q['query']['ticket_id'])) {
1011 // find out what state the ticket is in.
1012 $t = DB_DataObject::Factory('mtrack_ticket');
1014 $t->get($q['query']['ticket_id']);
1016 if (!$this->checkPerm('S', $au)) {
1017 $roo->jerr("permssion denied to query state of ticket");
1020 $p = DB_DataObject::factory('ProjectDirectory');
1021 $pids = array($t->project_id);
1023 $peps = $p->people($pids);
1025 $this->whereAddIn($this->tableName().'.id', $peps, 'int');
1027 //$this->whereAdd('join_prole != ''");
1032 * Seems we never expose oath_key / passwd, so...
1035 if($this->tableName() == 'core_person'){
1036 $this->_extra_cols = array('length_passwd', 'length_oath_key');
1039 LENGTH({$this->tableName()}.passwd) AS length_passwd,
1040 LENGTH({$this->tableName()}.oath_key) AS length_oath_key
1046 function setFromRoo($ar, $roo)
1048 $this->setFrom($ar);
1050 if(!empty($ar['_enable_oath_key'])){
1051 $this->generateOathKey();
1054 if (!empty($ar['passwd1'])) {
1055 $this->setPassword($ar['passwd1']);
1059 ($this->email == $roo->old->email)&&
1060 ($this->company_id == $roo->old->company_id)
1064 if (empty($this->email)) {
1067 // this only applies to our owner company..
1068 $c = $this->company();
1069 if (empty($c->comptype_name) || $c->comptype_name != 'OWNER') {
1074 $xx = DB_Dataobject::factory($this->tableName());
1076 'email' => $this->email,
1077 // 'company_id' => $x->company_id
1081 return "Duplicate Email found";
1088 * before Delete - delete significant dependancies..
1089 * this is called after checkPerm..
1092 function beforeDelete($dependants_array, $roo)
1095 $e = DB_DataObject::Factory('Events');
1096 $e->whereAdd('person_id = ' . $this->id);
1105 * Check if the a user has access to modify this item.
1106 * @param String $lvl Level (eg. Core.Projects)
1107 * @param Pman_Core_DataObjects_Person $au The authenticated user.
1108 * @param boolean $changes alllow changes???
1110 * @return false if no access..
1112 function checkPerm($lvl, $au, $changes=false) //heck who is trying to access this. false == access denied..
1115 // do we have an empty system..
1116 if ($au && $au->id == -1) {
1119 // if not authenticated... do not allow in???
1124 // determine if it's staff!!!
1125 $owncomp = DB_DataObject::Factory('core_company');
1126 $owncomp->get('comptype', 'OWNER');
1127 $isStaff = ($au->company_id == $owncomp->id);
1132 // - can not change company!!!
1134 isset($changes['company_id']) &&
1135 $changes['company_id'] != $au->company_id) {
1138 // can only set new emails..
1140 !empty($this->email) &&
1141 isset($changes['email']) &&
1142 $changes['email'] != $this->email) {
1147 // mtrack had the idea that all 'S' should be allowed.. - but filtered later..
1148 // ???? do we want this?
1150 // edit self... - what about other staff members...
1152 //return $this->company_id == $au->company_id;
1156 // yes, only owner company can mess with this...
1162 // extra case change passwod?
1163 case 'P': //??? password
1164 // standard perms -- for editing + if the user is dowing them selves..
1165 $ret = $isStaff ? $au->hasPerm("Core.Staff", "E") : $au->hasPerm("Core.Person", "E");
1166 return $ret || $au->id == $this->id;
1169 return $isStaff ? $au->hasPerm("Core.Staff", $lvl) : $au->hasPerm("Core.Person", $lvl);
1175 function beforeInsert($req, $roo)
1177 $p = DB_DataObject::factory('core_person');
1178 if ($roo->authUser->id > -1 || $p->count() > 1) {
1181 $c = DB_DAtaObject::Factory('core_company');
1183 if (!$tc || $tc> 1) {
1184 $roo->jerr("can not create initial user as multiple companies already exist");
1187 $this->company_id = $c->id;
1191 function onInsert($req, $roo)
1194 $p = DB_DataObject::factory('core_person');
1195 if ($roo->authUser->id < 0 && $p->count() == 1) {
1196 // this seems a bit risky...
1198 $g = DB_DataObject::factory('core_group');
1202 $g->get('name', 'Administrators');
1204 $p = DB_DataObject::factory('core_group_member');
1205 $p->group_id = $g->id;
1206 $p->user_id = $this->id;
1209 $roo->addEvent("ADD", $p, $g->toEventString(). " Added " . $this->toEventString());
1213 if (!empty($req['project_id_addto'])) {
1214 $pd = DB_DataObject::factory('ProjectDirectory');
1215 $pd->project_id = $req['project_id_addto'];
1216 $pd->person_id = $this->id;
1218 $pd->office_id = $this->office_id;
1219 $pd->company_id = $this->company_id;
1225 function importFromArray($roo, $persons, $opts)
1227 if (empty($opts['prefix'])) {
1228 $roo->jerr("opts[prefix] is empty - you can not just create passwords based on the user names");
1231 if (!is_array($persons) || empty($persons)) {
1232 $roo->jerr("error in the person data. - empty on not valid");
1234 DB_DataObject::factory('core_group')->initGroups();
1236 foreach($persons as $person){
1237 $p = DB_DataObject::factory('core_person');
1238 if($p->get('name', $person['name'])){
1241 $p->setFrom($person);
1243 $companies = DB_DataObject::factory('core_company');
1244 if(!$companies->get('comptype', 'OWNER')){
1245 $roo->jerr("Missing OWNER companies!");
1247 $p->company_id = $companies->pid();
1248 // strip the 'spaces etc.. make lowercase..
1249 $name = strtolower(str_replace(' ', '', $person['name']));
1250 $p->setPassword("{$opts['prefix']}{$name}");
1253 // if $person->groups is set.. then
1254 // add this person to that group eg. groups : [ 'Administrator' ]
1255 if(!empty($person['groups'])){
1256 $groups = DB_DataObject::factory('core_group');
1257 if(!$groups->get('name', $person['groups'])){
1258 $roo->jerr("Missing groups : {$person['groups']}");
1260 $gm = DB_DataObject::factory('core_group_member');
1261 $gm->change($p, $groups, true);
1264 $p->onInsert(array(), $roo);
1268 // this is for the To: "{getEmailName()}" <email@address>
1269 // not good for Dear XXXX, - use {person.firstname} for that.
1270 function getEmailName()
1274 if(!empty($this->honor)){
1275 array_push($name, $this->honor);
1278 if(!empty($this->name)){
1279 array_push($name, $this->name);
1281 return implode(' ', $name);
1284 if(!empty($this->firstname) || !empty($this->lastname)){
1285 array_push($name, $this->firstname);
1286 array_push($name, $this->lastname);
1288 $name = array_filter($name);
1290 return implode(' ', $name);
1293 return $this->email;
1296 function sesPrefix()
1298 $ff= HTML_FlexyFramework::get();
1300 $appname = empty($ff->appNameShort) ? $ff->project : $ff->project . '-' . $ff->appNameShort;
1302 $dname = method_exists($this, 'getDatabaseConnection') ? $this->getDatabaseConnection()->dsn['database'] : $this->databaseNickname();
1304 $sesPrefix = $appname.'-' .get_class($this) .'-' . $dname;
1309 function loginPublic()
1311 $this->isAuth(); // force session start..
1313 $db = $this->getDatabaseConnection();
1315 $ff = HTML_FlexyFramework::get();
1317 if(empty($ff->Pman) || empty($ff->Pman['login_public'])){
1321 $sesPrefix = $ff->Pman['login_public'] . '-' .get_class($this) .'-'.$db->dsn['database'] ;
1323 $p = DB_DAtaObject::Factory($this->tableName());
1324 $p->get($this->pid());
1326 $_SESSION[get_class($this)][$sesPrefix .'-auth'] = serialize((object)$p->toArray());
1331 function beforeUpdate($old, $q, $roo)
1333 if(!empty($q['_generate_oath_key'])){
1335 $this->generateOathKey();
1340 if(!empty($q['_to_qr_code'])){
1341 $qrcode = $this->generateQRCode();
1344 $roo->jerr('Fail to generate QR Code');
1347 $roo->jdata($qrcode);
1351 function generateOathKey()
1353 $hex = bin2hex(openssl_random_pseudo_bytes(10));
1355 require 'Base32.php';
1357 $base32 = new Base32();
1359 $this->oath_key = $base32->base32_encode($hex);
1361 return $this->oath_key;
1365 function generateQRCode()
1367 if(empty($this->oath_key)){
1371 $issuer = (empty($this->name)) ? rawurlencode('ROOJS') : rawurlencode($this->name);
1373 $uri = "otpauth://totp/{$issuer}:{$this->email}?secret={$this->oath_key}&issuer={$issuer}&algorithm=SHA1&digits=6&period=30";
1375 require_once 'Image/QRCode.php';
1377 $qrcode = new Image_QRCode();
1379 $image = $qrcode->makeCode($uri, array(
1380 'output_type' => 'return'
1385 $base64 = base64_encode(ob_get_contents());
1388 return "data:image/png;base64,{$base64}";