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'])}%' OR $tn.title LIKE '%{$this->escape($q['search']['filename'])}%'
43 if(!empty($q['toBase64'])) {
44 $roo->jok($this->toBase64());
50 function checkPerm($lvl, $au)
52 // default permissons are to
53 // allow create / edit / if the user has
61 if ($o && method_exists($o, 'checkPerm')) {
62 // edit permissions on related object needed...
63 return $o->checkPerm( $lvl == 'S' ? 'S' : 'E' , $au);
67 return true; //// ??? not really that safe...
71 function beforeInsert($q, $roo)
73 if (isset($q['_remote_upload'])) {
74 require_once 'System.php';
76 $tmpdir = System::mktemp("-d remote_upload");
78 $path = $tmpdir . '/' . basename($q['_remote_upload']);
80 if(!file_exists($path)){
81 file_put_contents($path, file_get_contents($q['_remote_upload']));
84 $imageInfo = getimagesize($path);
86 require_once 'File/MimeType.php';
87 $y = new File_MimeType();
88 $ext = $y->toExt(trim((string) $imageInfo['mime'] ));
90 if (!preg_match("/\." . $ext."$/", $path, $matches)) {
91 rename($path,$path.".".$ext);
95 if (!$this->createFrom($path)) {
96 $roo->jerr("erro making image" . $q['_remote_upload']);
99 if(!empty($q['_return_after_create'])){
103 $roo->addEvent("ADD", $this, $this->toEventString());
105 $r = DB_DataObject::factory($this->tableName());
110 $roo->jok($r->URL(-1,'/Images') . '#attachment-'. $r->id);
117 * create an email from file.
118 * these must have been set first.
122 function createFrom($file, $filename=false)
124 // copy the file into the storage area..
125 if (!file_exists($file) || !filesize($file)) {
126 $this->err = "File $file did not exist or is 0 size";
130 $filename = empty($filename) ? $file : $filename;
132 if (empty($this->mimetype)) {
133 require_once 'File/MimeType.php';
134 $y = new File_MimeType();
135 $this->mimetype = $y->fromFilename($filename);
138 $this->mimetype = strtolower($this->mimetype);
140 $mta = explode('/', $this->mimetype);
141 if (array_shift($mta) == 'image') {
143 $imgs = @getimagesize($file);
145 if (empty($imgs) || empty($imgs[0]) || empty($imgs[1])) {
148 list($this->width , $this->height) = $imgs;
152 if($this->mimetype == 'application/pdf'){
153 $this->no_of_pages = $this->getPdfPages($file);
156 $this->filesize = filesize($file);
157 $this->created = date('Y-m-d H:i:s');
160 if (empty($this->filename)) {
161 $this->filename = basename($filename);
164 //DB_DataObject::debugLevel(1);
173 $f = $this->getStoreName();
175 if (!file_exists($dest)) {
176 // currently this is 0775 due to problems using shared hosing (FTP)
177 // it makes all the files unaccessable..
178 // you can normally solve this by giving the storedirectory better perms
179 // if needed on a dedicated server..
180 $oldumask = umask(0);
181 mkdir($dest, 0775, true);
192 // $this->createThumbnail(0,50);
198 * Calculate target file name
200 * @return - target file name
202 function getStoreName()
204 $opts = HTML_FlexyFramework::get()->Pman;
205 $fn = preg_replace('/[^a-z0-9\.]+/i', '_', $this->filename);
206 return implode( '/', array(
207 $opts['storedir'], '_images_', date('Y/m', strtotime($this->created)), $this->id . '-'. $fn
213 * does the files exist?
217 return file_exists($this->getStoreName());
222 * deletes all the image instances of it...
226 function beforeDelete($dependants_array, $roo)
229 if (!empty($dependants_array)) {
233 $opts = HTML_FlexyFramework::get()->Pman;
234 $deldir = $opts['storedir']. '/_deleted_images_';
236 if (!file_exists( $deldir )) {
237 @mkdir($deldir, 0755); // not sure why we are erroring here.. after checking - maybe permissions?
240 $fn = $this->getStoreName();
242 if (file_exists($fn)) {
244 if (file_exists($deldir . '/'. $b)) {
247 rename($fn, $deldir .'/'. $b);
255 if (file_exists($d)) {
258 while (false !== ($fn = readdir($dh))) {
259 if (substr($fn, 0, strlen($b)) == $b) {
261 if (file_exists($deldir . '/'. $fn)) {
262 unlink($d. '/'. $fn);
265 rename($d. '/'. $fn, $deldir .'/'. $fn);
273 * check mimetype against type
274 * - eg. img.is(#image#)
279 if (empty($this->mimetype)) {
282 return 0 === strcasecmp($type, array_shift(explode('/',$this->mimetype)));
286 * onUpload (singlely attached image to a table)
289 function onUploadWithTbl($tbl, $fld)
291 if ( $tbl->__table == 'Images') {
292 return; // not upload to self...
294 if (empty($_FILES['imageUpload']['tmp_name']) ||
295 empty($_FILES['imageUpload']['name']) ||
296 empty($_FILES['imageUpload']['type'])
301 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
303 $image = DB_DataObject::factory('Images');
304 $image->get($tbl->$fld);
305 $image->beforeDelete();
309 $image = DB_DataObject::factory('Images');
310 $image->onid = $tbl->id;
311 $image->ontable = $tbl->__table;
312 $image->filename = $_FILES['imageUpload']['name'];
313 $image->mimetype = $_FILES['imageUpload']['type'];
315 if (!$image->createFrom($_FILES['imageUpload']['tmp_name'])) {
319 $tbl->$fld = $image->id;
326 function onUpload($roo, $table = false, $file = false)
329 if ($table !== false) {
330 $this->ontable = $table->tableName();
331 $this->onid = $table->pid();
334 if ($file === false) {
335 $file = isset($_FILES['imageUpload']) ? $_FILES['imageUpload'] : array();
338 //print_r($_FILES); echo $_FILES['imageUpload']['type'];exit;
339 if (empty($file['tmp_name']) ||
340 empty($file['name']) ||
345 0=>"There is no error, the file uploaded with success",
346 1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
347 2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" ,
348 3=>"The uploaded file was only partially uploaded",
349 4=>"No file was uploaded",
350 6=>"Missing a temporary folder"
352 $estr = (empty($file['error']) ? '?': $emap[$file['error']]);
353 $this->err = "Missing file details : Error=". $estr;
358 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
360 $this->beforeDelete();
362 if ( empty($this->ontable)) {
363 $this->err = "Missing ontable";
367 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
368 // then its an upload
369 $img = DB_DataObject::factory('Images');
370 $img->onid = $this->onid;
371 $img->ontable = $this->ontable;
372 $img->imgtype = $this->imgtype;
375 while ($img->fetch()) {
376 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
378 $img->beforeDelete();
386 require_once 'File/MimeType.php';
387 $y = new File_MimeType();
388 $this->mimetype = $file['type'];
389 if (in_array($this->mimetype, array(
391 'application/octet-stream',
392 'image/x-png', // WTF does this?
393 'image/pjpeg', // WTF does this?
394 'application/x-apple-msg-attachment', /// apple doing it's magic...
395 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
396 'application/csv-tab-delimited-table', // windows again!!?
397 ))) { // weird tyeps..
398 $inf = pathinfo($file['name']);
399 $this->mimetype = $y->fromExt($inf['extension']);
403 $ext = $y->toExt(trim((string) $this->mimetype ));
405 $this->filename = empty($this->filename) ?
406 $file['name'] : ($this->filename .'.'. $ext);
410 if (!$this->createFrom($file['tmp_name'])) {
411 $this->err = isset($this->err) ? $this->err : "createFrom Image failed";
421 * return a list of images for an object, optionally with a mime regex.
422 * eg. '%/pdf' or 'image/%'
426 * $i = DB_DataObject::factory('Images');
427 * $i->imgtype = 'LOGO';
428 * $ar = $i->gather($somedataobject, 'image/%');
430 * @param {DB_DataObject} dataobject = the object to gather data on.
431 * @param {String} mimelike LIKE query to use for search
434 function gather($obj, $mime_like='', $opts=array())
436 //DB_DataObject::debugLevel(1);
437 if (empty($obj->id)) {
442 $c->whereAddIn($this->tableName() . '.ontable', array( $obj->tableName(), $obj->__table) , 'string');
445 if (!empty($mime_like)) {
446 $c->whereAdd("Images.mimetype LIKE '". $c->escape($mime_like) ."'");
448 $c->orderBy('created DESC');
450 return $c->fetchAll();
455 * set or get the dataobject this image is associated with
456 * @param DB_DataObject $obj An object to associate this image with
457 * (does not store it - you need to call update() to do that)
458 * @return DB_DataObject the dataobject this image is attached to.
460 function object($obj=false)
462 if ($obj === false) {
463 if (empty($this->ontable) || empty($this->onid)) {
466 $ret = DB_DataObject::factory($this->ontable);
467 $ret->get($this->onid);
472 $this->ontable = $obj->tableName();
473 $this->onid = $obj->id; /// assumes our nice standard of using ids..
478 function toRooArray($req)
481 $ret= $this->toArray();
484 $ff = HTML_FlexyFramework::get();
487 $ret['public_baseURL'] = isset($ff->Pman_Images['public_baseURL']) ?
488 $ff->Pman_Images['public_baseURL'] : $ff->baseURL;
490 if (!empty($req['query']['imagesize'])) {
491 // query/imageBaseURL ... depricated...? -- set it in config?
493 $baseURL = isset($req['query']['imageBaseURL']) ? $req['query']['imageBaseURL'] : $ret['public_baseURL'];
495 $ret['url'] = $this->URL(-1, '/Images/Download',$baseURL);
497 $ret['url_view'] = $this->URL(-1, '/Images',$baseURL);
499 if (!empty($req['query']['imagesize'])) {
500 $ret['url_thumb'] = $this->URL($req['query']['imagesize'], '/Images/Thumb',$baseURL);
505 $ret['shorten_name'] = $ret['filename'] = $this->shorten_name();
511 * URL - create a url for the image.
512 * size - use -1 to show full size.
513 * provier = baseURL + /Images/Thumb ... use '/Images/' for full
517 function URL($size , $provider = '/Images/Thumb', $baseURL=false)
520 return 'about:blank';
522 if (!$this->exists()) {
523 return 'about:missing';
526 $shorten_name = $this->shorten_name();
528 $ff = HTML_FlexyFramework::get();
529 $baseURL = $baseURL ? $baseURL : $ff->baseURL ;
530 if (preg_match('#^http[s]*://#', $provider)) {
535 $provider = preg_replace('#/Thumb$#', '', $provider);
537 return $baseURL . $provider . "/{$this->id}/{$shorten_name}"; // -- this breaks the rss feed #image-{$this->id}";
540 //$size = max(100, (int) $size);
541 //$size = min(1024, (int) $size);
542 // the size should 200x150 to convert
543 $sizear = preg_split('/(x|c)/', $size);
544 if(!isset($sizear[1])){
545 $sizear[1] = 0; // 0x with '0' is a box? why
548 $size = implode(strpos($size,'c') > -1 ? 'c' : 'x', $sizear);
550 $fc = $this->toFileConvert();
553 $mt = $this->mimetype;
554 if (!preg_match('#^image/#i',$mt)) {
558 $fc->convert($mt, $size);
560 return $baseURL . $provider . "/$size/{$this->id}/{$shorten_name}"; // -- this breaks the rss feed #image-{$this->id}";
563 function getFromHashURL($url)
566 if (preg_match('/#image-([0-9]+)$/', $url, $matches)) {
568 } else if (preg_match('#Images/Thumb/[^/]+/([0-9]+)/#', $url, $matches)) {
570 } else if (preg_match('#Images/([0-9]+)/#', $url, $matches)) {
574 if ($id === false || $id < 1) {
578 $img = DB_DAtaObject::Factory('images');
579 if ($img->get($id)) {
586 function shorten_name()
588 if(empty($this->filename)) {
592 $filename = explode('.', $this->filename);
593 $ext = array_pop($filename);
594 $name = preg_replace("/[^A-Z0-9.]+/i", '-', implode('-', $filename)) ;
596 if(strlen($name) > 32) {
597 $name = substr($name, 0, 32);
600 $shorten_name = "{$name}.{$ext}";
602 return $shorten_name;
605 * size could be 123x345
609 function toHTML($size, $provider = '/Images/Thumb', $extra = '')
614 $sz = explode('x', $size);
617 if (!$this->id || empty($this->width)) {
619 $this->width = empty($sz[1]) ? $sx : $sz[1];
623 $ratio = empty($this->width) ? 1 : $this->height/ ($this->width *1.0);
624 $sy = intval($ratio * $sx);
630 if (strlen($this->title)) {
631 $extra = ' title="'. htmlspecialchars($this->title) . '"';
634 return '<img src="' . $this->URL($size, $provider) . '"' .
636 ' width="'. $sx . '"' .
637 ' height="'. $sy . '">';
644 * #2142 [new] CMS - image link urls
649 function toLinkHTML($size, $provider = '/Images/Thumb')
651 if(empty($this->linkurl)){
652 return $this->toHTML($size, $provider = '/Images/Thumb');
655 return '<a href="'.$this->linkurl.'" target="_blank">'.$this->toHTML($size, $provider = '/Images/Thumb').'</a>';
661 * to Fileconvert object..
666 function toFileConvert()
668 require_once 'File/Convert.php';
669 $fc = new File_Convert($this->getStoreName(), $this->mimetype);
676 require_once 'File/MimeType.php';
678 $y = new File_MimeType();
679 return $y->toExt($this->mimetype);
691 function setFromRoo($ar, $roo)
693 // not sure why we do this..
695 // if imgtype starts with '-' ? then we set the 'old' (probably to delete later)
696 if (!empty($ar['imgtype']) && !empty($ar['ontable']) && !empty($ar['onid']) && ($ar['imgtype'][0] == '-')) {
699 if ($this->find(true)) {
700 $roo->old = clone($this);
705 if (!empty($ar['_copy_from'])) {
707 if (!$this->checkPerm( 'A' , $roo->authUser)) {
708 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
711 $copy = DB_DataObject::factory('Images');
712 $copy->get($ar['_copy_from']);
713 $this->setFrom($copy->toArray());
715 $this->createFrom($copy->getStoreName());
717 $roo->addEvent("ADD", $this, $this->toEventString());
719 $r = DB_DataObject::factory($this->tableName());
725 $roo->jok($r->toRooArray($ar));
732 // FIXME - we should be checking perms here...
734 // this should be doign update
737 if (!$this->checkPerm($this->id ? 'A' : 'E', $roo->authUser)) {
738 $roo->jerr("IMAGE UPLOAD PERMISSION DENIED");
742 if (!isset($_FILES['imageUpload'])) {
743 return; // standard update...
747 // print_r(!$this->onUpload($this));
749 if ( !$this->onUpload($this)) {
750 $roo->jerr("File upload failed : error = ". (!empty($this->err) ? $this->err : ''));
753 $this->addEvent($ar, $roo);
755 $r = DB_DataObject::factory($this->tableName());
760 $roo->jok($r->toRooArray($ar));
764 function addEvent($ar, $roo)
766 $roo->addEvent("ADD", $this, $this->toEventString());
769 function toEventString()
772 //$p = DB_DataObject::factory($this->ontable);
774 // return "ERROR unknown table? {$this->ontable}";
778 return $this->filename .' - on ' . $this->ontable . ':' . $this->onid;
779 //$p->toEventString();
782 function onUploadFromData($data, $roo)
785 $this->err = "Missing file details";
790 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
792 $this->beforeDelete();
795 if (empty($this->ontable)) {
796 $this->err = "Missing ontable";
800 if (!empty($this->imgtype) && $this->imgtype[0] == '-' && !empty($this->onid)) {
801 // then its an upload
802 $img = DB_DataObject::factory('Images');
803 $img->onid = $this->onid;
804 $img->ontable = $this->ontable;
805 $img->imgtype = $this->imgtype;
808 while ($img->fetch()) {
809 HTML_FlexyFramework::get()->page->jerr("updating images is disabled");
811 $img->beforeDelete();
817 require_once 'File/MimeType.php';
818 $y = new File_MimeType();
820 if (in_array($this->mimetype, array(
822 'application/octet-stream',
823 'image/x-png', // WTF does this?
824 'image/pjpeg', // WTF does this?
825 'application/x-apple-msg-attachment', /// apple doing it's magic...
826 'application/vnd.ms-excel', /// sometimes windows reports csv as excel???
827 'application/csv-tab-delimited-table', // windows again!!?
828 ))) { // weird tyeps..
829 $inf = pathinfo($this->filename);
830 $this->mimetype = $y->fromExt($inf['extension']);
833 $ext = $y->toExt(trim((string) $this->mimetype ));
835 $explode_filename = explode('.', $this->filename);
836 if(array_pop($explode_filename) != $ext){
837 $this->filename = $this->filename .'.'. $ext;
840 if (!$this->createFromData($data)) {
848 function createFromData($data)
851 if (0 === strpos($data, "data:")) {
852 // data:image/png;base64,
853 $data = substr($data,5);
854 $bits = explode(";", $data);
855 $this->mimetype = $bits[0];
858 if (empty($this->filename)) {
859 require_once 'File/MimeType.php';
860 $y = new File_MimeType();
861 $this->filename = 'image-'.$imgid++.'.'.$y->toExt($this->mimetype);
865 $this->mimetype = strtolower($this->mimetype);
866 if ($this->mimetype == 'image/jpg') {
867 $this->mimetype = 'image/jpeg';
871 $explode_mimetype = explode('/', $this->mimetype);
873 if (array_shift($explode_mimetype) == 'image') {
875 $imgs = @getimagesize('data://'. $data);
877 if (!empty($imgs) && !empty($imgs[0]) && !empty($imgs[1])) {
878 list($this->width , $this->height) = $imgs;
882 $this->created = date('Y-m-d H:i:s');
890 $f = $this->getStoreName();
892 if (!file_exists($dest)) {
893 $oldumask = umask(0);
894 mkdir($dest, 0775, true);
898 file_put_contents($f, file_get_contents("data://" . $data));
902 $this->filesize = filesize($f);
904 if($this->mimetype == 'application/pdf'){
905 $this->no_of_pages = $this->getPdfPages($f);
914 function toBase64($rotate = false, $scaleWidth = 0, $scaleHeight = 0)
916 if(!preg_match('/^image\//', $this->mimetype)){
920 $file = $this->getStoreName();
925 if(!file_exists($file)){
929 $data = file_get_contents($file);
931 if(!empty($scaleWidth) || !empty($scaleHeight)){
932 $data = $this->scale(false, $scaleWidth, $scaleHeight);
936 $data = $this->rotate($data);
939 $base64 = 'data:' . $this->mimetype . ';base64,' . base64_encode($data);
944 function getPdfPages($file)
946 require_once 'System.php';
950 $pdfinfo = System::which('pdfinfo');
952 if (!file_exists($file) || empty($pdfinfo)) {
956 $cmd = "{$pdfinfo} {$file}";
960 $info = explode("\n", $ret);
962 foreach ($info as $i){
964 if(!preg_match('/^Pages:[\s]*([0-9]+)/', $i, $matches)){
968 $page = (empty($matches[1])) ? 0 : $matches[1];
974 function rotate($imageBlob = false)
976 if(empty($imageBlob)){
977 $imagick = new Imagick($this->getStoreName());
979 $imagick = new Imagick();
980 $imagick->readImageBlob($imageBlob);
983 $orientation = $imagick->getImageOrientation();
985 switch($orientation) {
986 case Imagick::ORIENTATION_BOTTOMRIGHT:
987 $imagick->rotateimage(new ImagickPixel('#00000000'), 180); // rotate 180 degrees
990 case Imagick::ORIENTATION_RIGHTTOP:
991 $imagick->rotateimage(new ImagickPixel('#00000000'), 90); // rotate 90 degrees CW
994 case Imagick::ORIENTATION_LEFTBOTTOM:
995 $imagick->rotateimage(new ImagickPixel('#00000000'), -90); // rotate 90 degrees CCW
999 return $imagick->getImageBlob();
1002 function scale($imageBlob = false, $width = 0, $height = 0)
1004 if(empty($imageBlob)){
1005 $imagick = new Imagick($this->getStoreName());
1007 $imagick = new Imagick();
1008 $imagick->readImageBlob($imageBlob);
1011 $imagick->resizeimage($width, $height, Imagick::FILTER_LANCZOS, true, true);
1013 return $imagick->getImageBlob();