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