6 * - base application setup (variables etc to javascript)
8 * - authentication and permission info about user / application
9 * - json output methods.
10 * - file upload error checking - checkFileUploadError
11 * - logging to event table
12 * - sendTemplate code (normally use the Person version for sending to specific people..)
14 * - doc managment code?? - remarks and tracking??? - MOVEME
15 * - authentication link checking?? MOVEME?
16 * - authentication reset password ?? MOVEME?
17 * ?? arrayClean.. what's it doing here?!? ;)
22 class Pman extends HTML_FlexyFramework_Page
25 var $appShortName= "";
26 var $appVersion = "1.8";
38 * ------------- Standard getAuth/get/post methods of framework.
43 function getAuth() // everyone allowed in!!!!!
45 $this->loadOwnerCompany();
53 if (isset($this->_hasInit)) {
57 $this->_hasInit = true;
59 if (method_exists('HTML_FlexyFramework', 'get')) {
61 $boot = HTML_FlexyFramework::get();
62 // echo'<PRE>';print_R($boot);exit;
63 $this->appName= $boot->appName;
64 $this->appNameShort= $boot->appNameShort;
65 $this->appModules= $boot->enable;
66 $this->isDev = true; //empty($opts['isDev']) ? '' : $opts['isDev'];
67 $this->appDisable = $boot->disable;
68 $this->version = $boot->version;
73 $opts = PEAR::getStaticProperty('Pman', 'options');
75 $this->isDev = true; //empty($opts['isDev']) ? '' : $opts['isDev'];
77 $this->appName= empty($opts['appName']) ? '' : $opts['appName'];
78 $this->appNameShort= empty($opts['appNameShort']) ? '' : $opts['appNameShort'];
79 $this->appModules= $opts['enable'];
80 $this->appDisable = $opts['disable'];
81 $this->version = isset($opts['version']) ? $this->version : $opts['version'];
89 //$this->allowSignup= empty($opts['allowSignup']) ? 0 : 1;
90 $bits = explode('/', $base);
92 if ($bits[0] == 'Link') {
93 $this->linkFail = $this->linkAuth(@$bits[1],@$bits[2]);
94 header('Content-type: text/html; charset=utf-8');
97 if ($bits[0] == 'PasswordReset') {
98 $this->linkFail = $this->resetPassword(@$bits[1],@$bits[2],@$bits[3]);
99 header('Content-type: text/html; charset=utf-8');
104 if ($this->getAuthUser()) {
105 $this->addEvent("RELOAD");
110 $this->addEvent("BADURL", false, $base);
111 $this->jerr("invalid url");
114 if (isset($_GET['onloadTrack'])) {
115 $this->onloadTrack = (int)$_GET['onloadTrack'];
117 // getting this to work with xhtml is a nightmare
118 // = nbsp / <img> issues screw everyting up.
120 //header('Content-type: application/xhtml+xml; charset=utf-8');
121 header('Content-type: text/html; charset=utf-8');
124 function post($base) {
125 return $this->get($base);
129 * ------------- Authentication and permission info about logged in user!!!
134 function loadOwnerCompany()
136 $this->company = DB_DataObject::Factory('Companies');
137 $this->company->get('comptype', 'OWNER');
140 function staticGetAuthUser()
142 $u = DB_DataObject::factory('Person');
146 return $u->getAuthUser();
148 function getAuthUser()
150 if (!empty($this->authUser)) {
151 return $this->authUser;
154 $u = DB_DataObject::factory('Person');
158 $this->authUser =$u->getAuthUser();
159 return $this->authUser ;
161 function hasPerm($name, $lvl) // do we have a permission
163 static $pcache = array();
164 $au = $this->getAuthUser();
165 return $au->hasPerm($name,$lvl);
168 function hasModule($name)
171 if (!strpos( $name,'.') ) {
172 // use enable / disable..
175 $enabled = array('Core') ;
176 $enabled = !empty($this->appModules) ?
177 array_merge($enabled, explode(',', $this->appModules)) :
179 $disabled = explode(',', $this->appDisable ? $this->appDisable: '');
183 return in_array($name, $enabled) && !in_array($name, $disabled);
186 $x = DB_DataObject::factory('Group_Rights');
187 $ar = $x->defaultPermData();
188 if (empty($ar[$name]) || empty($ar[$name][0])) {
198 * ---------------- Global Tools ---------------
204 * send a template to the user
205 * rcpts are read from the resulting template.
207 * @arg $templateFile - the file in mail/XXXXXX.txt
208 * @arg $args - variables available to the form as {t.*} over and above 'this'
213 function sendTemplate($templateFile, $args)
218 $content = clone($this);
220 foreach((array)$args as $k=>$v) {
223 $content->msgid = md5(time() . rand());
225 $content->HTTP_HOST = $_SERVER["HTTP_HOST"];
226 /* use the regex compiler, as it doesnt parse <tags */
227 require_once 'HTML/Template/Flexy.php';
228 $template = new HTML_Template_Flexy( array(
229 'compiler' => 'Regex',
230 'filters' => array('SimpleTags','Mail'),
234 // this should be done by having multiple template sources...!!!
236 $template->compile('mail/'. $templateFile.'.txt');
238 /* use variables from this object to ouput data. */
239 $mailtext = $template->bufferedOutputObject($content);
240 //echo "<PRE>";print_R($mailtext);
242 /* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
243 require_once 'Mail/mimeDecode.php';
244 require_once 'Mail.php';
246 $decoder = new Mail_mimeDecode($mailtext);
247 $parts = $decoder->getSendArray();
248 if (PEAR::isError($parts)) {
250 //echo "PROBLEM: {$parts->message}";
253 list($recipents,$headers,$body) = $parts;
254 ///$recipents = array($this->email);
255 $mailOptions = PEAR::getStaticProperty('Mail','options');
256 $mail = Mail::factory("SMTP",$mailOptions);
257 $headers['Date'] = date('r');
258 if (PEAR::isError($mail)) {
261 $oe = error_reporting(E_ALL ^ E_NOTICE);
262 $ret = $mail->send($recipents,$headers,$body);
263 error_reporting($oe);
269 function checkFileUploadError() // check for file upload errors.
272 empty($_FILES['File'])
273 || empty($_FILES['File']['name'])
274 || empty($_FILES['File']['tmp_name'])
275 || empty($_FILES['File']['type'])
276 || !empty($_FILES['File']['error'])
277 || empty($_FILES['File']['size'])
279 $this->jerr("File upload error: <PRE>" . print_r($_FILES,true) . print_r($_POST,true) . "</PRE>");
285 * generate a tempory file with an extension (dont forget to delete it)
288 function tempName($ext)
290 $x = tempnam(ini_get('session.save_path'), HTML_FlexyFramework::get()->appNameShort.'TMP');
292 return $x .'.'. $ext;
295 * ------------- Authentication testing ------ ??? MOVEME?
299 function linkAuth($trid, $trkey)
301 $tr = DB_DataObject::factory('Documents_Tracking');
302 if (!$tr->get($trid)) {
303 return "Invalid URL";
305 if (strtolower($tr->authkey) != strtolower($trkey)) {
306 $this->AddEvent("ERROR-L", false, "Invalid Key");
307 return "Invalid KEY";
310 $this->onloadTrack = (int) $tr->doc_id;
311 if (strtotime($tr->date_sent) < strtotime("NOW - 14 DAYS")) {
312 $this->AddEvent("ERROR-L", false, "Key Expired");
313 return "Key Expired";
315 // user logged in and not
316 $au = $this->getAuthUser();
317 if ($au && $au->id && $au->id != $tr->person_id) {
320 return "Logged Out existing Session\n - reload to log in with correct key";
322 if ($au) { // logged in anyway..
323 $this->AddEvent("LOGIN", false, "With Key (ALREADY)");
324 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
329 // authenticate the user...
331 $u = DB_DataObject::factory('Person');
333 $u->get($tr->person_id);
335 $this->AddEvent("LOGIN", false, "With Key");
337 // we need to redirect out - otherwise refererer url will include key!
338 header('Location: ' . $this->baseURL.'?onloadTrack='.$this->onloadTrack);
350 * ------------- Authentication password reset ------ ??? MOVEME?
356 function resetPassword($id,$t, $key)
359 $au = $this->getAuthUser();
361 return "Already Logged in - no need to use Password Reset";
364 $u = DB_DataObject::factory('Person');
365 //$u->company_id = $this->company->id;
367 if (!$u->get($id) || !strlen($u->passwd)) {
372 if ($key != $u->genPassKey($t)) {
373 return "invalid key";
376 $u->no_reset_sent = 0;
379 if ($t < strtotime("NOW - 1 DAY")) {
382 $this->showNewPass = implode("/", array($id,$t,$key));
388 * ---------------- Standard JSON outputers. - used everywhere
391 function jerr($str, $errors=array()) // standard error reporting..
393 require_once 'Services/JSON.php';
394 $json = new Services_JSON();
396 if (!empty($_REQUEST['returnHTML']) ||
397 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
399 header('Content-type: text/html');
400 echo "<HTML><HEAD></HEAD><BODY>";
401 echo $json->encodeUnsafe(array(
404 'message' => $str, // compate with exeption / loadexception.
406 'errors' => $errors ? $errors : true, // used by forms to flag errors.
407 'authFailure' => !empty($errors['authFailure']),
409 echo "</BODY></HTML>";
413 echo $json->encode(array(
417 'message' => $str, // compate with exeption / loadexception.
418 'errors' => $errors ? $errors : true, // used by forms to flag errors.
419 'authFailure' => !empty($errors['authFailure']),
427 require_once 'Services/JSON.php';
428 $json = new Services_JSON();
430 if (!empty($_REQUEST['returnHTML']) ||
431 (isset($_SERVER['CONTENT_TYPE']) && preg_match('#multipart/form-data#i', $_SERVER['CONTENT_TYPE']))
434 header('Content-type: text/html');
435 echo "<HTML><HEAD></HEAD><BODY>";
436 echo $json->encodeUnsafe(array('success'=> true, 'data' => $str));
437 echo "</BODY></HTML>";
442 echo $json->encode(array('success'=> true, 'data' => $str));
446 function jdata($ar,$total=false, $extra=array())
448 // should do mobile checking???
449 if ($total == false) {
452 $extra= $extra ? $extra : array();
453 require_once 'Services/JSON.php';
454 $json = new Services_JSON();
455 echo $json->encode(array('success' => true, 'total'=> $total, 'data' => $ar) + $extra);
465 * ---------------- Page output?!?!?
469 function hasBg($fn) // used on front page to check if logos exist..
471 return file_exists($this->rootDir.'/Pman/'.$this->appNameShort.'/templates/images/'. $fn);
474 function outputJavascriptIncludes() // includes on devel version..
477 $mods = explode(',', $this->appModules);
478 array_unshift($mods, 'Core');
479 $mods = array_unique($mods);
481 foreach($mods as $mod) {
482 // add the css file..
484 $files = $this->moduleJavascriptList($mod.'/widgets');
485 foreach($files as $f) {
486 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
489 $files = $this->moduleJavascriptList($mod);
490 foreach($files as $f) {
491 echo '<script type="text/javascript" src="'. $f. '"></script>'."\n";
498 function outputCSSIncludes() // includes on CSS links.
501 $mods = explode(',', $this->appModules);
502 array_unshift($mods, 'Core');
503 $mods = array_unique($mods);
505 foreach($mods as $mod) {
506 // add the css file..
507 $css = $this->rootDir.'/Pman/'.$mod.'/'.strtolower($mod).'.css';
508 if (file_exists( $css)){
509 $css = $this->rootURL .'/Pman/'.$mod.'/'.strtolower($mod).'.css';
510 echo '<link rel="stylesheet" type="text/css" href="'.$css.'" />'."\n";
521 function moduleJavascriptList($mod)
523 $dir = $this->rootDir.'/Pman/'. $mod;
525 $path = $this->rootURL."/Pman/$mod/";
526 $base = dirname($_SERVER['SCRIPT_FILENAME']);
527 $cfile = realpath($base .'/_compiled_/' . $mod . '.js');
528 $lfile = realpath($base .'/_translations_/' . $mod . '.js');
530 if (!file_exists($dir)) {
536 if (file_exists($cfile)) {
537 // $ctime = max(filemtime($cfile), filectime($cfile));
538 // otherwise use compile dfile..
539 $files = array( $this->rootURL."/_compiled_/". basename($cfile));
540 if (file_exists($lfile)) {
541 array_push($files, $this->rootURL."/_translations_/$mod.js");
545 // works out if stuff has been updated..
546 // technically the non-dev version should output compiled only?!!?
547 while (false !== ($f = readdir($dh))) {
548 if (!preg_match('/\.js$/', $f)) {
551 // got the 'module file..'
553 $maxtime = max(filemtime($dir . '/'. $f), $maxtime);
554 $files[] = $path . $f;
556 // var_dump(array($maxtime , $ctime));
557 //if ($maxtime > $ctime) {
558 $lsort = create_function('$a,$b','return strlen($a) > strlen($b) ? 1 : -1;');
559 usort($files, $lsort);
560 // if (file_exists($lfile)) {
561 // array_unshift($files, $this->rootURL."/_translations_/$mod.js");
571 * ---------------- Logging ---------------
578 function addEvent($act, $obj = false, $remarks = '') {
579 $au = $this->getAuthUser();
580 $e = DB_DataObject::factory('Events');
581 $e->person_name = $au ? $au->name : '';
582 $e->person_id = $au ? $au->id : '';
583 $e->event_when = date('Y-m-d H:i:s');
584 $e->ipaddr = $_SERVER["REMOTE_ADDR"];
586 $e->on_table = $obj ? $obj->tableName() : '';
587 $e->on_id = $obj ? $obj->id : 0;
588 $e->remarks = $remarks;