示例#1
0
 function delete()
 {
     // security check
     if (!SecurityUtil::checkPermission('AddressBook::', '::', ACCESS_ADMIN)) {
         return LogUtil::registerPermissionError();
     }
     $ot = FormUtil::getPassedValue('ot', 'categories', 'GETPOST');
     $id = (int) FormUtil::getPassedValue('id', 0, 'GETPOST');
     $url = ModUtil::url('AddressBook', 'admin', 'view', array('ot' => $ot));
     $class = 'AddressBook_DBObject_' . ucfirst($ot);
     if (!class_exists($class)) {
         return z_exit(__f('Error! Unable to load class [%s]', $ot));
     }
     $object = new $class();
     $data = $object->get($id);
     if (!$data) {
         LogUtil::registerError(__f('%1$s with ID of %2$s doesn\'\\t seem to exist', array($ot, $id)));
         return System::redirect($url);
     }
     $object->delete();
     if ($ot == "customfield") {
         $sql = "ALTER TABLE addressbook_address DROP adr_custom_" . $id;
         try {
             DBUtil::executeSQL($sql, -1, -1, true, true);
         } catch (Exception $e) {
         }
     }
     LogUtil::registerStatus($this->__('Done! Item deleted.'));
     return System::redirect($url);
 }
示例#2
0
 /**
  * Protects against basic attempts of Cross-Site Scripting (XSS).
  *
  * @see    http://technicalinfo.net/papers/CSS.html
  *
  * @return void
  */
 public function idsInputFilter(Zikula_Event $event)
 {
     if ($event['stage'] & Zikula_Core::STAGE_MODS && System::getVar('useids') == 1) {
         // Run IDS if desired
         try {
             // build request array defining what to scan
             // @todo: change the order of the arrays to merge if ini_get('variables_order') != 'EGPCS'
             if (isset($_REQUEST)) {
                 $request['REQUEST'] = $_REQUEST;
             }
             if (isset($_GET)) {
                 $request['GET'] = $_GET;
             }
             if (isset($_POST)) {
                 $request['POST'] = $_POST;
             }
             if (isset($_COOKIE)) {
                 $request['COOKIE'] = $_COOKIE;
             }
             if (isset($_SERVER['HTTP_HOST'])) {
                 $request['HOST'] = $_SERVER['HTTP_HOST'];
             }
             if (isset($_SERVER['HTTP_ACCEPT'])) {
                 $request['ACCEPT'] = $_SERVER['HTTP_ACCEPT'];
             }
             if (isset($_SERVER['USER_AGENT'])) {
                 $request['USER_AGENT'] = $_SERVER['USER_AGENT'];
             }
             // while i think that REQUEST_URI is unnecessary,
             // the REFERER would be important, but results in way too many false positives
             /*                    if (isset($_SERVER['REQUEST_URI'])) {
                                     $request['REQUEST_URI'] = $_SERVER['REQUEST_URI'];
                                 }
                                 if (isset($_SERVER['HTTP_REFERER'])) {
                                     $request['REFERER'] = $_SERVER['HTTP_REFERER'];
                                 }
                             */
             // initialise configuration object
             $init = IDS_Init::init();
             // set configuration options
             $init->config = $this->_getidsconfig();
             // create new IDS instance
             $ids = new IDS_Monitor($request, $init);
             // run the request check and fetch the results
             $result = $ids->run();
             // analyze the results
             if (!$result->isEmpty()) {
                 // process the IDS_Report object
                 $this->_processIdsResult($init, $result);
             } else {
                 // no attack detected
             }
         } catch (Exception $e) {
             // sth went wrong - maybe the filter rules weren't found
             z_exit(__f('An error occured during executing PHPIDS: %s', $e->getMessage()));
         }
     }
 }
/**
 * render plugin for fetching a particular module object
 *
 * Examples
 *   {selectmodobject module="AutoCustomer" objecttype="customer" id=4 assign="myCustomer"}
 *   {selectmodobject module="AutoCocktails" objecttype="recipe" id=12 assign="myRecipe"}
 *   {selectmodobject recordClass="AutoCocktails_Model_Recipe" id=12 assign="myRecipe"}
 *
 * Parameters:
 *  module      Name of the module storing the desired object (in DBObject mode)
 *  objecttype  Name of object type (in DBObject mode)
 *  recordClass Class name of an doctrine record. (in Doctrine mode)
 *  id          Identifier of desired object
 *  prefix      Optional prefix for class names (defaults to PN) (in DBObject mode)
 *  assign      Name of the returned object
 *
 * @param array       $params All attributes passed to this function from the template.
 * @param Zikula_View $view   Reference to the Zikula_View object.
 *
 * @return void
 */
function smarty_function_selectmodobject($params, Zikula_View $view)
{
    if (isset($params['recordClass']) && !empty($params['recordClass'])) {
        $doctrineMode = true;
    } else {
        // DBObject checks
        if (!isset($params['module']) || empty($params['module'])) {
            $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('selectmodobject', 'module')));
        }
        if (!isset($params['objecttype']) || empty($params['objecttype'])) {
            $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('selectmodobject', 'objecttype')));
        }
        if (!isset($params['prefix'])) {
            $params['prefix'] = 'PN';
        }
        $doctrineMode = false;
    }
    if (!isset($params['id']) || empty($params['id']) || !is_numeric($params['id'])) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('selectmodobject', 'id')));
    }
    if (!isset($params['assign']) || empty($params['assign'])) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('selectmodobject', 'assign')));
    }
    // load object depending on mode: doctrine or dbobject
    if (!$doctrineMode) {
        if (!ModUtil::available($params['module'])) {
            $view->trigger_error(__f('Invalid %1$s passed to %2$s.', array('module', 'selectmodobject')));
        }
        ModUtil::dbInfoLoad($params['module']);
        $classname = "{$params['module']}_DBObject_" . StringUtil::camelize($params['objecttype']);
        if (!class_exists($classname) && System::isLegacyMode()) {
            // BC check for PNObject old style.
            // load the object class corresponding to $params['objecttype']
            if (!($class = Loader::loadClassFromModule($params['module'], $params['objecttype'], false, false, $params['prefix']))) {
                z_exit(__f('Unable to load class [%s] for module [%s]', array(DataUtil::formatForDisplay($params['objecttype']), DataUtil::formatForDisplay($params['module']))));
            }
        }
        // intantiate object model
        $object = new $class();
        $idField = $object->getIDField();
        // assign object data
        // this performs a new database select operation
        // while the result will be saved within the object, we assign it to a local variable for convenience
        $objectData = $object->get(intval($params['id']), $idField);
        if (!is_array($objectData) || !isset($objectData[$idField]) || !is_numeric($objectData[$idField])) {
            $view->trigger_error(__('Sorry! No such item found.'));
        }
    } else {
        $objectData = Doctrine_Core::getTable($params['recordClass'])->find($params['id']);
        if ($objectData === false) {
            $view->trigger_error(__('Sorry! No such item found.'));
        }
    }
    $view->assign($params['assign'], $objectData);
}
示例#4
0
 /**
  * Set a cookie value.
  *
  * @param string  $name    Name of cookie.
  * @param string  $value   Value.
  * @param integer $expires Unix epoch date for expiry.
  * @param string  $path    Cookie path.
  * @param string  $domain  Domain must be at least .domain.tld.
  * @param boolean $secure  To set if cookie must only be set over existing https connection.
  * @param boolean $signed  Override system setting to use signatures.
  *
  * @return boolean
  */
 public static function setCookie($name, $value = '', $expires = null, $path = null, $domain = null, $secure = null, $signed = true)
 {
     if (!$name) {
         return z_exit(__f("Error! In 'setCookie', you must specify at least the cookie name '%s'.", DataUtil::formatForDisplay($name)));
     }
     if (!is_string($value)) {
         return z_exit('setCookie: ' . DataUtil::formatForDisplay($value) . ' must be a string');
     }
     if (System::getVar('signcookies') && !$signed == false) {
         // sign the cookie
         $value = SecurityUtil::signData($value);
     }
     return setcookie($name, $value, $expires, $path, $domain, $secure);
 }
示例#5
0
 public function prepare(&$groups)
 {
     if (!self::$filter) {
         $filter = array('__META__' => array('module' => 'TimeIt'));
         $items = $this->getItems($groups);
         // load the categories system
         if (!($class = Loader::loadClass('CategoryRegistryUtil'))) {
             z_exit('Unable to load class [CategoryRegistryUtil] ...');
         }
         $properties = CategoryRegistryUtil::getRegisteredModuleCategories('TimeIt', 'TimeIt_events');
         foreach ($properties as $prop => $catid) {
             $filter[$prop] = $items;
         }
         self::$filter = DBUtil::generateCategoryFilterWhere('TimeIt_events', false, $filter);
     }
 }
示例#6
0
 /**
  * parse xml
  *
  * @param string $xmldata    XML data.
  * @param string $schemaName Schema name.
  * @param string $module     Module name.
  *
  * @return mixed Associative array of workflow or false.
  */
 public function parse($xmldata, $schemaName, $module)
 {
     // parse XML
     if (!xml_parse($this->parser, $xmldata, true)) {
         xml_parser_free($this->parser);
         z_exit(__f('Unable to parse XML workflow (line %1$s, %2$s): %3$s', array(xml_get_current_line_number($this->parser), xml_get_current_column_number($this->parser), xml_error_string($this->parser))));
     }
     // close parser
     xml_parser_free($this->parser);
     // check for errors
     if ($this->workflow['state'] == 'error') {
         return LogUtil::registerError($this->workflow['errorMessage']);
     }
     $this->mapWorkflow();
     if (!$this->validate()) {
         return false;
     }
     $this->workflow['workflow']['module'] = $module;
     $this->workflow['workflow']['id'] = $schemaName;
     return $this->workflow;
 }
示例#7
0
 /**
  * Check permissions
  *
  * @param string   $component Component.
  * @param string   $instance  Instance.
  * @param constant $level     Level.
  * @param integer  $user      User Id.
  *
  * @return boolean
  */
 public static function checkPermission($component = null, $instance = null, $level = null, $user = null)
 {
     static $groupperms = array();
     if (!is_numeric($level)) {
         return z_exit(__f('Invalid security level [%1$s] received in %2$s', array($level, 'SecurityUtil::checkPermission')));
     }
     if (!$user) {
         $user = UserUtil::getVar('uid');
     }
     if (!isset($GLOBALS['authinfogathered'][$user]) || (int) $GLOBALS['authinfogathered'][$user] == 0) {
         $groupperms[$user] = self::getAuthInfo($user);
         // First time here - get auth info
         if (count($groupperms[$user]) == 0) {
             return false;
             // No permissions
         }
     }
     $res = self::getSecurityLevel($groupperms[$user], $component, $instance) >= $level;
     return $res;
 }
示例#8
0
 /**
  * Check permission of action
  *
  * @param string  $module    Module name.
  * @param string  $schema    Schema name.
  * @param array   $obj       Array object.
  * @param string  $permLevel Permission level.
  * @param integer $actionId  Action Id.
  *
  * @return boolean
  */
 public static function permissionCheck($module, $schema, $obj = array(), $permLevel = 'overview', $actionId = null)
 {
     // translate permission to something meaningful
     $permLevel = self::translatePermission($permLevel);
     // test conversion worked
     if (!$permLevel) {
         return false;
     }
     // get current user
     $currentUser = UserUtil::getVar('uid');
     // no user then assume anon
     if (empty($currentUser)) {
         $currentUser = -1;
     }
     $function = "{$module}_workflow_{$schema}_permissioncheck";
     if (function_exists($function)) {
         // function already exists
         return $function($obj, $permLevel, $currentUser, $actionId);
     }
     // test operation file exists
     $path = self::_findpath("function.{$schema}_permissioncheck.php", $module);
     if (!$path) {
         return z_exit(__f("Permission check file [%s] does not exist.", "function.{$schema}_permissioncheck.php"));
     }
     // load file and test if function exists
     include_once $path;
     if (!function_exists($function)) {
         return z_exit(__f("Permission check function [%s] not defined.", $function));
     }
     // function must be loaded so now we can execute the function
     return $function($obj, $permLevel, $currentUser, $actionId);
 }
示例#9
0
 /**
  * Return a nParas paragraphs of random text based on the dictionary.
  *
  * @param intiger $nParas         The number of paragraphs to return to put in the sentence.
  * @param string  $dict           The dictionary to use (a space separated list of words).
  * @param intiger $irndS          The number of sentences in a paragraph (optional) (default=0=randomlyGenerated).
  * @param intiger $irndW          The number of words in a sentence (optional) (default=0=randomlyGenerated).
  * @param boolean $startCustomary Whether or not to start with the customary phrase (optional) (default=false).
  *
  * @return The resulting random date string.
  */
 public static function getParagraphs($nParas, $dict = '', $irndS = 0, $irndW = 0, $startCustomary = false)
 {
     if (!$nParas) {
         return z_exit(__f('Invalid %1$s passed to %2$s.', array('nParas', 'RandomUtil::getParagraphs')));
     }
     if (!$dict) {
         return z_exit(__f('Invalid %1$s passed to %2$s.', array('dictionary', 'RandomUtil::getParagraphs')));
     }
     $dictArray = explode(' ', $dict);
     $txt = '';
     for ($i = 0; $i < $nParas; $i++) {
         if (!$irndS) {
             $rndS = self::getInteger(3, 7);
         } else {
             $rndS = $irndS;
         }
         for ($j = 0; $j < $rndS; $j++) {
             if (!$irndW) {
                 $rndW = self::getInteger(8, 25);
             } else {
                 $rndW = $irndW;
             }
             $txt .= self::getSentence($rndW, $dictArray);
         }
         $txt .= "\n";
     }
     // start with first 5 words
     if ($startCustomary) {
         $pre = '';
         for ($i = 0; $i < 5; $i++) {
             $pre .= $dictArray[$i] . ' ';
         }
         $startLetter = substr($txt, 0, 1);
         $txt = $pre . strtolower($startLetter) . substr($txt, 1);
     }
     return $txt;
 }
示例#10
0
 /**
  * Selector for a module's tables.
  *
  * @param string  $modname           Module name.
  * @param string  $tablename         Table name.
  * @param string  $name              Select field name.
  * @param string  $selectedValue     Selected value.
  * @param string  $defaultValue      Value for "default" option.
  * @param string  $defaultText       Text for "default" option.
  * @param boolean $submit            Submit on choose.
  * @param boolean $showSystemColumns Whether or not to show the system columns.
  * @param boolean $disabled          Add Disabled attribute to select.
  * @param integer $multipleSize      Size for multiple selects.
  *
  * @return string The rendered output.
  */
 public static function getSelector_TableFields($modname, $tablename, $name, $selectedValue = '', $defaultValue = 0, $defaultText = '', $submit = false, $showSystemColumns = false, $disabled = false, $multipleSize = 1)
 {
     if (!$modname) {
         return z_exit(__f('Invalid %1$s passed to %2$s.', array('modname', 'HtmlUtil::getSelector_TableFields')));
     }
     if (!$tablename) {
         return z_exit(__f('Invalid %1$s passed to %2$s.', array('tablename', 'HtmlUtil::getSelector_TableFields')));
     }
     if (!$name) {
         return z_exit(__f('Invalid %1$s passed to %2$s.', array('name', 'HtmlUtil::getSelector_TableFields')));
     }
     $tables = ModUtil::dbInfoLoad($modname, '', true);
     $colkey = $tablename . '_column';
     $cols = $tables[$colkey];
     if (!$cols) {
         return z_exit(__f('Invalid %1$s [%2$s] in %3$s.', array('column key', $colkey, 'HtmlUtil::getSelector_TableFields')));
     }
     if (!$showSystemColumns) {
         $filtercols = array();
         ObjectUtil::addStandardFieldsToTableDefinition($filtercols, '');
     }
     $data = array();
     foreach ($cols as $k => $v) {
         if ($showSystemColumns) {
             $data[$v] = $k;
         } else {
             if (!$filtercols[$k]) {
                 $data[$v] = $k;
             }
         }
     }
     return self::getSelector_Generic($name, $data, $selectedValue, $defaultValue, $defaultText, $allValue, $allText, $submit, $disabled, $multipleSize);
 }
示例#11
0
 /**
  * Post-process an object's expanded category data to generate relative paths.
  *
  * @param array   &$obj        The object we wish to post-process.
  * @param array   $rootCatsIDs The root category ID for the relative path creation.
  * @param boolean $includeRoot Whether or not to include the root folder in the relative path (optional) (default=false).
  *
  * @return The object with the additionally expanded category data is altered in place and returned
  */
 public static function postProcessExpandedObjectCategories(&$obj, $rootCatsIDs, $includeRoot = false)
 {
     if (!$obj) {
         return z_exit(__f('Invalid object in %s', 'postProcessExpandedObjectCategories'));
     }
     $rootCats = CategoryUtil::getCategoriesByRegistry($rootCatsIDs);
     if (empty($rootCats)) {
         return false;
     }
     // if the function was called to process the object categories
     if (isset($obj['__CATEGORIES__'])) {
         $ak = array_keys($obj['__CATEGORIES__']);
         foreach ($ak as $prop) {
             CategoryUtil::buildRelativePathsForCategory($rootCats[$prop], $obj['__CATEGORIES__'][$prop], $includeRoot);
         }
         // else, if the function was called to process the categories array directly
     } else {
         $ak = array_keys($obj);
         foreach ($ak as $prop) {
             CategoryUtil::buildRelativePathsForCategory($rootCats[$prop], $obj[$prop], $includeRoot);
         }
     }
     return;
 }
示例#12
0
 /**
  * Limit the table name if necessary and prepend the prefix.
  *
  * When using Oracle the object name may not be longer than 30 chars. Now ADODB uses TRIGGERS and SEQUENCEs to emulate the AUTOINCREMENT
  * which eats up to 9 chars (TRIG_SEQ_<prefix>_<tablename>) so we have to limit the length of the table name to
  * 30 - 9 - length(prefix) - separator.
  * We use this function as a central point to shorten table name (there might be restrictions in ' other RDBMS too). If the resulting tablename is
  * empty we will show an error. In this case the prefix is too long.
  *
  * @param string $table        The treated table reference.
  * @param string $dbDriverName The driver used for this DB (optional).
  *
  * @deprecated
  * @see    Doctrines DBAL layer.
  *
  * @return boolean
  */
 public static function getLimitedTablename($table, $dbDriverName = '')
 {
     if (!$dbDriverName) {
         $dbDriverName = strtolower(Doctrine_Manager::getInstance()->getCurrentConnection()->getDriverName());
     }
     $prefix = self::getTablePrefix($table);
     switch ($dbDriverName) {
         case 'oracle':
             // Oracle
             $maxlen = 30;
             // max length for a tablename
             $_tablename = $table;
             // save for later if we need to show an error
             $lenTable = strlen($table);
             $lenPrefix = strlen($prefix);
             // 10 for length of TRIG_SEQ_ + _
             if ($lenTable + $lenPrefix + 10 > $maxlen) {
                 $table = substr($table, 0, $maxlen - 10 - $lenPrefix);
                 // same as 20-strlen(), but easier to understand :-)
             }
             if (empty($table)) {
                 return z_exit(__f('%1$s: unable to limit tablename [%2$s] because database prefix is too long for Oracle, please shorten it (recommended length is 4 chars)', array(__CLASS__ . '::' . __FUNCTION__, DataUtil::formatForDisplay($_tablename))));
             }
             break;
         default:
             // no action necessary, use tablename as is
             break;
     }
     // finally build the tablename
     $tablename = $prefix ? $prefix . '_' . $table : $table;
     return $tablename;
 }
示例#13
0
 /**
  * Load event handler.
  *
  * @param Zikula_Form_View $view Reference to Zikula_Form_View object.
  * @param array            &$params Parameters passed from the Smarty plugin function.
  *
  * @return void
  */
 public function load(Zikula_Form_View $view, &$params)
 {
     if ($this->showEmptyValue != 0) {
         $this->addItem('- - -', 0);
     }
     // switch between doctrine and dbobject mode
     if ($this->recordClass) {
         $q = Doctrine::getTable($this->recordClass)->createQuery();
         if ($this->where) {
             if (is_array($this->where)) {
                 $q->where($this->where[0], $this->where[1]);
             } else {
                 $q->where($this->where);
             }
         }
         if ($this->orderby) {
             $q->orderBy($this->orderby);
         }
         if ($this->pos >= 0) {
             $q->offset($this->pos);
         }
         if ($this->num > 0) {
             $q->limit($this->num);
         }
         $rows = $q->execute();
         foreach ($rows as $row) {
             $itemLabel = $row[$this->displayField];
             if (!empty($this->displayFieldTwo)) {
                 $itemLabel .= ' (' . $row[$this->displayFieldTwo] . ')';
             }
             $this->addItem($itemLabel, $row[$this->idField]);
         }
     } else {
         ModUtil::dbInfoLoad($this->module);
         // load the object class corresponding to $this->objecttype
         $class = "{$this->module}_DBObject_" . StringUtil::camelize($this->objecttype) . 'Array';
         if (!class_exists($class) && System::isLegacyMode()) {
             if (!($class = Loader::loadArrayClassFromModule($this->module, $this->objecttype, false, $this->prefix))) {
                 z_exit(__f('Unable to load class [%s] for module [%s]', array(DataUtil::formatForDisplay($this->objecttype, $this->module))));
             }
         }
         // instantiate the object-array
         $objectArray = new $class();
         // get() returns the cached object fetched from the DB during object instantiation
         // get() with parameters always performs a new select
         // while the result will be saved in the object, we assign in to a local variable for convenience.
         $objectData = $objectArray->get($this->where, $this->orderby, $this->pos, $this->num);
         foreach ($objectData as $obj) {
             $itemLabel = $obj[$this->displayField];
             if (!empty($this->displayFieldTwo)) {
                 $itemLabel .= ' (' . $obj[$this->displayFieldTwo] . ')';
             }
             $this->addItem($itemLabel, $obj[$this->idField]);
         }
     }
     parent::load($view, $params);
 }
示例#14
0
 /**
  * Delete categories, labels, custom fields
  */
 public function delete()
 {
     // Security check
     if (!SecurityUtil::checkPermission('AddressBook::', '::', ACCESS_ADMIN)) {
         return LogUtil::registerPermissionError();
     }
     $ot = FormUtil::getPassedValue('ot', 'categories', 'GETPOST');
     $id = (int) FormUtil::getPassedValue('id', 0, 'GETPOST');
     $confirmation = (int) FormUtil::getPassedValue('confirmation', false);
     $url = ModUtil::url('AddressBook', 'admin', 'view', array('ot' => $ot));
     // Check for existence
     $class = 'AddressBook_DBObject_' . ucfirst($ot);
     if (!class_exists($class)) {
         return z_exit($this->__f('Error! Unable to load class [%s]', $ot));
     }
     $object = new $class();
     $data = $object->get($id);
     if (!$data) {
         LogUtil::registerError($this->__('Error! No such item found.'), 404);
         return System::redirect($url);
     }
     // Check for confirmation.
     if (empty($confirmation)) {
         $this->view->assign('id', $id);
         $this->view->assign('ot', $ot);
         $this->view->assign('object', $data);
         return $this->view->fetch('admin_delete.tpl');
     }
     // If we get here it means that the user has confirmed the action
     // Confirm the forms authorisation key
     $this->checkCsrfToken();
     if (ModUtil::apiFunc('AddressBook', 'admin', 'delete', array('id' => $id, 'ot' => $ot))) {
         // Success
         LogUtil::registerStatus($this->__('Done! Item deleted.'));
     }
     return System::redirect($url);
 }
/**
 * render plugin for fetching a list of module objects
 *
 * Examples
 *   {selectmodobjectarray module="AutoCustomer" objecttype="customer" assign="myCustomers"}
 *   {selectmodobjectarray module="AutoCocktails" objecttype="recipe" orderby="name desc" assign="myRecipes"}
 *   {selectmodobjectarray recordClass="AutoCocktails_Model_Recipe" orderby="name desc" assign="myRecipes"}
 *
 * Parameters:
 *  module      Name of the module storing the desired object (in DBObject mode)
 *  objecttype  Name of object type (in DBObject mode)
 *  recordClass Class name of an doctrine record. (in Doctrine mode)
 *  useArrays   true to fetch arrays and false to fetch objects (default is true) (in Doctrine mode)
 *  where       Filter value
 *  orderby     Sorting field and direction
 *  pos         Start offset
 *  num         Amount of selected objects
 *  prefix      Optional prefix for class names (defaults to PN) (in DBObject mode)
 *  assign      Name of the returned object
 *
 * @param array       $params All attributes passed to this function from the template.
 * @param Zikula_View $view   Reference to the Zikula_View object.
 *
 * @return void
 */
function smarty_function_selectmodobjectarray($params, Zikula_View $view)
{
    if (isset($params['recordClass']) && !empty($params['recordClass'])) {
        $doctrineMode = true;
    } else {
        // DBObject checks
        if (!isset($params['module']) || empty($params['module'])) {
            $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('selectmodobjectarray', 'module')));
        }
        if (!isset($params['objecttype']) || empty($params['objecttype'])) {
            $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('selectmodobjectarray', 'objecttype')));
        }
        if (!isset($params['prefix'])) {
            $params['prefix'] = 'PN';
        }
        $doctrineMode = false;
    }
    if (!isset($params['assign'])) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('selectmodobjectarray', 'assign')));
    }
    // load object depending on mode: doctrine or dbobject
    if (!$doctrineMode) {
        if (!ModUtil::available($params['module'])) {
            $view->trigger_error(__f('Invalid %1$s passed to %2$s.', array('module', 'selectmodobjectarray')));
        }
        ModUtil::dbInfoLoad($params['module']);
        $classname = "{$params['module']}_DBObject_" . StringUtil::camelize($params['objecttype']) . 'Array';
        if (!class_exists($classname) && System::isLegacyMode()) {
            // BC check for PNObjectArray old style.
            // load the object class corresponding to $params['objecttype']
            if (!($class = Loader::loadArrayClassFromModule($params['module'], $params['objecttype'], false, $params['prefix']))) {
                z_exit(__f('Error! Cannot load module array class %1$s for module %2$s.', array(DataUtil::formatForDisplay($params['module']), DataUtil::formatForDisplay($params['objecttype']))));
            }
        }
        // instantiate the object-array
        $objectArray = new $class();
        // convenience vars to make code clearer
        $where = $sort = '';
        if (isset($params['where']) && !empty($params['where'])) {
            $where = $params['where'];
        }
        // TODO: add FilterUtil support here in 2.0
        if (isset($params['orderby']) && !empty($params['orderby'])) {
            $sort = $params['orderby'];
        }
        $pos = 1;
        if (isset($params['pos']) && !empty($params['pos']) && is_numeric($params['pos'])) {
            $pos = $params['pos'];
        }
        $num = 10;
        if (isset($params['num']) && !empty($params['num']) && is_numeric($params['num'])) {
            $num = $params['num'];
        }
        // get() returns the cached object fetched from the DB during object instantiation
        // get() with parameters always performs a new select
        // while the result will be saved in the object, we assign in to a local variable for convenience.
        $objectData = $objectArray->get($where, $sort, $pos - 1, $num);
    } else {
        $query = Doctrine_Core::getTable($params['recordClass'])->createQuery();
        if (isset($params['where']) && !empty($params['where'])) {
            if (is_array($params['where'])) {
                $query->where($params['where'][0], $params['where'][1]);
            } else {
                $query->where($params['where']);
            }
        }
        if (isset($params['orderby']) && !empty($params['orderby'])) {
            $query->orderBy($params['orderby']);
        }
        $pos = 0;
        if (isset($params['pos']) && !empty($params['pos']) && is_numeric($params['pos'])) {
            $pos = $params['pos'];
        }
        $num = 10;
        if (isset($params['num']) && !empty($params['num']) && is_numeric($params['num'])) {
            $num = $params['num'];
        }
        $query->offset($pos);
        $query->limit($num);
        if (isset($params['useArrays']) && !$params['useArrays']) {
            $objectData = $query->execute();
        } else {
            $objectData = $query->fetchArray();
        }
    }
    $view->assign($params['assign'], $objectData);
}
示例#16
0
 /**
  * Internal intialization routine.
  *
  * If $_init is an arrary it is set(), otherwise it is interpreted as a string specifying
  * the source from where the data should be retrieved from.
  *
  * @param mixed  $init  Initialization value (can be an object or a string directive).
  * @param string $key   The DB key to use to retrieve the object (optional) (default=null).
  * @param strubg $field The field containing the key value (optional) (default=null).
  *
  * @return void
  */
 public function _init($init = null, $key = null, $field = null)
 {
     if ($this->_objType != 'DBOBJECT') {
         $dbtables = DBUtil::getTables();
         $tkey = $this->_objType;
         $ckey = $this->_objType . "_column";
         $this->_table = isset($dbtables[$tkey]) ? $dbtables[$tkey] : null;
         $this->_columns = isset($dbtables[$ckey]) ? $dbtables[$ckey] : null;
         if ($field) {
             $this->_objField = $field;
         } else {
             $this->_objField = 'id';
         }
     }
     if (!$init) {
         return;
     }
     if (is_array($init)) {
         $this->setData($init);
     } elseif (is_string($init)) {
         switch ($init) {
             case self::GET_FROM_DB:
                 if (!$key) {
                     return z_exit("Invalid DB-key in DBObject::_init() ...");
                 }
                 $this->get($key, $field);
                 break;
             case self::GET_FROM_GET:
             case self::GET_FROM_POST:
             case self::GET_FROM_REQUEST:
                 $this->setData($this->getDataFromInput($this->_objPath, null, $init));
                 break;
             case self::GET_FROM_SESSION:
                 $this->getDataFromSource($_SESSION, $this->_objPath);
                 break;
             case self::GET_FROM_VALIDATION_FAILED:
                 $this->getDataFromSource($_SESSION['validationFailedObjects'], $this->_objPath);
                 break;
             default:
                 return z_exit(__f("Error! An invalid initialization directive '%s' found in 'DBObject::_init()'.", $init));
         }
     } else {
         return z_exit(__f("Error! An unexpected parameter type initialization '%s' was encountered in 'DBObject::_init()'.", $init));
     }
 }
示例#17
0
 function pn_exit($msg, $html = true)
 {
     LogUtil::log(__f('Warning! Function %1$s is deprecated. Please use %2$s instead.', array(
         'pn_exit()',
         'z_exit()')), E_USER_DEPRECATED);
     z_exit($msg, $html);
 }
示例#18
0
 /**
  * Return a boolean indicating whether or not the specified field failed validation.
  *
  * @param string $objectType The (string) object type.
  * @param string $field      The fieldname.
  *
  * @return boolean A boolean indicating whether or not the specified field failed validation.
  */
 public static function hasValidationErrors($objectType, $field = null)
 {
     if (!$objectType) {
         return z_exit(__f('Empty %1$s passed to %2$s.', array('objectType', 'FormUtil::hasValidationErrors')));
     }
     if (!$field) {
         return z_exit(__f('Empty %1$s passed to %2$s.', array('field', 'FormUtil::hasValidationErrors')));
     }
     $ve = self::getValidationErrors();
     if (isset($ve[$objectType][$field])) {
         return (bool) $ve[$objectType][$field];
     } else {
         return false;
     }
 }
示例#19
0
 /**
  * Internal intialization routine.
  *
  * If $init is an arrary it is set(), otherwise it is interpreted as a string specifying
  * the source from where the data should be retrieved from.
  *
  * @param string|array $init         Initialization value (can be an object or a string directive) (optional) (default=null).
  * @param string       $where        The where clause to use when retrieving the object array (optional) (default='').
  * @param string       $orderBy      The order-by clause to use when retrieving the object array (optional) (default='').
  * @param integer      $limitOffset  The limiting offset.
  * @param integer      $limitNumRows The limiting number of rows.
  * @param string       $assocKey     Key field to use for building an associative array (optional) (default=null).
  *
  * @return void
  */
 public function _init($init = null, $where = null, $orderBy = null, $limitOffset = -1, $limitNumRows = -1, $assocKey = null)
 {
     if ($this->_objType != 'DBOBJECTARRAY') {
         $dbtables = DBUtil::getTables();
         $tkey = $this->_objType;
         $ckey = $tkey . "_column";
         $this->_table = isset($dbtables[$tkey]) ? $dbtables[$tkey] : '';
         $this->_columns = isset($dbtables[$ckey]) ? $dbtables[$ckey] : '';
     }
     if (!$init) {
         return;
     }
     if (is_array($init)) {
         $this->setData($init);
     } elseif (is_string($init)) {
         switch ($init) {
             case DBObject::GET_FROM_DB:
                 $this->get($where, $orderBy, $limitOffset, $limitNumRows, $assocKey, true);
                 break;
             case DBObject::GET_FROM_GET:
             case DBObject::GET_FROM_POST:
             case DBObject::GET_FROM_REQUEST:
                 $this->setData($this->getDataFromInput($this->_objPath, null, $init));
                 break;
             case DBObject::GET_FROM_SESSION:
                 $this->getDataFromSource($_SESSION, $this->_objPath);
                 break;
             case DBObject::GET_FROM_VALIDATION_FAILED:
                 $this->getDataFromSource($_SESSION['validationFailedObjects'], $this->_objPath);
                 break;
             default:
                 return z_exit(__f("Error! An invalid initialization directive '%s' found in 'DBObjectArray::init()'.", $init));
         }
     } else {
         return z_exit(__f("Error! An unexpected parameter type initialization '%s' was encountered in 'PNObject::init()'.", $init));
     }
 }
示例#20
0
 /**
  * Load a DBObject extended class from the given module. The given class name is
  * prefixed with 'PN' and underscores are removed to produce a proper class name.
  *
  * @param module        The module to load from
  * @param base_obj_type The base object type for which to load the class
  * @param array         If true, load the array class instead of the single-object class.
  * @param exitOnError   whether or not exit upon error (optional) (default=true)
  * @param prefix        Override parameter for the default PN prefix (default=PN)
  *
  * @deprecated since 1.3.0
  *
  * @return string The ClassName which was loaded from the file
  */
 public static function loadClassFromModule($module, $base_obj_type, $array = false, $exitOnError = false, $prefix = 'PN')
 {
     LogUtil::log(__f('Warning! Function %1$s is deprecated. Please use %2$s instead.', array(__CLASS__ . '#' . __FUNCTION__, 'autoloading'), E_USER_DEPRECATED));
     if (!$module) {
         return z_exit(__f("Error! Invalid module specification '%s'.", $module));
     }
     if (!$base_obj_type) {
         return z_exit(__f("Error! Invalid 'base_obj_type' specification '%s'.", $base_obj_type));
     }
     $prefix = (string) $prefix;
     if (strpos($base_obj_type, '_') !== false) {
         $c = $base_obj_type;
         $class = '';
         while (($p = strpos($c, '_')) !== false) {
             $class .= ucwords(substr($c, 0, $p));
             $c = substr($c, $p + 1);
         }
         $class .= ucwords($c);
     } else {
         $class = ucwords($base_obj_type);
     }
     $class = $prefix . $class;
     if ($array) {
         $class .= 'Array';
     }
     // prevent unncessary reloading
     if (class_exists($class)) {
         return $class;
     }
     $classFiles = array();
     $classFiles[] = "config/classes/{$module}/{$class}.class.php";
     $classFiles[] = "system/{$module}/classes/{$class}.class.php";
     $classFiles[] = "modules/{$module}/classes/{$class}.class.php";
     foreach ($classFiles as $classFile) {
         $classFile = DataUtil::formatForOS($classFile);
         if (is_readable($classFile)) {
             if (self::includeOnce($classFile)) {
                 return $class;
             }
             if ($exitOnError) {
                 return z_exit(__f('Error! Unable to load class [%s]', $classFile));
             }
             return false;
         }
     }
     return false;
 }
 /**
  * Get the IDs of the property registers.
  *
  * @param string $modname       The module name.
  * @param string $entityname    The entity name for which we wish to get the property for.
  *
  * @return array The associative field array of register ids for the specified module.
  */
 public static function getRegisteredModuleCategoriesIds($modname, $entityname)
 {
     if (!$modname || !$entityname) {
         return z_exit(__f("Error! Received invalid specifications %1{$s}, %2{$s}.", array($modname, $entityname)));
     }
     $em = \ServiceUtil::get('doctrine')->getManager();
     $rCategories = $em->getRepository('Zikula\\Core\\Doctrine\\Entity\\CategoryRegistry')->findBy(array('modname' => $modname, 'entityname' => $entityname));
     $fArr = array();
     foreach ($rCategories as $rCategory) {
         $fArr[$rCategory['property']] = $rCategory['id'];
     }
     return $fArr;
 }
示例#22
0
 /**
  * Adds Join to columns.
  *
  * Edits the column array for use with a join array.
  * We must call it whenever we edited the join information!
  *
  * @return void
  */
 public function addJoinToColumn()
 {
     if (count($this->_join) <= 0) {
         return;
     }
     // reset columns
     $this->resetColumns();
     // now add the alias to all fields
     foreach ($this->_column as &$a) {
         $a = $this->_alias . '.' . $a;
     }
     $tables = DBUtil::getTables();
     // store the fixed aliases
     $aliases = array();
     foreach ($this->_join as $join) {
         if (isset($join['join_alias'])) {
             $aliases[] = $join['join_alias'];
         }
     }
     // add fields of all joins
     $alias = 'a';
     foreach ($this->_join as $join) {
         // check if the alias is ok
         if (!isset($join['join_alias'])) {
             if (in_array($alias, $aliases)) {
                 do {
                     $alias++;
                 } while (in_array($alias, $aliases));
             }
             $join['join_alias'] = $alias;
         }
         // process the fields
         $jc = isset($tables[$join['join_table'] . '_column']) ? $tables[$join['join_table'] . '_column'] : false;
         foreach ($join['join_field'] as $k => $f) {
             $a = $join['object_field_name'][$k];
             if (isset($this->_column[$a])) {
                 // Oh, that won't work! Two fields with the same alias!
                 return z_exit(__f('%s: Invalid join information!', 'FilterUtil'));
             }
             // so, let's add the field to the column array
             $this->_column[$a] = $join['join_alias'] . '.' . ($jc ? $jc[$f] : $f);
         }
         // now increase the alias ('a'++ = 'b')
         $alias++;
     }
 }
示例#23
0
    /**
     * Get the IDs of the property registers.
     *
     * @param string $modname   The module name.
     * @param string $tablename The tablename for which we wish to get the property for.
     *
     * @return array The associative field array of register ids for the specified module.
     */
    public static function getRegisteredModuleCategoriesIds($modname, $tablename)
    {
        if (!$modname || !$tablename) {
            return z_exit(__f("Error! Received invalid specifications '%1$s', '%2$s'.", array($modname, $tablename)));
        }

        $wheres = array();
        $dbtables = DBUtil::getTables();
        $col = $dbtables['categories_registry_column'];
        $wheres[] = "$col[modname]='" . DataUtil::formatForStore($modname) . "'";
        $wheres[] = "$col[table]='" . DataUtil::formatForStore($tablename) . "'";
        $where = implode(' AND ', $wheres);
        $fArr = DBUtil::selectFieldArray('categories_registry', 'id', $where, '', false, 'property');

        return $fArr;
    }
示例#24
0
 /**
  * Export data to a csv file.
  *
  * @param array  $datarows  The data to write to the csv file.
  * @param array  $titlerow  The titles to write to the csv file (default is empty array) (optional).
  * @param string $delimiter The character to use for field delimeter (default is character ,) (one character only) (optional).
  * @param string $enclosure The character to use for field enclosure (default is character ") (one character only) (optional).
  * @param string $filename  The filename of the exported csv file (default is null) (optional).
  *
  * @return nothing
  */
 public static function exportCSV($datarows, $titlerow = array(), $delimiter = ',', $enclosure = '"', $filename = null)
 {
     // check if $datarows is array
     if (!is_array($datarows)) {
         return z_exit(__f('%1$s: %2$s is not an array', array('FileUtil::exportCSV', 'datarows')));
     }
     // check if $datarows is empty
     if (count($datarows) == 0) {
         return z_exit(__f('%1$s: %2$s is empty', array('FileUtil::exportCSV', 'datarows')));
     }
     // create random filename if none is given or else format it appropriately
     if (!isset($filename)) {
         $filename = 'csv_' . time() . '.csv';
     } else {
         $filename = DataUtil::formatForOS($filename);
     }
     //disable compression and set headers
     ob_end_clean();
     ini_set('zlib.output_compression', 0);
     header('Cache-Control: no-store, no-cache');
     header('Content-type: text/csv');
     header('Content-Disposition: attachment; filename="' . $filename . '"');
     header('Content-Transfer-Encoding: binary');
     // open a file for csv writing
     $out = fopen("php://output", 'w');
     // write out title row if it exists
     if (isset($titlerow) && is_array($titlerow) && count($titlerow) > 0) {
         fputcsv($out, $titlerow, $delimiter, $enclosure);
     }
     // write out data
     foreach ($datarows as $datarow) {
         fputcsv($out, $datarow, $delimiter, $enclosure);
     }
     //close the out file
     fclose($out);
     exit;
 }
示例#25
0
 /**
  * Load multiple files from the specified location in the pn file tree
  * Note that in it's default invokation, this method exits after the
  * first successful file load.
  *
  * @param files       Array of filenames to load
  * @param path        The path prefix to use (optional) (default='null')
  * @param all         whether or not to load all files or exit upon 1st successful load (optional) (default=false)
  * @param exitOnError whether or not exit upon error (optional) (default=true)
  * @param returnVar   The variable to return if $all==false (optional) (default=null)
  *
  * @return boolean true
  */
 public static function loadFiles($files, $path = null, $all = false, $exitOnError = false, $returnVar = '')
 {
     if (!is_array($files) || !$files) {
         return z_exit(__('Error! Invalid file array specification.'));
     }
     $files = array_unique($files);
     $loaded = false;
     foreach ($files as $file) {
         $rc = self::loadFile($file, $path, $exitOnError, $returnVar);
         if ($rc) {
             $loaded = true;
         }
         if ($loaded && !$all) {
             break;
         }
     }
     if ($returnVar && !$all) {
         return $rc;
     }
     return $loaded;
 }
示例#26
0
 function search($args)
 {
     // Private Address Book mode, for users only
     if (!UserUtil::isLoggedIn() && ModUtil::getVar('AddressBook', 'globalprotect') == 1) {
         return LogUtil::registerError($this->__f('This website require it\'s users to be registered to use the address book.<br />Register for free <a href="%1$s">here</a>, or <a href=\\"%1$s\\">log in</a> if you are already registered.', array(ModUtil::url('Users', 'user', 'view'))));
     }
     // security check
     if (!SecurityUtil::checkPermission('AddressBook::', '::', ACCESS_READ)) {
         return LogUtil::registerPermissionError();
     }
     $search = isset($args['search']) ? $args['search'] : '';
     if (ModUtil::getVar('AddressBook', 'addressbooktype') == 1) {
         $sort = "sortname ASC";
     } else {
         $sort = "sortcompany ASC";
     }
     $ot = "address";
     // Get user id
     if (UserUtil::isLoggedIn()) {
         $user_id = UserUtil::getVar('uid');
     } else {
         $user_id = 0;
     }
     // build the where clause
     $where = '';
     $ztable = DBUtil::getTables();
     $address_table = $ztable['addressbook_address'];
     $address_column =& $ztable['addressbook_address_column'];
     // admin always sees all records but favourites
     if (SecurityUtil::checkPermission('AddressBook::', '::', ACCESS_ADMIN)) {
         $where .= "({$address_column['user_id']} IS NOT NULL)";
     } else {
         // global protect - users see only their own records (admin sees all)
         if (ModUtil::getVar('AddressBook', 'globalprotect') == 1 && !SecurityUtil::checkPermission('AddressBook::', '::', ACCESS_ADMIN)) {
             $where = "({$address_column['user_id']}={$user_id})";
         } else {
             // if private = 1, show only private records
             if ($private == 1) {
                 $where = "({$address_column['user_id']}={$user_id} AND {$address_column['private']} = 1)";
             } else {
                 // if private = 0, show all records
                 $where = "(({$address_column['private']} = 0) OR ({$address_column['user_id']}={$user_id} AND {$address_column['private']} = 1))";
             }
         }
     }
     // typecasting / security
     if (is_string($search)) {
         $where .= " AND ({$address_column['lname']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n                        OR {$address_column['fname']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n                        OR {$address_column['company']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n                        OR {$address_column['title']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n                        OR {$address_column['city']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n                        OR {$address_column['address1']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n                        OR {$address_column['address2']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n                        OR {$address_column['zip']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n                        OR {$address_column['country']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n                        OR {$address_column['state']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n                        OR {$address_column['note']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n                        OR {$address_column['contact_1']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n                        OR {$address_column['contact_2']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n                        OR {$address_column['contact_3']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n                        OR {$address_column['contact_4']} LIKE '%" . DataUtil::formatForStore($search) . "%'\n                        OR {$address_column['contact_5']} LIKE '%" . DataUtil::formatForStore($search) . "%')";
     }
     // and now the custom fields
     $cus_where = "";
     $cus_sort = "cus_pos ASC";
     $cus_Array = new AddressBook_DBObject_CustomfieldArray();
     $customfields = $cus_Array->get($cus_where, $cus_sort);
     foreach ($customfields as $cus) {
         if (!strstr($cus['type'], 'tinyint') && !strstr($cus['type'], 'smallint')) {
             $the_name = 'adr_custom_' . $cus['id'];
             if (strstr($cus['type'], 'varchar') || strstr($cus['type'], 'text') || strstr($cus['type'], 'dropdown')) {
                 // typecasting / security
                 if (is_string($search)) {
                     $where .= " OR {$the_name} LIKE '%" . DataUtil::formatForStore($search) . "%'";
                 }
             }
             if (strstr($cus['type'], 'int')) {
                 // typecasting / security
                 if (is_int($search)) {
                     $where .= " OR {$the_name} = {$search}";
                 }
             }
             if (strstr($cus['type'], 'decimal')) {
                 // typecasting / security
                 if (is_numeric($search)) {
                     $where .= " OR {$the_name} = {$search}";
                 }
             }
         }
     }
     // get the result
     $class = 'AddressBook_DBObject_' . ucfirst($ot) . 'Array';
     if (!class_exists($class)) {
         return z_exit($this->__f('Error! Unable to load class [%s]', $ot));
     }
     $objectArray = new $class();
     $data = $objectArray->get($where, $sort, $startnum - 1, $pagesize);
     return $data;
 }
示例#27
0
 function simpledisplay($args)
 {
     // security check
     if (!SecurityUtil::checkPermission('AddressBook::', '::', ACCESS_READ)) {
         return LogUtil::registerPermissionError();
     }
     $ot = FormUtil::getPassedValue('ot', isset($args['ot']) ? $args['ot'] : 'address', 'GET');
     $id = (int) FormUtil::getPassedValue('id', isset($args['id']) ? $args['id'] : null, 'GET');
     $category = FormUtil::getPassedValue('category', 0);
     $private = FormUtil::getPassedValue('private', 0);
     unset($args);
     $lang = ZLanguage::getLanguageCode();
     if (!$id) {
         return z_exit($this->__f('Error! Invalid id [%s] received.', $id));
     }
     // get the details
     $object = new AddressBook_DBObject_Address();
     $data = $object->get($id);
     // get the custom fields
     $cus_where = "";
     $cus_sort = "cus_pos ASC";
     $cus_Array = new AddressBook_DBObject_CustomfieldArray();
     $customfields = $cus_Array->get($cus_where, $cus_sort);
     foreach ($customfields as $key => $customfield) {
         if (isset($customfield['name1']) && $customfield['name1'] && $lang != 'en') {
             $customfields[$key]['name'] = $customfield['name1'];
         }
     }
     // Labels
     $addressbook_labels = DBUtil::selectObjectArray('addressbook_labels');
     $ablabels = array();
     foreach ($addressbook_labels as $addressbook_label) {
         if (isset($addressbook_label['name1']) && $addressbook_label['name1'] && $lang != 'en') {
             $addressbook_label['name'] = $addressbook_label['name1'];
         }
         $ablabels[$addressbook_label['id']] = $addressbook_label;
     }
     $this->view->assign('address', $data);
     $this->view->assign('customfields', $customfields);
     $this->view->assign('ot', $ot);
     $this->view->assign('category', $category);
     $this->view->assign('private', $private);
     $this->view->assign('preferences', ModUtil::getVar('AddressBook'));
     $this->view->assign('lang', $lang);
     $this->view->assign('ablabels', $ablabels);
     return $this->view->fetch('user_simpledisplay.tpl');
 }
示例#28
0
 /**
  * Get dateformat data.
  *
  * Parses strftime formatted __('%Y-%m-%d),  __('%Y-%m-%d %H:%M') or __('%Y-%m-%d %H:%M:%S')
  * into meaning data that can be used to process a date string.
  *
  * format strings can contain %d, %e, %y, %Y, %g, %G, %H, %I, %l, %M and %S.
  *
  * @param string $dateformat Default current language default (strftime formatted).
  *
  * @return array Array of the meaning of each match.
  */
 public static function getDateFormatData($dateformat = null)
 {
     if (is_null($dateformat)) {
         $dateformat = __('%Y-%m-%d');
     }
     // 8 = __('%Y-%m-%d');
     // 14 = __('%Y-%m-%d %H:%M');
     // 17 = __('%Y-%m-%d %h:%M:%S');
     $length = strlen($dateformat);
     switch ($length) {
         case 8:
             $regex = '#%(\\w)(.)%(\\w)(.)%(\\w)#';
             $type = 'date';
             break;
         case 14:
             $regex = '#%(\\w)(.)%(\\w)(.)%(\\w)\\s%(\\w)(.)%(\\w)#';
             $type = 'datetimeshort';
             break;
         case 17:
             $regex = '#%(\\w)(.)%(\\w)(.)%(\\w)\\s%(\\w)(.)%(\\w)(.)%(\\w)#';
             $type = 'datetimefull';
             break;
         default:
             z_exit(__f('Dateformat must be with 8, 14 or 17 characters long.', $dateformat));
     }
     if (preg_match($regex, $dateformat, $matches)) {
         $matchCount = count($matches);
         // validate separator
         if ($matches[2] != $matches[4]) {
             // TODO A throw exception here (dateformat separators must match) - drak
             z_exit(__f('Dateformat separators must be the same in %s', $dateformat));
         }
         // construct separator regex
         $separator = preg_quote($matches[2]);
         $dateMap = array('d' => array('regex' => '(\\d{2})', 'type' => 'day'), 'e' => array('regex' => '(\\d{1,2})', 'type' => 'day'), 'm' => array('regex' => '(\\d{2})', 'type' => 'month'), 'y' => array('regex' => '(\\d{2})', 'type' => 'year'), 'Y' => array('regex' => '(\\d{4})', 'type' => 'year'), 'g' => array('regex' => '(\\d{2})', 'type' => 'year'), 'G' => array('regex' => '(\\d{4})', 'type' => 'year'), 'H' => array('regex' => '(\\d{2})', 'type' => 'hour'), 'I' => array('regex' => '(\\d{2})', 'type' => 'hour'), 'l' => array('regex' => '(\\d{1,2})', 'type' => 'hour'), 'M' => array('regex' => '(\\d{2})', 'type' => 'minute'), 'S' => array('regex' => '(\\d{2})', 'type' => 'second'));
         // define elements
         $format = array();
         $format[] = $matches[1];
         // position 1
         $format[] = $matches[3];
         // position 2
         $format[] = $matches[5];
         // position 3
         if ($matchCount > 8) {
             if ($matchCount == 11 && $matches[7] != $matches[9]) {
                 // TODO A throw exception here (dateformat separators must match) - drak
                 z_exit(__f('Dateformat time separators must be the same in %s', $dateformat));
             }
             $timeseparator = preg_quote($matches[7]);
             $format[] = $matches[6];
             // position 3
             $format[] = $matches[8];
             // position 3
             if ($matchCount == 11) {
                 $format[] = $matches[10];
                 // position 3
             }
         }
         // map elements
         foreach ($format as $key) {
             $meaning[] = array('key' => $key, 'type' => $dateMap[$key]['type'], 'regex' => $dateMap[$key]['regex']);
         }
         // build regex
         $regex = $meaning[0]['regex'] . $separator . $meaning[1]['regex'] . $separator . $meaning[2]['regex'];
         if ($matchCount > 7) {
             $regex .= '\\s' . $meaning[3]['regex'] . $timeseparator . $meaning[4]['regex'];
             if ($matchCount == 11) {
                 $regex .= $timeseparator . $meaning[5]['regex'];
             }
         }
         // find month, day, year, hour, minute and second positions in the dateformat
         $count = 1;
         foreach ($meaning as $m) {
             $positionMatch[$m['type']] = $count;
             $count++;
         }
         // build and return array
         return array('regex' => $regex, 'matches' => $positionMatch, 'type' => $type);
     }
     // TODO A throw exception here in 1.3.0 - drak
     z_exit(__f('Dateformat did not match known format in %s', $dateformat));
 }
示例#29
0
 /**
  * Validate a specific field using the supplied plain validation array.
  * 
  * This function converts the plain validation array into a structured
  * validation array and then calls ValidationUtil::validateObject().
  *
  * The expected structure for the validation array is as follows:
  * $validationArray[] = array ($fieldname, true/false, eq/neq/lt/lte/gt/gte/noop, $value, $errorMessage);
  *
  * The noop value for the cmp_op field is only valid if the field is not required.
  *
  * @param string $objectType      The string object type.
  * @param array  $object          The object to validate.
  * @param array  $validationArray The plain (numerically indexed) validation array.
  *
  * @return boolean A true/false value indicating whether the object validation passed or failed.
  */
 public static function validateObjectPlain($objectType, $object, $validationArray)
 {
     $validationControls = array();
     $vc = array();
     foreach ($validationArray as $va) {
         $size = count($va);
         if ($size < 5) {
             return z_exit(__f('%1$s: invalid validationArray supplied: expected 5 fields but found %2$s.', array('ValidationUtil::validateObjectPlain', $size)));
         }
         $vc['objectType'] = $objectType;
         $vc['field'] = $va[0];
         $vc['required'] = $va[1];
         $vc['cmp_op'] = $va[2];
         $vc['cmp_value'] = $va[3];
         $vc['err_msg'] = $va[4];
         $vc['callback'] = $va[5];
         $validationControls[] = $vc;
     }
     return self::validateObject($objectType, $object, $validationControls);
 }
示例#30
0
 /**
  * Execute workflow operation within action.
  *
  * @param string $operation  Operation name.
  * @param array  &$obj       Data object.
  * @param string &$nextState Next state.
  *
  * @return mixed|false
  */
 public function executeOperation($operation, &$obj, &$nextState)
 {
     $params = $operation['parameters'];
     if (isset($params['nextstate'])) {
         $nextState = $params['nextstate'];
     }
     $params['nextstate'] = $nextState;
     // test operation file exists
     $path = Zikula_Workflow_Util::_findpath("operations/function.{$operation['name']}.php", $this->module);
     if (!$path) {
         return z_exit(__f('Operation file [%s] does not exist', $operation['name']));
     }
     // load file and test if function exists
     include_once $path;
     $function = "{$this->module}_operation_{$operation['name']}";
     if (!function_exists($function)) {
         return z_exit(__f('Operation function [%s] is not defined', $function));
     }
     // execute operation and return result
     $result = $function($obj, $params);
     $states = array_keys($this->stateMap);
     // checks for an invalid next state value
     if (!in_array($params['nextstate'], $states)) {
         LogUtil::registerError(__f('Invalid next-state value [%1$s] retrieved by the \'%2$s\' operation for the workflow \'%3$s\' [\'%4$s\'].', array($nextState, $operation, $this->getID(), $this->getModule())));
     } else {
         $nextState = $params['nextstate'];
     }
     return $result;
 }