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