3 * Table Definition for Images
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
7 class Pman_Core_DataObjects_Images extends DB_DataObject
10 /* the code below is auto generated do not remove the above tag */
12 public $__table = 'Images'; // table name
13 public $id; // int(11) not_null primary_key auto_increment
14 public $filename; // string(255) not_null
15 public $ontable; // string(32) not_null multiple_key
16 public $onid; // int(11) not_null
17 public $mimetype; // string(64) not_null
18 public $width; // int(11) not_null
19 public $height; // int(11) not_null
20 public $filesize; // int(11) not_null
21 public $displayorder; // int(11) not_null
22 public $language; // string(6) not_null
23 public $parent_image_id; // int(11) not_null
24 public $created; // datetime(19) not_null binary
25 public $imgtype; // string(32) not_null
26 public $linkurl; // string(254) not_null
27 public $descript; // blob(65535) not_null blob
28 public $title; // string(128) not_null
30 /* the code above is auto generated do not remove the tag below */
32 function applyFilters($q, $au, $roo)
34 $tn = $this->tableName();
36 if(!empty($q['search']['filename'])){
38 $tn.filename LIKE '%{$this->escape($q['search']['filename'])}%'
40 echo $this->whereAdd("
41 $tn.filename LIKE '%{$this->escape($q['search']['filename'])}%'
48 function checkPerm($lvl, $au)
50 // default permissons are to
51 // allow create / edit / if the user has
59 if (method_exists($o, 'checkPerm')) {
60 // edit permissions on related object needed...
61 return $o->checkPerm( $lvl == 'S' ? 'S' : 'E' , $au);
65 return true; //// ??? not really that safe...
69 function beforeInsert($q, $roo)
71 if (isset($q['_remote_upload'])) {
72 require_once 'System.php';
74 $tmpdir = System::mktemp("-d remote_upload");
76 $path = $tmpdir . '/' . basename($q['_remote_upload']);
78 if(!file_exists($path)){
79 file_put_contents($path, file_get_contents($q['_remote_upload']));
82 $imageInfo = getimagesize($path);
84 require_once 'File/MimeType.php';
85 $y = new File_MimeType();
86 $ext = $y->toExt(trim((string) $imageInfo['mime'] ));
88 if (!preg_match("/\." . $ext."$/", $path, $matches)) {
89 rename($path,$path.".".$ext);
93 if (!$this->createFrom($path)) {
94 $roo->jerr("erro making image" . $q['_remote_upload']);
97 if(!empty($q['_return_after_create'])){
101 $roo->addEvent("ADD", $this, $this->toEventString());
103 $r = DB_DataObject::factory($this->tableName());
108 $roo->jok($r->URL(-1,'/Images') . '#attachment-'. $r->id);
115 * create an email from file.
116 * these must have been set first.
120 function createFrom($file, $filename=false)
122 // copy the file into the storage area..
123 if (!file_exists($file) || !filesize($file)) {
124 $this->err = "File $file did not exist or is 0 size";
128 $filename = empty($filename) ? $file : $filename;
130 if (empty($this->mimetype)) {
131 require_once 'File/MimeType.php';
132 $y = new File_MimeType();
133 $this->mimetype = $y->fromFilename($filename);
136 $this->mimetype = strtolower($this->mimetype);
138 $mta = explode('/', $this->mimetype);
139 if (array_shift($mta) == 'image') {
141 $imgs = @getimagesize($file);
143 if (empty($imgs) || empty($imgs[0]) || empty($imgs[1])) {
146 list($this->width , $this->height) = $imgs;
150 if($this->mimetype == 'application/pdf'){
151 $this->no_of_pages = $this->getPdfPages($file);
154 $this->filesize = filesize($file);
155 $this->created = date('Y-m-d H:i:s');
158 if (empty($this->filename)) {
159 $this->filename = basename($filename);
162 //DB_DataObject::debugLevel(1);
171 $f = $this->getStoreName();
173 if (!file_exists($dest)) {
174 // currently this is 0775 due to problems using shared hosing (FTP)
175 // it makes all the files unaccessable..
176 // you can normally solve this by giving the storedirectory better perms
177 // if needed on a dedicated server..
178 $oldumask = umask(0);
179 mkdir($dest, 0775, true);
190 // $this->createThumbnail(0,50);
196 * Calculate target file name
198 * @return - target file name
200 function getStoreName()
202 $opts = HTML_FlexyFramework::get()->Pman;
203 $fn = preg_replace('/[^a-z0-9\.]+/i', '_', $this->filename);
204 return implode( '/', array(
205 $opts['storedir'], '_images_', date('Y/m', strtotime($this->created)), $this->id . '-'. $fn
211 * deletes all the image instances of it...
215 function beforeDelete($dependants_array, $roo)
218 $opts = HTML_FlexyFramework::get()->Pman;
219 $deldir = $opts['storedir']. '/_deleted_images_';
220 if (!file_exists( $deldir )) {
221 mkdir($deldir, 0755);
224 $fn = $this->getStoreName();
226 if (file_exists($fn)) {
228 if (file_exists($deldir . '/'. $b)) {
231 rename($fn, $deldir .'/'. $b);
239 if (file_exists($d)) {
242 while (false !== ($fn = readdir($dh))) {
243 if (substr($fn, 0, strlen($b)) == $b) {
245 if (file_exists($deldir . '/'. $fn)) {
246 unlink($d. '/'. $fn);
249 rename($d. '/'. $fn, $deldir .'/'. $fn);
257 * check mimetype against type
258 * - eg. img.is(#image#)
263 if (empty($this->mimetype)) {
266 return 0 === strcasecmp($type, array_shift(explode('/',$this->mimetype)));
270 * onUpload (singlely attached image to a table)
273 function onUploadWithTbl($tbl, $fld)
275 if ( $tbl->__table == 'Images') {
276 return; // not upload to self...
278 if (empty($_FILES['imageUpload']['tmp_name']) ||
279 empty($_FILES['imageUpload']['name']) ||
280 empty($_FILES['imageUpload']['type'])
285 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
287 $image = DB_DataObject::factory('Images');
288 $image->get($tbl->$fld);
289 $image->beforeDelete();
293 $image = DB_DataObject::factory('Images');
294 $image->onid = $tbl->id;
295 $image->ontable = $tbl->__table;
296 $image->filename = $_FILES['imageUpload']['name'];
297 $image->mimetype = $_FILES['imageUpload']['type'];
299 if (!$image->createFrom($_FILES['imageUpload']['tmp_name'])) {
303 $tbl->$fld = $image->id;
310 function onUpload($roo)
312 //print_r($_FILES); echo $_FILES['imageUpload']['type'];exit;
313 if (empty($_FILES['imageUpload']['tmp_name']) ||
314 empty($_FILES['imageUpload']['name']) ||
315 empty($_FILES['imageUpload']['type'])
319 0=>"There is no error, the file uploaded with success",
320 1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
321 2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" ,
322 3=>"The uploaded file was only partially uploaded",
323 4=>"No file was uploaded",
324 6=>"Missing a temporary folder"
326 $estr = (empty($_FILES['imageUpload']['error']) ? '?': $emap[$_FILES['imageUpload']['error']]);
327 $this->err = "Missing file details : Error=". $estr;
332 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
334 $this->beforeDelete();
336 if ( empty($this->ontable)) {
337 $this->err = "Missing ontable";
341 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
342 // then its an upload
343 $img = DB_DataObject::factory('Images');
344 $img->onid = $this->onid;
345 $img->ontable = $this->ontable;
346 $img->imgtype = $this->imgtype;
349 while ($img->fetch()) {
350 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
352 $img->beforeDelete();
360 require_once 'File/MimeType.php';
361 $y = new File_MimeType();
362 $this->mimetype = $_FILES['imageUpload']['type'];
363 if (in_array($this->mimetype, array(
365 'application/octet-stream',
366 'image/x-png', // WTF does this?
367 'image/pjpeg', // WTF does this?
368 'application/x-apple-msg-attachment', /// apple doing it's magic...
369 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
370 'application/csv-tab-delimited-table', // windows again!!?
371 ))) { // weird tyeps..
372 $inf = pathinfo($_FILES['imageUpload']['name']);
373 $this->mimetype = $y->fromExt($inf['extension']);
377 $ext = $y->toExt(trim((string) $this->mimetype ));
379 $this->filename = empty($this->filename) ?
380 $_FILES['imageUpload']['name'] : ($this->filename .'.'. $ext);
384 if (!$this->createFrom($_FILES['imageUpload']['tmp_name'])) {
385 $this->err = isset($this->err) ? $this->err : "createFrom Image failed";
395 * return a list of images for an object, optionally with a mime regex.
396 * eg. '%/pdf' or 'image/%'
400 * $i = DB_DataObject::factory('Images');
401 * $i->imgtype = 'LOGO';
402 * $ar = $i->gather($somedataobject, 'image/%');
404 * @param {DB_DataObject} dataobject = the object to gather data on.
405 * @param {String} mimelike LIKE query to use for search
408 function gather($obj, $mime_like='', $opts=array())
410 //DB_DataObject::debugLevel(1);
411 if (empty($obj->id)) {
416 $c->whereAddIn($this->tableName() . '.ontable', array( $obj->tableName(), $obj->__table) , 'string');
419 if (!empty($mime_like)) {
420 $c->whereAdd("Images.mimetype LIKE '". $c->escape($mime_like) ."'");
422 $c->orderBy('created DESC');
424 return $c->fetchAll();
429 * set or get the dataobject this image is associated with
430 * @param DB_DataObject $obj An object to associate this image with
431 * (does not store it - you need to call update() to do that)
432 * @return DB_DataObject the dataobject this image is attached to.
434 function object($obj=false)
436 if ($obj === false) {
437 if (empty($this->ontable) || empty($this->onid)) {
440 $ret = DB_DataObject::factory($this->ontable);
441 $ret->get($this->onid);
446 $this->ontable = $obj->tableName();
447 $this->onid = $obj->id; /// assumes our nice standard of using ids..
452 function toRooArray($req) {
454 $ret= $this->toArray();
458 $ff = HTML_FlexyFramework::get();
461 $ret['public_baseURL'] = isset($ff->Pman_Images['public_baseURL']) ?
462 $ff->Pman_Images['public_baseURL'] : $ff->baseURL;
464 if (!empty($req['query']['imagesize'])) {
465 // query/imageBaseURL ... depricated...? -- set it in config?
467 $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : $ret['public_baseURL'];
469 $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
471 $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);
473 if (!empty($req['query']['imagesize'])) {
474 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
484 * URL - create a url for the image.
485 * size - use -1 to show full size.
486 * provier = baseURL + /Images/Thumb ... use '/Images/' for full
490 function URL($size , $provider = '/Images/Thumb', $baseURL=false)
493 return 'about:blank';
497 $ff = HTML_FlexyFramework::get();
498 $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
499 if (preg_match('#^http[s]*://#', $provider)) {
504 $provider = preg_replace('#/Thumb$#', '', $provider);
506 return $baseURL . $provider . "/{$this->id}/{$this->filename}";
509 //$size = max(100, (int) $size);
510 //$size = min(1024, (int) $size);
511 // the size should 200x150 to convert
512 $sizear = preg_split('/(x|c)/', $size);
513 if(empty($sizear[1])){
516 $size = implode(strpos($size,'c') > -1 ? 'c' : 'x', $sizear);
518 $fc = $this->toFileConvert();
521 $mt = $this->mimetype;
522 if (!preg_match('#^image/#i',$mt)) {
526 $fc->convert($mt, $size);
528 return $baseURL . $provider . "/$size/{$this->id}/{$this->filename}";
531 * size could be 123x345
535 function toHTML($size, $provider = '/Images/Thumb')
540 $sz = explode('x', $size);
543 if (!$this->id || empty($this->width)) {
545 $this->width = empty($sz[1]) ? $sx : $sz[1];
549 $ratio = empty($this->width) ? 1 : $this->height/ ($this->width *1.0);
556 if (strlen($this->title)) {
557 $extra = ' title="'. htmlspecialchars($this->title) . '"';
560 return '<img src="' . $this->URL($size, $provider) . '"' .
562 ' width="'. $sx . '"' .
563 ' height="'. $sy . '">';
570 * #2142 [new] CMS - image link urls
575 function toLinkHTML($size, $provider = '/Images/Thumb')
577 if(empty($this->linkurl)){
578 return $this->toHTML($size, $provider = '/Images/Thumb');
581 return '<a href="'.$this->linkurl.'" target="_blank">'.$this->toHTML($size, $provider = '/Images/Thumb').'</a>';
587 * to Fileconvert object..
592 function toFileConvert()
594 require_once 'File/Convert.php';
595 $fc = new File_Convert($this->getStoreName(), $this->mimetype);
602 require_once 'File/MimeType.php';
604 $y = new File_MimeType();
605 return $y->toExt($this->mimetype);
617 function setFromRoo($ar, $roo)
619 // not sure why we do this..
621 // if imgtype starts with '-' ? then we set the 'old' (probably to delete later)
622 if (!empty($ar['imgtype']) && !empty($ar['ontable']) && !empty($ar['onid']) && ($ar['imgtype'][0] == '-')) {
625 if ($this->find(true)) {
626 $roo->old = clone($this);
631 if (!empty($ar['_copy_from'])) {
633 if (!$this->checkPerm( 'A' , $roo->authUser)) {
634 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
637 $copy = DB_DataObject::factory('Images');
638 $copy->get($ar['_copy_from']);
639 $this->setFrom($copy->toArray());
641 $this->createFrom($copy->getStoreName());
643 $roo->addEvent("ADD", $this, $this->toEventString());
645 $r = DB_DataObject::factory($this->tableName());
650 $roo->jok($r->toArray());
657 // FIXME - we should be checking perms here...
659 // this should be doign update
662 if (!$this->checkPerm($this->id ? 'A' : 'E', $roo->authUser)) {
663 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
668 if (!isset($_FILES['imageUpload'])) {
669 return; // standard update...
673 // print_r(!$this->onUpload($this));
675 if ( !$this->onUpload($this)) {
676 $roo->jerr("File upload failed : error = ". (!empty($this->err) ? $this->err : ''));
679 $this->addEvent($ar, $roo);
681 $r = DB_DataObject::factory($this->tableName());
686 $roo->jok($r->toArray());
690 function addEvent($ar, $roo)
692 $roo->addEvent("ADD", $this, $this->toEventString());
695 function toEventString()
698 //$p = DB_DataObject::factory($this->ontable);
700 // return "ERROR unknown table? {$this->ontable}";
704 return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
705 //$p->toEventString();
708 function onUploadFromData($data, $roo)
711 $this->err = "Missing file details";
716 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
718 $this->beforeDelete();
721 if (empty($this->ontable)) {
722 $this->err = "Missing ontable";
726 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
727 // then its an upload
728 $img = DB_DataObject::factory('Images');
729 $img->onid = $this->onid;
730 $img->ontable = $this->ontable;
731 $img->imgtype = $this->imgtype;
734 while ($img->fetch()) {
735 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
737 $img->beforeDelete();
743 require_once 'File/MimeType.php';
744 $y = new File_MimeType();
746 if (in_array($this->mimetype, array(
748 'application/octet-stream',
749 'image/x-png', // WTF does this?
750 'image/pjpeg', // WTF does this?
751 'application/x-apple-msg-attachment', /// apple doing it's magic...
752 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
753 'application/csv-tab-delimited-table', // windows again!!?
754 ))) { // weird tyeps..
755 $inf = pathinfo($this->filename);
756 $this->mimetype = $y->fromExt($inf['extension']);
759 $ext = $y->toExt(trim((string) $this->mimetype ));
761 if(array_pop(explode('.', $this->filename)) != $ext){
762 $this->filename = $this->filename .'.'. $ext;
765 if (!$this->createFromData($data)) {
773 function createFromData($data)
776 $this->mimetype= strtolower($this->mimetype);
778 if (array_shift(explode('/', $this->mimetype)) == 'image') {
780 $imgs = @getimagesize($data);
782 if (!empty($imgs) && !empty($imgs[0]) && !empty($imgs[1])) {
783 list($this->width , $this->height) = $imgs;
787 $this->created = date('Y-m-d H:i:s');
795 $f = $this->getStoreName();
797 if (!file_exists($dest)) {
798 $oldumask = umask(0);
799 mkdir($dest, 0775, true);
803 file_put_contents($f, file_get_contents("data://" . $data));
807 $this->filesize = filesize($f);
809 if($this->mimetype == 'application/pdf'){
810 $this->no_of_pages = $this->getPdfPages($f);
821 if(!preg_match('/^image\//', $this->mimetype)){
825 $file = $this->getStoreName();
827 if(!file_exists($file)){
831 $data = file_get_contents($file);
833 $base64 = 'data:' . $this->mimetype . ';base64,' . base64_encode($data);
838 function getPdfPages($file)
840 require_once 'System.php';
844 $pdfinfo = System::which('pdfinfo');
846 if (!file_exists($file) || empty($pdfinfo)) {
850 $cmd = "{$pdfinfo} {$file}";
854 $info = explode("\n", $ret);
856 foreach ($info as $i){
858 if(!preg_match('/^Pages:[\s]*([0-9]+)/', $i, $matches)){
862 $page = (empty($matches[1])) ? 0 : $matches[1];