Exemplo n.º 1
0
 public function validateTest2($attribute, $value, $params = null)
 {
     \pkdebug("In ValidateTest: attriubute: [{$attribute}], value: [{$value}]; Params:", $params);
     $errorMsg = "No, Not, not Valid!";
     $this->setCustomMessages(['test2' => "Quite a problem"]);
     return false;
 }
Exemplo n.º 2
0
 public function get_tests($className)
 {
     $className = 'App\\Models\\' . $className;
     $tableName = $className::getTableName();
     $keys = keyVal('keys', keyVal($tableName, static::$tablesAndKeys), []);
     $keyName = keyVal('key_name', keyVal($tableName, static::$tablesAndKeys));
     pkdebug("For class [{$className}], keyName: [{$keyName}], keys:", $keys);
     if (!$keys || !count($keys) || !$keyName) {
         pkdebug("Get All [{$className}]");
         return $className::get();
     } else {
         #Don't return real data
         return $className::whereNotIn($keyName, $keys)->get();
     }
 }
Exemplo n.º 3
0
 public function send($template, array $params, $closure)
 {
     /** Write the supposed email to a log file for checking
      * 
      * @param type $template
      * @param array $params
      * @param type $closure
      */
     $msg = new Message(new Universal());
     $closure($msg);
     $emailFile = getAppLogDir() . '/testEmail-' . time() . "template-{$template}.htm";
     pkdebug("IN FAKE MAILER SEND; writing to: [{$emailFile}]!");
     $fp = fopen($emailFile, "w");
     $str = '';
     $str .= "<pre>\n";
     $str .= print_r($msg, 1);
     $str .= "</pre>\n\n";
     $str .= view($template, $params);
     fwrite($fp, $str);
 }
Exemplo n.º 4
0
 public static function staticRender($view, $data = [])
 {
     if (!$view || !is_string($view)) {
         return '';
     }
     $relview = str_replace('.', '/', $view);
     $viewroots = \Config::get('view.paths');
     $viewfile = null;
     foreach ($viewroots as $viewroot) {
         $testpath = $viewroot . '/' . $relview . '.phtml';
         if (file_exists($testpath)) {
             $viewfile = $testpath;
             continue;
         }
     }
     if (!$viewfile) {
         pkdebug("ERROR: Couldn't find viewtemplate: [{$view}]");
         return ' ';
     }
     if (is_array($data)) {
         ############# BE VERY CAREFUL ABOUT VARIABLE NAMES USED AFTER EXTRACT!!!
         ###########  $out, for example, was a terrible choice!
         extract($data);
     }
     ob_start();
     include $viewfile;
     $___PKMVC_RENDERER_OUT = ob_get_contents();
     ob_end_clean();
     return $___PKMVC_RENDERER_OUT;
 }
Exemplo n.º 5
0
 /** To render regular Blade templates within a PkHtmlRenderer context
  * ... uh, looks like it renders .phtml templates - which is fine
  * @param string $view - standarad blade view name
  * @param array $data - standard blade view data
  * @return string|\PkExtensions\PkHtmlRenderer
  */
 public function render($view, $data = [])
 {
     if (!$view || !is_string($view)) {
         return '';
     }
     $relview = str_replace('.', '/', $view);
     $viewroots = \Config::get('view.paths');
     $viewfile = null;
     //pkdebug('viewroots', $viewroots);
     foreach ($viewroots as $viewroot) {
         $testpath = $viewroot . '/' . $relview . '.phtml';
         // pkdebug("testpath:  $testpath");
         if (file_exists($testpath)) {
             $viewfile = $testpath;
             break;
         }
         #Will this work with Blade templates?
         $testpath = $viewroot . '/' . $relview . '.blade.php';
         if (file_exists($testpath)) {
             $viewfile = $testpath;
             break;
         }
     }
     if (!$viewfile) {
         pkdebug("ERROR: Couldn't find viewtemplate: [{$view}]");
         return $this;
     }
     if (is_array($data)) {
         ############# BE VERY CAREFUL ABOUT VARIABLE NAMES USED AFTER EXTRACT!!!
         ###########  $out, for example, was a terrible choice!
         extract($data);
     }
     ob_start();
     include $viewfile;
     $___PKMVC_RENDERER_OUT = ob_get_contents();
     ob_end_clean();
     //pkdebug("RENDEROUT\n\n$___PKMVC_RENDERER_OUT\n\n");
     //$this[] = $___PKMVC_RENDERER_OUT;
     return $this->rawcontent($___PKMVC_RENDERER_OUT);
 }
Exemplo n.º 6
0
 /**
  * Make an Ajax clickable component, assuming JS support.
  *
  * Makes an arbitrary DOM element that has the data attribute:
  * <tt>data-pk-ajax-element</tt>
  * so clicking will automatically perform an AJAX call.
  * The URL for the call will be in 'data-ajax-url', and so on 
  * @param  array|string  $options:
  *   In simplest form, $options is a string with the ajax-url to call.
  *   Then just render a button, with content/label $content
  *   If is_array($options), can contain all arguments - 
  *    - Normal HTML attributes, plus optionally:
  *   'params' => [$key1=>$val2, $key2=>$val2,] data param arr for AJAX
  * 
  * 
  *  'attr-target' => string: 'name of attribute target_to_recieve_response
  *  'selector-target' => string: The selector that matches this element or child - replace inner HTML with response
  *  'func-target' => string: The name of the JS function to be called with fn(click_target, data, func_arg)
  * 
  *   'attr-arg' => mixed - scalar or array use after AJAX to set the named attribute with.
  *         If an array, expect the AJAX return is a key to the array, to get the value
  *   'selector-arg' => mixed - scalar or array use after AJAX to set the
  *       inner HTML of the matched element with. If array, AJAX return key to the array, to get the value
  * 
  *   'func-arg' => mixed - scalar or array to be passed to the JS function from this component
  * 
  *   If no targets are set, the return from the AJAX call does nothing
  * 
  * @param string $tag - the HTML element to make clickable
  * @param  string $content - the content of the HTML element, if it's a content type
  * 
  * @return \Illuminate\Support\HtmlString
  */
 public function ajaxElement($options = [], $content = null, $ajax_url = null, $tag = 'button')
 {
     if (is_string($options)) {
         $options = ['ajax-url' => $options];
     }
     $options[] = 'data-pk-ajax-element';
     $content = keyVal('content', $options, $content);
     unset($options['content']);
     $options['data-ajax-url'] = keyVal('ajax-url', $options, $ajax_url);
     unset($options['ajax-url']);
     if (empty($options['data-ajax-url'])) {
         throw new \Exception("No AJAX URL for AJAX Element");
     }
     $tag = keyVal('tag', $options, $tag);
     if ($tag === 'button') {
         $options['type'] = keyVal('type', $options, 'button');
     }
     if (empty($options['params'])) {
         $options['data-ajax-params'] = '';
     } else {
         $options['data-ajax-params'] = http_build_query($options['params']);
     }
     unset($options['params']);
     $options['data-attr-target'] = keyVal('attr-target', $options);
     unset($options['attr-target']);
     $options['data-selector-target'] = keyVal('selector-target', $options);
     unset($options['selector-target']);
     $options['data-func-target'] = keyVal('func-target', $options);
     unset($options['func-target']);
     #JSON encode target-args - but convert empty array to empty obj manually
     if (array_key_exists('func-arg', $options)) {
         if ($options['func-arg'] === []) {
             $options['data-func-arg'] = '{}';
         } else {
             $options['data-func-arg'] = json_encode($options['func-arg']);
         }
         unset($options['func-arg']);
     }
     #JSON encode target-args - but convert empty array to empty obj manually
     if (array_key_exists('attr-arg', $options)) {
         if ($options['attr-arg'] === []) {
             $options['data-attr-arg'] = '{}';
         } else {
             $options['data-attr-arg'] = json_encode($options['attr-arg']);
         }
         unset($options['attr-arg']);
     }
     #JSON encode target-args - but convert empty array to empty obj manually
     if (array_key_exists('selector-arg', $options)) {
         if ($options['selector-arg'] === []) {
             $options['data-selector-arg'] = '{}';
         } else {
             $options['data-selector-arg'] = json_encode($options['selector-arg']);
         }
         unset($options['selector-arg']);
     }
     pkdebug('options', $options);
     if (PkHtmlRenderer::contentTag($tag)) {
         return $this->toHtmlString("<{$tag}" . $this->html->attributes($options) . '>' . $content . "</{$tag}>\n");
     }
     if (PkHtmlRenderer::selfClosingTag($tag)) {
         #Ignore content
         return $this->toHtmlString("<{$tag}" . $this->html->attributes($options) . ' />');
     }
     throw new PkException("Invalid args to ajaxElement");
 }
Exemplo n.º 7
0
 public function tagged($tag, $content = null, $attributes = null, $raw = false)
 {
     if ($this->isAncestor($content)) {
         #We want to insert this into a new element
         //$val = $content->up()->release();
         $val = $this->detach();
         $content->addChild($val);
         //$val = $content->detach();
         pkdebug("Yes, Matched This; contentatts:", $content->attributes, 'THESE ATTS', $this->attributes, "Arg Atts", $attributes, 'THIS IS', $this);
         //$content = $val;
         //    return ;
         //   $this->content($val);
     }
     $this->setPkTag($tag);
     $this->attributes = $this->cleanAttributes($attributes);
     $this->content($content, $raw);
     return $this;
 }
Exemplo n.º 8
0
 public static function randFilePathFromDir($dir, $type = 'image')
 {
     pkdebug("DIR:  [{$dir}] ");
     if (!is_dir($dir)) {
         pkdebug("Couldn't resolve [{$dir}] to a directory");
         return null;
     }
     $tmpdir = static::$tmpdir;
     if (!is_dir($tmpdir)) {
         mkdir($tmpdir);
     }
     $entries = scandir($dir);
     pkdebug("Entries:  ", $entries);
     if (!is_array($entries) || !sizeOf($entries)) {
         pkdebug("No entries in [{$dir}]. Entries:", $entries);
         return null;
     }
     #Make array of valid file type paths from entries
     $paths = [];
     //$validentries = [];
     foreach ($entries as $entry) {
         $newpath = pkuntrailingslashit($dir) . "/{$entry}";
         if (!is_file($newpath)) {
             continue;
         }
         // $validentries[]=$entry;
         //      $valid = BaseFileHandler::validateFiletype($newpath, $type);
         //     if ($valid === false) continue;
         $paths[] = $newpath;
     }
     pkdebug("For [{$dir}], got valid paths:", $paths);
     #We have a set of valid file paths of the required type. Pick one:
     $path = static::randData($paths);
     $base = basename($path);
     $copypath = pkuntrailingslashit(static::$tmpdir) . "/{$base}";
     copy($path, $copypath);
     //Copy it to
     return $copypath;
     /*
       //  $relPath = BaseFileHandler::relPathFromFullPath($path);
         //pkdebug("Your rel path:", $relPath);
         $mimeType = getFileMimeType($newpath);
         $newFileObjArgs = [
        'mimetype' => $mimeType,
        'path' => $relPath,
        'type' => $type,
         ];
     
         $fileObj = BaseFileHandler::makeNewFileObj($newFileObjArgs);
         if (!($fileObj instanceOf BaseFile)) return false;
         //pkdebug("Wow - made a file obj!");
         $fileObj->save();
         $fileObjId = $fileObj->getId();
         return $fileObjId;
         #We have copied a file into our upload dir. Now let's make a file obj of it -
         //}
     * 
     */
 }
Exemplo n.º 9
0
 /** Builds an array of image information, and optionally creates compressed versions of them
    * Checks if the compressed versions exist before re-compressing them. Returns something like:
    * array: [
   84-Boracay-OurHumbleHomeAfterTyphoon=>[
     mimeType=>string:{image/jpeg}
     file_name=>string:{84-Boracay-OurHumbleHomeAfterTyphoon.jpg}
     full_path=>string:{C:\www\Laravels\lkirkaas.local\laravel\public\uploads/ORIG_MEDIA/84-Boracay-OurHumbleHomeAfterTyphoon.jpg}
     url=>string:{http://lkirkaas.local/uploads/ORIG_MEDIA/84-Boracay-OurHumbleHomeAfterTyphoon.jpg}
     aspect_ratio=>double:{1.5450755601876}
     root_name=>string:{84-Boracay-OurHumbleHomeAfterTyphoon}
     description=>string:{Our Humble Cottage on Boracay, after the Typhoon}
     mimeType_c0=>string:{image/jpeg}
     file_name_c0=>string:{84-Boracay-OurHumbleHomeAfterTyphoon.jpg}
     full_path_c0=>string:{C:\www\Laravels\lkirkaas.local\laravel\public\uploads/ORIG_MEDIA-1000-1000//84-Boracay-OurHumbleHomeAfterTyphoon.jpg}
     url_c0=>string:{http://lkirkaas.local/uploads/ORIG_MEDIA-1000-1000/84-Boracay-OurHumbleHomeAfterTyphoon.jpg}
     mimeType_c1=>string:{image/jpeg}
     file_name_c1=>string:{84-Boracay-OurHumbleHomeAfterTyphoon.jpg}
     full_path_c1=>string:{C:\www\Laravels\lkirkaas.local\laravel\public\uploads/ORIG_MEDIA-256-256//84-Boracay-OurHumbleHomeAfterTyphoon.jpg}
     url_c1=>string:{http://lkirkaas.local/uploads/ORIG_MEDIA-256-256/84-Boracay-OurHumbleHomeAfterTyphoon.jpg}
   ]
   84-Burma-SchwedegonMonk=>[
  
    * @param int levels=2: How many 'levels' of compressed images. Can be as many as elements in $this->maxwidtharr 
    */
 public function buildGalleryArray($levels = null)
 {
     if ($levels === null) {
         $levels = 2;
     }
     if ($levels > count($this->maxwidtharr)) {
         throw new PkException("Too many levels for array of sizes");
     }
     if ($this->maxlevels >= $levels && $this->img_items) {
         return $this->img_items;
     }
     // We've already run; return
     $this->maxlevels = max($this->maxlevels, $levels);
     if (!$this->relurl) {
         $this->relurl = $this->relpath;
     }
     if (!$this->maxheightarr) {
         $this->maxheightarr = $this->maxwidtharr;
     }
     $setpath = realpath(public_path() . "/{$this->relpath}") . '/';
     $srcdir = $this->srcdir;
     $fullsrcdir = $setpath . $srcdir . '/';
     if (!is_dir($fullsrcdir)) {
         throw new PkException("The src dir [{$fullsrcdir}] doesn't exist");
     }
     $seturl = url("/") . '/' . $this->relurl . "/";
     $origurl = $seturl . $srcdir;
     //$levelroots = [];
     $level_items = [];
     for ($level = 0; $level < $levels; $level++) {
         if (!keyVal($level, $this->cmpdirs)) {
             $this->cmpdirs[$level] = $srcdir . '-' . $this->maxwidtharr[$level] . '-' . $this->maxheightarr[$level];
         }
         $reldir = keyVal($level, $this->cmpdirs);
         $level_items[$level] = [];
         $tmpfullcmpdir = $setpath . $reldir . '/';
         $this->fullcmpdirs[$level] = $tmpfullcmpdir;
         if (!is_dir($tmpfullcmpdir)) {
             mkdir($tmpfullcmpdir, 0777, true);
         }
         $this->cmpurlroots[$level] = $seturl . $reldir . '/';
         $levelentries = scandir($this->fullcmpdirs[$level]);
         foreach ($levelentries as $entry) {
             $fullpath = $this->fullcmpdirs[$level] . '/' . $entry;
             $root_name = substr($entry, 0, strrpos($entry, "."));
             if (!($level_item = $this->makeLevelItemArray($level, $fullpath))) {
                 continue;
             }
             $level_items[$level][$root_name] = $level_item;
         }
     }
     #Get all the valid image files in the src dir:
     $entries = scandir($fullsrcdir);
     $img_items = [];
     foreach ($entries as $entry) {
         $fullpath = $fullsrcdir . $entry;
         if (!($mimeType = isValidImagePath($fullpath))) {
             continue;
         }
         $root_name = substr($entry, 0, strrpos($entry, "."));
         $exif = [];
         try {
             $exif = @exif_read_data($fullpath);
         } catch (Exception $e) {
             error_log("Exception Reading EXIF: " . $e->getMessage());
             pkdebug("Exception reading EXIF:", $e);
         }
         $img_item = ['mimeType' => $mimeType, 'file_name' => $entry, 'full_path' => $fullpath, 'url' => $origurl . '/' . $entry, 'aspect_ratio' => aspectRatio($fullpath), 'root_name' => $root_name, 'description' => keyVal('ImageDescription', $exif)];
         for ($level = 0; $level < $levels; $level++) {
             //pkdebug("Level: [$level], level_items:", $level_items);
             if (!in_array($root_name, array_keys($level_items[$level]), 1)) {
                 $level_items[$level][$root_name] = $this->makeLevelItemArray($level, $this->makeReducedImageFile($fullpath, $level));
             }
             $img_item = array_merge($img_item, $level_items[$level][$root_name]);
         }
         $img_items[$root_name] = $img_item;
     }
     return $this->img_items = $img_items;
 }
Exemplo n.º 10
0
 /** Special handling to reset passwords in a form, then calls parent method
  */
 public function saveRelations(array $arr = [])
 {
     if (!$this->authUpdate()) {
         throw new Exception("Not authorized to update this object");
     }
     ## Check for password reset
     if (isset($arr['new_password'])) {
         $new_password = $arr['new_password'];
         $confirm_password = keyVal('confirm_password', $arr);
         if ($new_password !== $confirm_password) {
             $redirback = redirect()->back()->withInput()->with('error_dialog', "Passwords didn't match");
             pkdebug("Type of redirback: ", typeOf($redirback));
             return $redirback;
         }
         //$arr['password'] = $new_password;
         $this->password = bcrypt($new_password);
     }
     return parent::saveRelations($arr);
 }
Exemplo n.º 11
0
/** If the $filePath is a valid info & can get dimensions, return width/height,
 * else 0/false
 * @param type $filePath
 */
function aspectRatio($filePath) {
  if (!($mimeType = isValidImagePath($filePath))) return false;
  $exif = null;
  try {
    $exif = @exif_read_data($filePath);
  } catch (Exception $e) {
    error_log("Exception Reading EXIF for file [$filePath]: " . $e->getMessage());
    pkdebug("Exception reading EXIF for file [$filePath]:", $e);
  }
  if (($computed = keyVal('COMPUTED', $exif)) && ($width = keyVal('Width', $computed)) && ($height = keyVal('Height', $computed))) {
    return $width / $height;
  }
  #If no exif data, use GD:
  //$gdresource = imagecreatefromstring (file_get_contents($filePath));
  $sz = getimagesize($filePath);
  if (($width = keyVal(0, $sz)) && ($height = keyVal(1, $sz)))
      return $width / $height;
  return false;
}
Exemplo n.º 12
0
 /** This relies on the m-m definitions in the static $load_many_to_many array
  * Much more complicated than just saving one to many, or deleting many to many....
  * The daya should be an array that contains keys to the relationship matching
  * the relationship names defined in the object.
  * 
  * Like if this class has many-to-many relationships with items and
  * children, it should have those relationships defined in the class, and
  * also defined in the static::$load_many_to_many variable, with the key
  * names of $load_many_to_many the same as the relationship names
  */
 public function saveM2MRelations($data = [])
 {
     //pkdebug("Saving Here Data:", $data);
     if (empty(static::$load_many_to_many) || !array_intersect(array_keys(static::$load_many_to_many), array_keys($data))) {
         return true;
         #Nothing to do
     }
     foreach (static::$load_many_to_many as $relName => $definition) {
         if (!in_array($relName, array_keys($data))) {
             continue;
         }
         #Nothing here, keep looking
         $othermodel = keyval('other_model', $definition);
         if (!class_exists($othermodel) || !is_a($othermodel, self::class, true)) {
             throw new Exception("No found other class was defined for [{$relName}]");
         }
         #Have the 'other' class - now find Pivot Class or Table
         $pivotmodel = keyval('pivot_model', $definition);
         if (!class_exists($pivotmodel) || !is_a($pivotmodel, self::class, true)) {
             $pivotmodel = null;
             $pivottable = keyval('pivot_table', $definition);
             if (!Schema::hasTable($pivottable)) {
                 #Can't do anything
                 throw new Exception("Niether a valid pivot class nor tabe was defined for [{$relName}]");
             }
         }
         $mykey = keyval('my_key', $definition, Str::snake(getBaseName(static::class)) . '_id');
         $otherkey = keyval('other_key', $definition, Str::snake(getBaseName($othermodel)) . '_id');
         #Here's where the easy part ends.
         $arr = $data[$relName];
         if (!is_arrayish($arr) || !count($arr)) {
             #Delete it all!
             $deleteAll = true;
         } else {
             #We have an array of data
             $otherobjs = $this->{$relName};
             if (!is_arrayish($otherobjs)) {
                 pkdebug("unexpected for [{$relName}], other objs are:", $otherobjs);
                 continue;
             }
             $mycurrentotherobjkeys = [];
             foreach ($otherobjs as $otherobj) {
                 if (!is_a($otherobj, $othermodel, true)) {
                     #Again, something seriously wrong
                     pkdebug("For [{$relName}], other model is [{$othermodel}], but otherobj:", $otherobj);
                     continue;
                 }
                 $otherobjkey = $otherobj->getKey();
                 $mycurrentotherobjkeys[] = "{$otherobjkey}";
             }
             #Great - we have a list of otherobj keys our model pointed to, we have a new
             #submitted list of other obj keys - let's go!
             #But gotta clean up the keys in case some are 3 & some are '3'!
             #Just make them all strings?
             //pkdebug("Array is:", $arr);
             $newarr = [];
             foreach ($arr as $el) {
                 $newarr[] = "{$el}";
             }
             $addIds = array_diff($newarr, $mycurrentotherobjkeys);
             $idsToDelete = array_diff($mycurrentotherobjkeys, $newarr);
         }
         $thiskeyval = $this->getKey();
         $fresh = [];
         if ($pivotmodel) {
             if (!empty($deleteAll)) {
                 $pivotmodel::where($mykey, $thiskeyval)->delete();
             } else {
                 $pivotmodel::where($mykey, $thiskeyval)->whereIn($otherkey, $idsToDelete)->delete();
                 $fresh[$mykey] = $thiskeyval;
                 foreach ($addIds as $addId) {
                     $fresh[$otherkey] = $addId;
                     //pkdebug("Adding", $fresh);
                     $pivotmodel::create($fresh);
                 }
             }
         } else {
             if (Schema::hasTable($pivottable)) {
                 #Gotta try it with flat table
                 if (!empty($deleteAll)) {
                     DB::table($pivottable)->where($mykey, $thiskeyval)->delete();
                 } else {
                     DB::table($pivottable)->where($mykey, $thiskeyval)->whereIn($otherkey, $idsToDelete)->delete();
                     $fresh[$mykey] = $thiskeyval;
                     foreach ($addIds as $addId) {
                         $fresh[$otherkey] = $addId;
                         DB::table($pivottable)->insert($fresh);
                     }
                 }
             }
         }
     }
 }