DataObjects/Core_company.php
[Pman.Core] / DataObjects / Core_company.php
1 <?php
2 /**
3  * Table Definition for Companies
4  */
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
6
7 class Pman_Core_DataObjects_Core_Company extends DB_DataObject 
8 {
9     ###START_AUTOCODE
10     /* the code below is auto generated do not remove the above tag */
11
12     public $__table = 'core_company';                       // table name
13     public $code;                            // string(32)  not_null
14     public $name;                            // string(128)  
15     public $remarks;                         // blob(65535)  blob
16     public $owner_id;                        // int(11)  not_null
17     public $address;                         // blob(65535)  blob
18     public $tel;                             // string(32)  
19     public $fax;                             // string(32)  
20     public $email;                           // string(128)  
21     public $id;                              // int(11)  not_null primary_key auto_increment
22     public $isOwner;                         // int(11)  
23     public $logo_id;                         // int(11)  not_null
24     public $background_color;                // string(8)  not_null
25     public $comptype;                        // string(8)  not_null
26     public $url;                             // string(254)  not_null
27     public $main_office_id;                  // int(11)  not_null
28     public $created_by;                      // int(11)  not_null
29     public $created_dt;                      // datetime(19)  not_null binary
30     public $updated_by;                      // int(11)  not_null
31     public $updated_dt;                      // datetime(19)  not_null binary
32     public $passwd;                          // string(64)  not_null
33     public $dispatch_port;                   // string(255)  not_null
34     public $province;                        // string(255)  not_null
35     public $country;                         // string(4)  not_null
36     public $is_system;                       // int(2)
37     
38     /* the code above is auto generated do not remove the tag below */
39     ###END_AUTOCODE
40     
41     function applyFilters($q, $au)
42     {
43         
44         $tn = $this->tableName();
45         $this->selectAdd("i18n_translate('c' , {$tn}.country, 'en') as country_display_name ");
46       
47         $tn = $this->tableName();
48         //DB_DataObject::debugLevel(1);
49         $x = DB_DataObject::factory('core_company');
50         $x->comptype= 'OWNER';
51         $x->find(true);
52
53         if (!empty($q['query']['company_project_id'])) {
54             $add = '';
55             if (!empty($q['query']['company_include_self'])) {
56                 $add = " OR {$tn}.id = {$x->id}";
57             }
58             if (!empty($q['query']['company_not_self'])) {
59                 $add = " AND {$tn}.id != {$x->id}";
60             }
61             
62             $pids = array();
63             $pid = $q['query']['company_project_id'];
64             if (strpos($pid, ',')) {
65                 $bits = explode(',', $pid);
66                 foreach($bits as $b) {
67                     $pids[] = (int)$b;
68                 }
69             } else {
70                 $pids = array($pid);
71             }
72             
73             
74             $pids = implode(',', $pids);
75             $this->whereAdd("{$tn}.id IN (
76                 SELECT distinct(company_id) FROM ProjectDirectory where project_id IN ($pids)
77             ) $add" );
78              
79         }
80         if (!empty($q['query']['comptype'])) {
81            
82             $this->whereAddIn('comptype', explode(',', $q['query']['comptype']), 'string');
83             
84         }
85         
86         // depricated - should be moved to module specific (texon afair)
87         
88          if (!empty($q['query']['province'])) {
89              $prov = $this->escape($q['query']['province']);
90             $this->whereAdd("province LIKE '$prov%'");
91             
92             
93         }
94         // ADD comptype_display name.. = for combos..
95         $this->selectAdd("
96             (SELECT display_name
97                 FROM
98                     core_enum
99                 WHERE
100                     etype='comptype'
101                     AND
102                     name={$tn}.comptype
103                 LIMIT 1
104                 ) as comptype_display_name
105         ");
106         
107         if(!empty($q['query']['name'])){
108             $s = $this->escape($q['query']['name']);
109             $this->whereAdd("
110                 {$tn}.name LIKE '%$s%'
111             ");
112         }
113         if(!empty($q['search']['name'])){ 
114             $s = $this->escape($q['search']['name']);
115             $this->whereAdd("
116                 {$tn}.name LIKE '%$s%'
117             ");
118         }
119         if(!empty($q['search']['name_starts'])){
120             $s = $this->escape($q['search']['name_starts']);
121             $this->whereAdd("
122                 {$tn}.name LIKE '$s%'
123             ");
124         }
125     }
126     
127     function toEventString() {
128         return $this->name;
129     }
130     
131     // ---------- AUTHENTICATION
132     // not sure where authetnication via company is used?? posibly media-outreach
133     
134     function isAuth()
135     {
136         $db = $this->getDatabaseConnection();
137         $sesPrefix = $db->dsn['database'];
138         @session_start();
139         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
140             // in session...
141             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
142             $u = DB_DataObject::factory('core_company');
143             if ($u->get($a->id)) { //&& strlen($u->passwd)) {
144                 return true;
145             }
146             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
147             
148         }
149         // not in session or not matched...
150         
151         
152         return false;
153         
154     }
155     function getAuthUser()
156     {
157         if (!$this->isAuth()) {
158             return false;
159         }
160         $db = $this->getDatabaseConnection();
161         $sesPrefix = $db->dsn['database'];
162         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
163             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
164             
165             $u = DB_DataObject::factory('core_company');
166             if ($u->get($a->id)) { /// && strlen($u->passwd)) {
167                 return clone($u);
168             }
169              
170         }
171         
172         
173         return false;
174     }     
175     function login()
176     {
177         $this->isAuth(); // force session start..
178          $db = $this->getDatabaseConnection();
179         $sesPrefix = $db->dsn['database'];
180         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
181         
182     }
183     function logout()
184     {
185         $this->isAuth(); // force session start..
186         $db = $this->getDatabaseConnection();
187         $sesPrefix = $db->dsn['database'];
188         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
189         
190     }    
191     // ---------- AUTHENTICATION
192     function checkPassword($val)
193     {
194         //echo '<pre>'.$val .  print_R($this,true);
195         if (substr($this->passwd,0,1) == '$') {
196             return crypt($val,$this->passwd) == $this->passwd ;
197         }
198         // old style md5 passwords...- cant be used with courier....
199         return md5($val) == $this->passwd;
200     }
201     function setPassword($value) 
202     {
203         $salt='';
204         while(strlen($salt)<9) {
205             $salt.=chr(rand(64,126));
206             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
207         }
208         $this->passwd = crypt($value, '$1$'. $salt. '$');
209        
210     }      
211     function onUpload($controller)
212     {
213         $image = DB_DataObject::factory('Images');
214         return $image->onUploadWithTbl($this, 'logo_id');
215          
216     }
217     function  onUpdate($old, $req,$roo) 
218     {
219         if (!empty($req['password1'])) {
220             $this->setPassword($req['password1']);
221             $this->update();
222         }
223     }
224     function onInsert($req, $roo)
225     {
226         if (!empty($this->logo_id)) { // update images table to sycn with this..
227             $img = DB_DataObject::factory('Images');
228             if ($img->get($this->logo_id) && ($img->onid != $this->id)) {
229                 $img->onid = $this->id;
230                 $img->update();
231             }
232         }
233         if (!empty($req['password1'])) {
234             $this->setPassword($req['password1']);
235             $this->update();
236         }
237         $img = DB_DataObject::factory('Images');
238         $img->onid= 0;
239         
240         $img->ontable = $this->tableName();
241         $img->imgtype = 'LOGO';
242         // should check uploader!!!
243         if ($img->find()) {
244             while($img->fetch()) {
245                 $ii = clone($img);
246                 $ii->onid = $this->id;
247                 $ii->update();
248                 $this->logo_id = $ii->id;
249             }
250             $this->update();
251         }
252         
253     }
254     
255     function beforeInsert($q, $roo)
256     {
257         if(!empty($q['_check_name'])){
258             if($this->checkName()){
259                 $roo->jok('OK');
260             }
261             
262             $roo->jerr('EXIST');
263         }
264     }
265     
266     function beforeUpdate($old, $q,$roo)
267     {
268         // we still use comptype in some old systems...
269         
270         if (!empty($q['comptype_id'])) {
271             $en = DB_DataObject::Factory('core_enum');
272             $en->get($q['comptype_id']);
273             $this->comptype = $en->name;
274         }
275         
276         
277         if(!empty($q['_flag_delete'])){
278             $this->deleted_dt = $this->sqlValue("NOW()");
279             $this->deleted_by = $roo->getAuthUser()->id;
280         }
281         
282         if(!empty($q['_flag_undelete'])){
283             $this->deleted_dt = "";
284             $this->deleted_by = 0;
285         }
286         if(!empty($q['_check_name'])){
287             if($this->checkName()){
288                 $roo->jok('OK');
289             }
290             
291             $roo->jerr('EXIST');
292         }
293         
294         if(!empty($q['_merge_id'])){
295             $this->merge($q['_merge_id'], $roo);
296         }
297         
298         if(!empty($this->is_system) && 
299             ($old->code != $this->code  ) // used to be not allowed to change name..
300         ){
301             $roo->jerr('This company is not allow to editing Ref. or Company Name...');
302         }
303     }
304     
305     function beforeDelete($req, $roo)
306     {
307         
308         // should check for members....
309         if(!empty($this->is_system) && 
310             ($old->code != $this->code || $old->name != $this->name)
311         ){
312             $roo->jerr('This company is not allow to delete');
313         }
314         
315         
316     }
317     function onDelete($req, $roo)
318     {   
319         $img = DB_DataObject::factory('Images');
320         $img->ontable = $this->tableName();
321         $img->onid = $this->id;
322         $img->find();
323         while ($img->fetch()) {
324             $img->beforeDelete();
325             $img->delete();
326         }
327         return true;
328         
329          
330     }
331     /**
332      * check who is trying to access this. false == access denied..
333      */
334     function checkPerm($lvl, $au, $changes = false) 
335     {
336         
337         // do we have an empty system..
338         if ($au && $au->id == -1) {
339             return true;
340         }
341         
342         
343         
344         if ($au->company()->comptype != 'OWNER') {
345             
346             // hacking!
347             if ($changes && isset($changes['comptype']) && $changes['comptype'] != $this->comptype) {
348                 return false;
349             }
350             
351             return $this->id == $au->company_id;
352         }
353         
354         return $au->hasPerm("Core.Companies", $lvl);    
355     }
356     
357     function logoImageToHTML($size)
358     {
359         $i = DB_DataObject::factory('Images');
360         if (!$this->logo_id || !$i->get($this->logo_id)) {
361             return '';
362         }
363         return $i->toHTML($size);
364         
365     }
366      function firstImage($filter='image/%')
367     {
368         $i = DB_DataObject::factory('Images');
369         //DB_DataObject::debugLevel(1);
370         $im = $i->gather($this, $filter);
371         if (empty($im)) {
372             return false;
373         }
374         return $im[0];
375     }
376     
377     function firstImageTag($size =-1, $base="/Images/Thumb", $filter='image/%')
378     {
379         $fm = $this->firstImage($filter);
380          if (empty($fm)) {
381             return '';
382         }
383         return $fm->toHTML($size, $base);
384     }
385     
386     function toRooSingleArray($authUser, $request)
387     {
388         $ret = $this->toArray();
389        // DB_DataObject::debugLevel(1);
390         // get the comptype display
391         $e = DB_DataObject::Factory('core_enum')->lookupObject('COMPTYPE', $this->comptype);
392         
393         $ret['comptype_display'] = $ret['comptype'];
394         if ($e   && !empty($e->name_display)) {
395             $ret['comptype_display'] = $e->name_display;
396         }
397         
398         
399         return $ret;
400     }
401     
402     /**
403      * # 2028 
404      * create the suppliers...
405      * 
406      * @param object $roo
407      * @param array $data
408      * 
409      */
410     function initCompaniesArray($roo, $data)
411     {
412         $tn = $this->tableName();
413         
414         foreach($data as $d){
415             $com = DB_DataObject::factory($tn);
416             $com->setFrom($d);
417             if(!$com->find(true)){
418                 $com->created_dt = Date('Y-m-d H:i:s');
419                 $com->updated_dt = Date('Y-m-d H:i:s');
420                 $com->is_system = 1;// new column.. block the user changing the code and name..
421                 $com->insert();
422             }
423         }
424         
425         
426     }
427     
428     
429     function initCompanies($roo, $opts)
430     {
431         $companies = DB_DataObject::factory('core_company');
432         
433         $ctype = empty($opts['add-company-with-type']) ? 'OWNER' : $opts['add-company-with-type'];
434         
435         $enum = DB_DataObject::Factory('core_enum')->lookup('COMPTYPE', $ctype  );
436         
437         if (empty($enum)) {
438             $roo->jerr("invalid company type '$ctype'");
439         }
440         if ($ctype =='OWNER') {
441             $companies = DB_DataObject::factory('core_company');
442             $companies->comptype_id = $enum;
443             if ($companies->count()) {
444                 $roo->jerr("Owner  company already exists");
445             }
446         }
447         $companies = DB_DataObject::factory('core_company');
448         
449         // check that 
450         $companies->setFrom(array(
451             'name' => $opts['add-company'],
452             'comptype' => $ctype,
453             'comptype_id' => $enum,
454         ));
455         if ($companies->find(true)) {
456             $roo->jerr("company already exists");
457         }
458         $companies->setFrom(array(
459             'background_color' => '',
460             'created_dt' => $this->sqlValue('NOW()'),
461             'updated_dt' => $this->sqlValue('NOW()')
462         ));
463         
464         
465         $companies->insert();
466         $companies->onInsert(array(), $roo);
467     }
468     static function lookupOwner()
469     {
470         $enum = DB_DataObject::Factory('core_enum')->lookup('COMPTYPE', 'OWNER'  );
471         $companies = DB_DataObject::factory('core_company');
472         $companies->comptype_id = $enum;
473         if ($companies->find(true)) {
474             return $companies;
475         }
476         return false;
477     }
478     
479     function merge($merge_to, $roo)
480     {
481         $affects  = array();
482         
483         $all_links = $this->databaseLinks();
484         
485         foreach($all_links as $tbl => $links) {
486             foreach($links as $col => $totbl_col) {
487                 $to = explode(':', $totbl_col);
488                 if ($to[0] != $this->tableName()) {
489                     continue;
490                 }
491                 
492                 $affects[$tbl .'.' . $col] = true;
493             }
494         }
495         
496         foreach($affects as $k => $true) {
497             $ka = explode('.', $k);
498
499             $chk = DB_DataObject::factory($ka[0]);
500             
501             if (!is_a($chk,'DB_DataObject')) {
502                 $roo->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
503             }
504             
505             $chk->{$ka[1]} = $this->id;
506
507             foreach ($chk->fetchAll() as $c){
508                 $cc = clone ($c);
509                 $c->{$ka[1]} = $merge_to;
510                 $c->update($cc);
511             }
512         }
513         
514         $this->delete();
515         
516         $roo->jok('Merged');
517         
518     }
519     
520     function checkName()
521     {
522         $company = DB_DataObject::factory('core_company');
523         $company->setFrom(array(
524             'name' => $this->name
525         ));
526         
527         if(!empty($this->id)){
528             $company->whereAdd("id != {$this->id}");
529         }
530         
531         if(!$company->find(true)){
532             return true;
533         }
534         
535         return false;
536     }
537 }