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_starts'])){
114             $s = $this->escape($q['search']['name_starts']);
115             $this->whereAdd("
116                 {$tn}.name LIKE '$s%'
117             ");
118         }
119     }
120     
121     function toEventString() {
122         return $this->name;
123     }
124     
125     // ---------- AUTHENTICATION
126     // not sure where authetnication via company is used?? posibly media-outreach
127     
128     function isAuth()
129     {
130         $db = $this->getDatabaseConnection();
131         $sesPrefix = $db->dsn['database'];
132         @session_start();
133         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
134             // in session...
135             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
136             $u = DB_DataObject::factory('core_company');
137             if ($u->get($a->id)) { //&& strlen($u->passwd)) {
138                 return true;
139             }
140             $_SESSION[__CLASS__][$sesPrefix .'-auth'] = '';
141             
142         }
143         // not in session or not matched...
144         
145         
146         return false;
147         
148     }
149     function getAuthUser()
150     {
151         if (!$this->isAuth()) {
152             return false;
153         }
154         $db = $this->getDatabaseConnection();
155         $sesPrefix = $db->dsn['database'];
156         if (!empty($_SESSION[__CLASS__][$sesPrefix .'-auth'])) {
157             $a = unserialize($_SESSION[__CLASS__][$sesPrefix .'-auth']);
158             
159             $u = DB_DataObject::factory('core_company');
160             if ($u->get($a->id)) { /// && strlen($u->passwd)) {
161                 return clone($u);
162             }
163              
164         }
165         
166         
167         return false;
168     }     
169     function login()
170     {
171         $this->isAuth(); // force session start..
172          $db = $this->getDatabaseConnection();
173         $sesPrefix = $db->dsn['database'];
174         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = serialize($this);
175         
176     }
177     function logout()
178     {
179         $this->isAuth(); // force session start..
180         $db = $this->getDatabaseConnection();
181         $sesPrefix = $db->dsn['database'];
182         $_SESSION[__CLASS__][$sesPrefix .'-auth'] = "";
183         
184     }    
185     // ---------- AUTHENTICATION
186     function checkPassword($val)
187     {
188         //echo '<pre>'.$val .  print_R($this,true);
189         if (substr($this->passwd,0,1) == '$') {
190             return crypt($val,$this->passwd) == $this->passwd ;
191         }
192         // old style md5 passwords...- cant be used with courier....
193         return md5($val) == $this->passwd;
194     }
195     function setPassword($value) 
196     {
197         $salt='';
198         while(strlen($salt)<9) {
199             $salt.=chr(rand(64,126));
200             //php -r var_dump(crypt('testpassword', '$1$'. (rand(64,126)). '$'));
201         }
202         $this->passwd = crypt($value, '$1$'. $salt. '$');
203        
204     }      
205     function onUpload($controller)
206     {
207         $image = DB_DataObject::factory('Images');
208         return $image->onUploadWithTbl($this, 'logo_id');
209          
210     }
211     function  onUpdate($old, $req,$roo) 
212     {
213         if (!empty($req['password1'])) {
214             $this->setPassword($req['password1']);
215             $this->update();
216         }
217     }
218     function onInsert($req, $roo)
219     {
220         if (!empty($this->logo_id)) { // update images table to sycn with this..
221             $img = DB_DataObject::factory('Images');
222             if ($img->get($this->logo_id) && ($img->onid != $this->id)) {
223                 $img->onid = $this->id;
224                 $img->update();
225             }
226         }
227         if (!empty($req['password1'])) {
228             $this->setPassword($req['password1']);
229             $this->update();
230         }
231         $img = DB_DataObject::factory('Images');
232         $img->onid= 0;
233         
234         $img->ontable = $this->tableName();
235         $img->imgtype = 'LOGO';
236         // should check uploader!!!
237         if ($img->find()) {
238             while($img->fetch()) {
239                 $ii = clone($img);
240                 $ii->onid = $this->id;
241                 $ii->update();
242                 $this->logo_id = $ii->id;
243             }
244             $this->update();
245         }
246         
247     }
248     
249     function beforeInsert($q, $roo)
250     {
251         if(!empty($q['_check_name'])){
252             if($this->checkName()){
253                 $roo->jok('OK');
254             }
255             
256             $roo->jerr('EXIST');
257         }
258     }
259     
260     function beforeUpdate($old, $q,$roo)
261     {
262          
263         if(!empty($q['_flag_delete']) && $q['_flag_delete'] * 1 == 1){
264             $this->deleted_dt = $this->sqlValue("NOW()");
265             $this->deleted_by = $roo->getAuthUser()->id;
266         }
267         
268         if(!empty($q['_flag_undelete']) && $q['_flag_undelete'] * 1 == 1){
269             $this->deleted_dt = "";
270             $this->deleted_by = 0;
271         }
272         if(!empty($q['_check_name'])){
273             if($this->checkName()){
274                 $roo->jok('OK');
275             }
276             
277             $roo->jerr('EXIST');
278         }
279         
280         if(!empty($q['_merge_id'])){
281             $this->merge($q['_merge_id'], $roo);
282         }
283         
284         if(!empty($this->is_system) && 
285             ($old->code != $this->code  ) // used to be not allowed to change name..
286         ){
287             $roo->jerr('This company is not allow to editing Ref. or Company Name...');
288         }
289     }
290     
291     function beforeDelete($req, $roo)
292     {
293         
294         // should check for members....
295         if(!empty($this->is_system) && 
296             ($old->code != $this->code || $old->name != $this->name)
297         ){
298             $roo->jerr('This company is not allow to delete');
299         }
300         
301         
302     }
303     function onDelete($req, $roo)
304     {   
305         $img = DB_DataObject::factory('Images');
306         $img->ontable = $this->tableName();
307         $img->onid = $this->id;
308         $img->find();
309         while ($img->fetch()) {
310             $img->beforeDelete();
311             $img->delete();
312         }
313         return true;
314         
315          
316     }
317     /**
318      * check who is trying to access this. false == access denied..
319      */
320     function checkPerm($lvl, $au, $changes = false) 
321     {
322         
323         // do we have an empty system..
324         if ($au && $au->id == -1) {
325             return true;
326         }
327         
328         
329         
330         if ($au->company()->comptype != 'OWNER') {
331             
332             // hacking!
333             if ($changes && isset($changes['comptype']) && $changes['comptype'] != $this->comptype) {
334                 return false;
335             }
336             
337             return $this->id == $au->company_id;
338         }
339         
340         return $au->hasPerm("Core.Companies", $lvl);    
341     }
342     
343     function logoImageToHTML($size)
344     {
345         $i = DB_DataObject::factory('Images');
346         if (!$this->logo_id || !$i->get($this->logo_id)) {
347             return '';
348         }
349         return $i->toHTML($size);
350         
351     }
352      function firstImage($filter='image/%')
353     {
354         $i = DB_DataObject::factory('Images');
355         //DB_DataObject::debugLevel(1);
356         $im = $i->gather($this, $filter);
357         if (empty($im)) {
358             return false;
359         }
360         return $im[0];
361     }
362     
363     function firstImageTag($size =-1, $base="/Images/Thumb", $filter='image/%')
364     {
365         $fm = $this->firstImage($filter);
366          if (empty($fm)) {
367             return '';
368         }
369         return $fm->toHTML($size, $base);
370     }
371     
372     function toRooSingleArray($authUser, $request)
373     {
374         $ret = $this->toArray();
375        // DB_DataObject::debugLevel(1);
376         // get the comptype display
377         $e = DB_DataObject::Factory('core_enum')->lookupObject('COMPTYPE', $this->comptype);
378         
379         $ret['comptype_display'] = $ret['comptype'];
380         if ($e   && !empty($e->name_display)) {
381             $ret['comptype_display'] = $e->name_display;
382         }
383         
384         
385         return $ret;
386     }
387     
388     /**
389      * # 2028 
390      * create the suppliers...
391      * 
392      * @param object $roo
393      * @param array $data
394      * 
395      */
396     function initCompaniesArray($roo, $data)
397     {
398         $tn = $this->tableName();
399         
400         foreach($data as $d){
401             $com = DB_DataObject::factory($tn);
402             $com->setFrom($d);
403             if(!$com->find(true)){
404                 $com->created_dt = Date('Y-m-d H:i:s');
405                 $com->updated_dt = Date('Y-m-d H:i:s');
406                 $com->is_system = 1;// new column.. block the user changing the code and name..
407                 $com->insert();
408             }
409         }
410         
411         
412     }
413     
414     
415     function initCompanies($roo, $opts)
416     {
417         $companies = DB_DataObject::factory('core_company');
418         
419         $ctype = empty($opts['add-company-with-type']) ? 'OWNER' : $opts['add-company-with-type'];
420         
421         $enum = DB_DataObject::Factory('core_enum')->lookup('COMPTYPE', $ctype  );
422         
423         if (empty($enum)) {
424             $roo->jerr("invalid company type '$ctype'");
425         }
426         if ($ctype =='OWNER') {
427             $companies = DB_DataObject::factory('core_company');
428             $companies->comptype_id = $enum;
429             if ($companies->count()) {
430                 $roo->jerr("Owner  company already exists");
431             }
432         }
433         $companies = DB_DataObject::factory('core_company');
434         
435         // check that 
436         $companies->setFrom(array(
437             'name' => $opts['add-company'],
438             'comptype' => $ctype,
439             'comptype_id' => $enum,
440         ));
441         if ($companies->find(true)) {
442             $roo->jerr("company already exists");
443         }
444         $companies->setFrom(array(
445             'background_color' => '',
446             'created_dt' => $this->sqlValue('NOW()'),
447             'updated_dt' => $this->sqlValue('NOW()')
448         ));
449         
450         
451         $companies->insert();
452         $companies->onInsert(array(), $roo);
453     }
454     static function lookupOwner()
455     {
456         $enum = DB_DataObject::Factory('core_enum')->lookup('COMPTYPE', 'OWNER'  );
457         $companies = DB_DataObject::factory('core_company');
458         $companies->comptype_id = $enum;
459         if ($companies->find(true)) {
460             return $companies;
461         }
462         return false;
463     }
464     
465     function merge($merge_to, $roo)
466     {
467         $affects  = array();
468         
469         $all_links = $this->databaseLinks();
470         
471         foreach($all_links as $tbl => $links) {
472             foreach($links as $col => $totbl_col) {
473                 $to = explode(':', $totbl_col);
474                 if ($to[0] != $this->tableName()) {
475                     continue;
476                 }
477                 
478                 $affects[$tbl .'.' . $col] = true;
479             }
480         }
481         
482         foreach($affects as $k => $true) {
483             $ka = explode('.', $k);
484
485             $chk = DB_DataObject::factory($ka[0]);
486             
487             if (!is_a($chk,'DB_DataObject')) {
488                 $roo->jerr('Unable to load referenced table, check the links config: ' .$ka[0]);
489             }
490             
491             $chk->{$ka[1]} = $this->id;
492
493             foreach ($chk->fetchAll() as $c){
494                 $cc = clone ($c);
495                 $c->{$ka[1]} = $merge_to;
496                 $c->update($cc);
497             }
498         }
499         
500         $this->delete();
501         
502         $roo->jok('Merged');
503         
504     }
505     
506     function checkName()
507     {
508         $company = DB_DataObject::factory('core_company');
509         $company->setFrom(array(
510             'name' => $this->name
511         ));
512         
513         if(!empty($this->id)){
514             $company->whereAdd("id != {$this->id}");
515         }
516         
517         if(!$company->find(true)){
518             return true;
519         }
520         
521         return false;
522     }
523 }