예제 #1
1
파일: Logging.php 프로젝트: Silwereth/core
 /**
  * Creates a new logging instance.
  *
  * @param Doctrine_Event $event  Event.
  * @param int            $opType I/U/D for Insert/Update/Delete.
  *
  * @return void
  */
 private function _createOperationLog(Doctrine_Event $event, $opType = 'I')
 {
     $data = $event->getInvoker();
     $tableName = $this->getTableNameFromEvent($event);
     $idColumn = $this->getIdColumnFromEvent($event);
     $log = array();
     $log['object_type'] = $tableName;
     $log['object_id'] = $data[$idColumn];
     $log['op'] = $opType;
     if ($opType == 'U') {
         $oldValues = $data->getLastModified(true);
         $diff = array();
         foreach ($oldValues as $column => $oldValue) {
             if (empty($oldValue) && isset($data[$column]) && !empty($data[$column])) {
                 $diff[$column] = 'I: ' . $data[$column];
             } elseif (!empty($oldValue) && isset($data[$column]) && !empty($data[$column])) {
                 $diff[$column] = 'U: ' . $data[$column];
             } elseif (!empty($oldValue) && empty($data[$column])) {
                 $diff[$column] = 'D: ' . $oldValue;
             }
         }
         $log['diff'] = serialize($diff);
     } else {
         // Convert object to array (otherwise we serialize the record object)
         $log['diff'] = serialize($data->toArray());
     }
     DBUtil::insertObject($log, 'objectdata_log');
 }
예제 #2
0
    /**
     * Create a new topic
     * @author:     Albert Pï¿œrez Monfort (aperezm@xtec.cat)
     * @param:	args	array with the topic information
     * @return:	identity of the new record created or false if error
     */
    public function crear($args) {
        $nomtema = FormUtil::getPassedValue('nomtema', isset($args['nomtema']) ? $args['nomtema'] : null, 'POST');
        $descriu = FormUtil::getPassedValue('descriu', isset($args['descriu']) ? $args['descriu'] : null, 'POST');
        $grup = FormUtil::getPassedValue('grup', isset($args['grup']) ? $args['grup'] : null, 'POST');

        // Security check
        if (!SecurityUtil::checkPermission('IWnoteboard::', '::', ACCESS_ADMIN)) {
            return LogUtil::registerPermissionError();
        }

        // Needed argument
        if (!isset($nomtema)) {
            return LogUtil::registerError($this->__('Error! Could not do what you wanted. Please check your input.'));
        }

        // Optional argument
        if (!isset($descriu)) {
            $descriu = '';
        }

        $item = array('nomtema' => $nomtema,
            'descriu' => $descriu,
            'grup' => $grup);

        if (!DBUtil::insertObject($item, 'IWnoteboard_topics', 'tid')) {
            return LogUtil::registerError($this->__('Error! Creation attempt failed.'));
        }

        // Return the id of the newly created item to the calling process
        return $item['tid'];
    }
예제 #3
0
/**
 * create a new Admin_Messages item
 * @author Mark West
 * @param string $args['title'] title of the admin message
 * @param string $args['content'] text of the admin message
 * @param string $args['language'] the language of the message
 * @param int $args['active'] activation status of the message
 * @param int $args['expire'] expiry date of the message
 * @param int $args['view'] who can view the message
 * @return mixed Admin_Messages item ID on success, false on failure
 */
function Admin_Messages_adminapi_create($args)
{
    $dom = ZLanguage::getModuleDomain('Admin_Messages');
    // Argument check
    if (!isset($args['title']) || !isset($args['content']) || !isset($args['language']) || !isset($args['active']) || !isset($args['expire']) || !isset($args['view'])) {
        return LogUtil::registerArgsError();
    }
    if (empty($args['title']) && empty($args['content'])) {
        return LogUtil::registerArgsError();
    }
    // Security check
    if (!SecurityUtil::checkPermission('Admin_Messages::', '::', ACCESS_ADD)) {
        return LogUtil::registerPermissionError();
    }
    // create the item array
    $item = array('title' => $args['title'], 'content' => $args['content'], 'language' => $args['language'], 'active' => $args['active'], 'view' => $args['view']);
    // add some additional modified values
    if ($args['expire'] < 0) {
        $args['expire'] = 0;
    }
    $item['expire'] = $args['expire'] * 86400;
    // turns days into seconds
    $item['date'] = time();
    if (!DBUtil::insertObject($item, 'message', 'mid')) {
        return LogUtil::registerError(__('Error! Could not create the new item.', $dom));
    }
    // Let any hooks know that we have created a new item.
    ModUtil::callHooks('item', 'create', $item['mid'], array('module' => 'Admin_Messages'));
    // Return the id of the newly created item to the calling process
    return $item['mid'];
}
예제 #4
0
    /**
     * Insert a new URL reference into the database
     *
     * @param    $args['ref']			Reference of the item
     * @param    $args['url']			URL website
     * @param    $args['description']	Reference description
     * @param    $args['scrolls']		The iframe show the scrolls
      1	- Yes (auto)
      0	- No
     * @param    $args['width']			Width of the iframe
     * @param    $args['height']		Height of the iframe
     * @param    $args['widthunit']		Unit used in the width specified
      %	- percentual
      px	- pixels
     * @return   mixed                  Reference ID on success, false on failure
     */
    public function create($args) {
        // Optiona argument
        if (!isset($args['description']))
            $args['description'] = '';

        // Check if args have arrived properly
        if (!isset($args['url']) || !isset($args['ref'])) {
            return LogUtil::registerError($this->__('Error! Could not do what you wanted. Please check your input.'));
        }
        $args['scrolls'] = ($args['scrolls'] == 'on') ? '1' : '0';

        // Security check
        if (!SecurityUtil::checkPermission('IWwebbox::', '::', ACCESS_ADD)) {
            return LogUtil::registerPermissionError();
        }

        if (!DBUtil::insertObject($args, 'IWwebbox', 'pid')) {
            return LogUtil::registerError($this->__('Error! Creation attempt failed.'));
        }

        // Let any hooks know that we have created a new item
        ModUtil::callHooks('item', 'create', $args['pid'], array('module' => 'IWwebbox'));

        return $args['pid'];
    }
예제 #5
0
    /**
     * create a new RSS item
     * @param $args['feedname'] name of the item
     * @param $args['number'] number of the item
     * @return mixed RSS item ID on success, false on failure
     */
    public function create($args)
    {
        // Argument check
        if (!isset($args['name']) || !isset($args['url'])) {
            return LogUtil::registerArgsError();
        }

        // Security check
        if (!SecurityUtil::checkPermission('Feeds::Item', "$args[name]::", ACCESS_ADD)) {
            return LogUtil::registerPermissionError();
        }

        // check for maximum length to avoid cutting off URLs
        if (strlen($args['url'] > 255)) {
            return LogUtil::registerError($this->__('The provided URL is too long (200 chars max.).'));
        }

        // Check for a protocol Magpie RSS (more exactly Snoopy) can handle.
        $url_parts = parse_url($args['url']);
        if (!isset($url_parts['scheme']) || ($url_parts['scheme'] != 'http' && $url_parts['scheme'] != 'https')) {
            return LogUtil::registerError($this->__('Invalid protocol selected. Only http and https are allowed.'));
        }

        // define the permalink title if not present
        if (!isset($args['urltitle']) || empty($args['urltitle'])) {
            $args['urltitle'] = DataUtil::formatPermalink($args['name']);
        }

        if (!DBUtil::insertObject($args, 'feeds', 'fid')) {
            return LogUtil::registerError($this->__('Error! Creation attempt failed.'));
        }

        // Return the id of the newly created item to the calling process
        return $args['fid'];
    }
예제 #6
0
    /**
     * create a new page
     * @param $args['title'] name of the item
     * @param $args['content'] content of the item
     * @param $args['language'] language of the item
     * @return mixed page ID on success, false on failure
     */
    public function create($args)
    {
        // Argument check
        if (!isset($args['title']) || !isset($args['content'])) {
            return LogUtil::registerArgsError();
        }

        $this->throwForbiddenUnless(SecurityUtil::checkPermission('Pages::', $args['title'] . '::', ACCESS_ADD), LogUtil::getErrorMsgPermission());

        // defaults
        if (!isset($args['language'])) {
            $args['language'] = '';
        }
        if (!isset($args['displaywrapper'])) {
            $args['displaywrapper'] = 0;
        }
        if (!isset($args['displaytitle'])) {
            $args['displaytitle'] = 0;
        }
        if (!isset($args['displaycreated'])) {
            $args['displaycreated'] = 0;
        }
        if (!isset($args['displayupdated'])) {
            $args['displayupdated'] = 0;
        }
        if (!isset($args['displaytextinfo'])) {
            $args['displaytextinfo'] = 0;
        }
        if (!isset($args['displayprint'])) {
            $args['displayprint'] = 0;
        }

        // define the permalink title if not present
        $urltitlecreatedfromtitle = false;
        if (!isset($args['urltitle']) || empty($args['urltitle'])) {
            $args['urltitle'] = DataUtil::formatPermalink($args['title']);
            $urltitlecreatedfromtitle = true;
        }

        if (ModUtil::apiFunc('Pages', 'admin', 'checkuniquepermalink', $args) == false) {
            $args['urltitle'] = '';
            if ($urltitlecreatedfromtitle == true) {
                LogUtil::registerStatus($this->__('The permalinks retrieved from the title has to be unique!'));
            } else {
                LogUtil::registerStatus($this->__('The permalink has to be unique!'));
            }
            LogUtil::registerStatus($this->__('The permalink has been removed, please update the page with a correct and unique permalink'));
        }

        if (!DBUtil::insertObject($args, 'pages', 'pageid')) {
            return LogUtil::registerError($this->__('Error! Creation attempt failed.'));
        }

        // An item was created, so we clear all cached pages of the items list.
        ModUtil::apiFunc('Pages', 'user', 'clearItemCache', $args);

        // Return the id of the newly created item to the calling process
        return $args['pageid'];
    }
예제 #7
0
    /**
     * Initialise the IWmenu module creating module tables and module vars
     * @author Albert Perez Monfort (aperezm@xtec.cat)
     * @return bool true if successful, false otherwise
     */
    public function Install() {
        // Checks if module IWmain is installed. If not returns error
        $modid = ModUtil::getIdFromName('IWmain');
        $modinfo = ModUtil::getInfo($modid);

        if ($modinfo['state'] != 3) {
            return LogUtil::registerError($this->__('Module IWmain is needed. You have to install the IWmain module previously to install it.'));
        }

        // Check if the version needed is correct
        $versionNeeded = '3.0.0';
        if (!ModUtil::func('IWmain', 'admin', 'checkVersion', array('version' => $versionNeeded))) {
            return false;
        }

        // Create module table
        if (!DBUtil::createTable('IWmenu'))
            return false;

        //Create indexes
        $pntable = DBUtil::getTables();
        $c = $pntable['IWmenu_column'];
        if (!DBUtil::createIndex($c['id_parent'], 'IWmenu', 'id_parent'))
            return false;

        //Create module vars
        ModUtil::setVar('IWmenu', 'height', 26); // Default height
        ModUtil::setVar('IWmenu', 'width', 200); // Default width
        ModUtil::setVar('IWmenu', 'imagedir', "menu"); // Default directori of menu images
        // checks if module vhmenu exists. If it exists import module vhmenu tables
        $modid = ModUtil::getIdFromName('IWmenu');
        $modinfo = ModUtil::getInfo($modid);
        if ($modinfo['state'] == 3) {
            // get the objects from the db
            ModUtil::load('IWvhmenu', 'user');
            $items = DBUtil::selectObjectArray('IWvhmenu');
            if ($items) {
                foreach ($items as $item) {
                    $groups = str_replace('|0', '', $item['groups']);
                    $groups = substr($groups, 1, strlen($groups));
                    $itemArray = array('text' => $item['text'],
                        'url' => $item['url'],
                        'icon' => '',
                        'id_parent' => $item['id_parent'],
                        'groups' => $groups,
                        'active' => $item['active'],
                        'target' => $item['target'],
                        'descriu' => $item['descriu']);

                    DBUtil::insertObject($itemArray, 'IWmenu', 'mid');
                }
            }
        }
        return true;
    }
예제 #8
0
 function addfavourite()
 {
     $objectid = FormUtil::getPassedValue('objectid', null, 'POST');
     $userid = FormUtil::getPassedValue('userid', null, 'POST');
     if (!SecurityUtil::checkPermission('AddressBook::', "::", ACCESS_COMMENT)) {
         AjaxUtil::error($this->__('Error! No authorization to access this module.'));
     }
     $obj['favadr_id'] = $objectid;
     $obj['favuser_id'] = $userid;
     DBUtil::insertObject($obj, 'addressbook_favourites');
     return;
 }
예제 #9
0
 /**
  * Install the Reviews application.
  *
  * @return boolean True on success, or false.
  */
 public function install()
 {
     // Check if upload directories exist and if needed create them
     try {
         $controllerHelper = new Reviews_Util_Controller($this->serviceManager);
         $controllerHelper->checkAndCreateAllUploadFolders();
     } catch (\Exception $e) {
         return LogUtil::registerError($e->getMessage());
     }
     // create all tables from according entity definitions
     try {
         DoctrineHelper::createSchema($this->entityManager, $this->listEntityClasses());
     } catch (\Exception $e) {
         if (System::isDevelopmentMode()) {
             return LogUtil::registerError($this->__('Doctrine Exception: ') . $e->getMessage());
         }
         $returnMessage = $this->__f('An error was encountered while creating the tables for the %s extension.', array($this->name));
         if (!System::isDevelopmentMode()) {
             $returnMessage .= ' ' . $this->__('Please enable the development mode by editing the /config/config.php file in order to reveal the error details.');
         }
         return LogUtil::registerError($returnMessage);
     }
     // set up all our vars with initial values
     $this->setVar('enablecategorization', false);
     $this->setVar('pagesize', 10);
     $this->setVar('scoreForUsers', false);
     $this->setVar('addcategorytitletopermalink', false);
     $categoryRegistryIdsPerEntity = array();
     // add default entry for category registry (property named Main)
     include_once 'modules/Reviews/lib/Reviews/Api/Base/Category.php';
     include_once 'modules/Reviews/lib/Reviews/Api/Category.php';
     $categoryApi = new Reviews_Api_Category($this->serviceManager);
     $categoryGlobal = CategoryUtil::getCategoryByPath('/__SYSTEM__/Modules/Global');
     $registryData = array();
     $registryData['modname'] = $this->name;
     $registryData['table'] = 'Review';
     $registryData['property'] = $categoryApi->getPrimaryProperty(array('ot' => 'Review'));
     $registryData['category_id'] = $categoryGlobal['id'];
     $registryData['id'] = false;
     if (!DBUtil::insertObject($registryData, 'categories_registry')) {
         LogUtil::registerError($this->__f('Error! Could not create a category registry for the %s entity.', array('review')));
     }
     $categoryRegistryIdsPerEntity['review'] = $registryData['id'];
     // create the default data
     $this->createDefaultData($categoryRegistryIdsPerEntity);
     // register persistent event handlers
     $this->registerPersistentEventHandlers();
     // register hook subscriber bundles
     HookUtil::registerSubscriberBundles($this->version->getHookSubscriberBundles());
     // initialisation successful
     return true;
 }
예제 #10
0
 function createFile($filename, $args)
 {
     $dom = ZLanguage::getModuleDomain('mediashare');
     $fileReference = "vfsdb/{$args['baseFileRef']}-{$args['fileMode']}.{$args['fileType']}";
     $data = file_get_contents($filename);
     $bytes = count($data);
     $record = array('fileref' => $fileReference, 'mode' => $args['fileMode'], 'type' => $args['fileType'], 'bytes' => $bytes, 'data' => $data);
     $result = DBUtil::insertObject($record, 'mediashare_mediadb', 'id');
     if ($result === false) {
         return LogUtil::registerError(__f('Error in %1$s: %2$s.', array('vfsHandlerDB.createFile', 'Could not retrieve insert the file information.'), $dom));
     }
     return $fileReference;
 }
예제 #11
0
function mediashare_sourcesapi_addSource($args)
{
    $dom = ZLanguage::getModuleDomain('mediashare');
    $title = $args['title'];
    $name = $args['name'];
    $pntable = pnDBGetTables();
    $sourcesColumn = $pntable['mediashare_sources_column'];
    $source = array('name' => $name, 'title' => $title, 'formEncType' => '');
    $result = DBUtil::insertObject($source, 'mediashare_sources', 'id');
    if ($result === false) {
        return LogUtil::registerError(__f('Error in %1$s: %2$s.', array('sourcesapi.addSource', 'Could not add a source.'), $dom));
    }
    return true;
}
예제 #12
0
 /**
  * Upgrade the MUVideo application from an older version.
  *
  * If the upgrade fails at some point, it returns the last upgraded version.
  *
  * @param integer $oldVersion Version to upgrade from.
  *
  * @return boolean True on success, false otherwise.
  */
 public function upgrade($oldVersion)
 {
     // Upgrade dependent on old version number
     switch ($oldVersion) {
         case '1.0.0':
             // update the database schema
             try {
                 DoctrineHelper::updateSchema($this->entityManager, $this->listEntityClasses());
             } catch (\Exception $e) {
                 if (System::isDevelopmentMode()) {
                     return LogUtil::registerError($this->__('Doctrine Exception: ') . $e->getMessage());
                 }
                 return LogUtil::registerError($this->__f('An error was encountered while updating tables for the %s extension.', array($this->getName())));
             }
             $categoryRegistryIdsPerEntity = array();
             // add default entry for category registry (property named Main)
             include_once 'modules/MUVideo/lib/MUVideo/Api/Base/Category.php';
             include_once 'modules/MUVideo/lib/MUVideo/Api/Category.php';
             $categoryApi = new MUVideo_Api_Category($this->serviceManager);
             $categoryGlobal = CategoryUtil::getCategoryByPath('/__SYSTEM__/Modules/Global');
             $registryData = array();
             $registryData['modname'] = $this->name;
             $registryData['table'] = 'Collection';
             $registryData['property'] = $categoryApi->getPrimaryProperty(array('ot' => 'Collection'));
             $registryData['category_id'] = $categoryGlobal['id'];
             $registryData['id'] = false;
             if (!DBUtil::insertObject($registryData, 'categories_registry')) {
                 LogUtil::registerError($this->__f('Error! Could not create a category registry for the %s entity.', array('collection')));
             }
             $categoryRegistryIdsPerEntity['collection'] = $registryData['id'];
             $registryData = array();
             $registryData['modname'] = $this->name;
             $registryData['table'] = 'Movie';
             $registryData['property'] = $categoryApi->getPrimaryProperty(array('ot' => 'Movie'));
             $registryData['category_id'] = $categoryGlobal['id'];
             $registryData['id'] = false;
             if (!DBUtil::insertObject($registryData, 'categories_registry')) {
                 LogUtil::registerError($this->__f('Error! Could not create a category registry for the %s entity.', array('movie')));
             }
             $categoryRegistryIdsPerEntity['movie'] = $registryData['id'];
             // unregister persistent event handlers
             EventUtil::unregisterPersistentModuleHandlers($this->name);
             // register persistent event handlers
             $this->registerPersistentEventHandlers();
         case '1.1.0':
             // for later updates
     }
     // update successful
     return true;
 }
예제 #13
0
function mediashare_invitationapi_createInvitationId($args)
{
    $dom = ZLanguage::getModuleDomain('mediashare');
    do {
        $key = mediashareCreateInvitationKey();
        $record = array('albumId' => (int) $args['albumId'], 'created' => DateUtil::getDatetime(), 'key' => $key, 'email' => $args['email'], 'subject' => $args['subject'], 'text' => $args['text'], 'sender' => $args['sender'], 'expires' => !empty($args['expires']) ? $args['expires'] : null);
        $result = DBUtil::insertObject($record, 'mediashare_invitation', 'id');
        if ($result == false) {
            return LogUtil::registerError(__f('Error in %1$s: %2$s.', array('invitationapi.createInvitationId', 'Could not create the invitation.'), $dom));
        }
    } while (false);
    // FIXME: add "key exists" check
    return $key;
}
예제 #14
0
파일: Admin.php 프로젝트: rmaiwald/Scribite
 public function addmodule($args)
 {
     $this->throwForbiddenUnless(SecurityUtil::checkPermission('Scribite::', '::', ACCESS_ADMIN), LogUtil::getErrorMsgPermission());
     // Argument check
     if (!isset($args['modulename']) || !isset($args['modfuncs']) || !isset($args['modareas']) || !isset($args['modeditor'])) {
         return LogUtil::registerError($this->__('Error! Could not do what you wanted. Please check your input.'));
     }
     // add item
     $additem = array('modname' => $args['modulename'], 'modfuncs' => serialize(explode(',', $args['modfuncs'])), 'modareas' => serialize(explode(',', $args['modareas'])), 'modeditor' => $args['modeditor']);
     if (!DBUtil::insertObject($additem, 'scribite', 'mid', false)) {
         return LogUtil::registerError($this->__('Configuration not updated'));
     }
     return true;
 }
예제 #15
0
    /**
     * Search plugin main function
     **/
    public function search($args)
    {
        if (!SecurityUtil::checkPermission('News::', '::', ACCESS_READ)) {
            return true;
        }

        ModUtil::dbInfoLoad('Search');
        $tables = DBUtil::getTables();
        $newsColumn = $tables['news_column'];

        $where = Search_Api_User::construct_where($args,
                array($newsColumn['title'],
                $newsColumn['hometext'],
                $newsColumn['bodytext']),
                $newsColumn['language']);
        // Only search in published articles that are currently visible
        $where .= " AND ({$newsColumn['published_status']} = '0')";
        $date = DateUtil::getDatetime();
        $where .= " AND ('$date' >= {$newsColumn['from']} AND ({$newsColumn['to']} IS NULL OR '$date' <= {$newsColumn['to']}))";

        $sessionId = session_id();

        ModUtil::loadApi('News', 'user');

        $permChecker = new News_ResultChecker($this->getVar('enablecategorization'), $this->getVar('enablecategorybasedpermissions'));
        $articles = DBUtil::selectObjectArrayFilter('news', $where, null, null, null, '', $permChecker, null);

        foreach ($articles as $article)
        {
            $item = array(
                'title' => $article['title'],
                'text'  => $article['hometext'],
                'extra' => $article['sid'],
                'created' => $article['from'],
                'module'  => 'News',
                'session' => $sessionId
            );
            $insertResult = DBUtil::insertObject($item, 'search_result');
            if (!$insertResult) {
                return LogUtil::registerError($this->__('Error! Could not load any articles.'));
            }
        }

        return true;
    }
예제 #16
0
파일: Admin.php 프로젝트: nmpetkov/Quotes
 /**
  * Create Quote
  * @author Greg Allan
  * @author The Zikula Development Team
  * @param 'qquote' quote text
  * @param 'qauthor' quote author
  * @param 'status' quote status
  * @return id of quote if success, false otherwise
  */
 public function create($quote)
 {
     // the argument associative array represents an object/row argument check
     if (!isset($quote['quote']) || !isset($quote['author'])) {
         return LogUtil::registerArgsError();
     }
     // security check
     if (!SecurityUtil::checkPermission('Quotes::', '::', ACCESS_ADD)) {
         return LogUtil::registerPermissionError();
     }
     // insert the object and check the return value for error
     $res = DBUtil::insertObject($quote, 'quotes', 'qid');
     if (!$res) {
         return LogUtil::registerError($this->__('Error! Quote creation failed.'));
     }
     // return the id of the newly created item to the calling process
     return $quote['qid'];
 }
예제 #17
0
 /**
  * Create user files info
  * @author:    Albert Pérez Monfort
  * @return:	   And a new row to table for the user
  */
 public function createUserFilesInfo()
 {
     // security check
     if (!SecurityUtil::checkPermission('Files::', '::', ACCESS_ADD)) {
         return LogUtil::registerPermissionError();
     }
     $uid = UserUtil::getVar('uid');
     // check if user exists. If not create it
     if (!ModUtil::apiFunc('Files', 'user', 'get', array('userId' => $uid))) {
         // get user disk quota
         $diskQuota = ModUtil::func('Files', 'user', 'getUserQuota', array('userId' => $uid));
         // create record for the user
         $item = array('userId' => DataUtil::formatForStore($uid), 'quota' => DataUtil::formatForStore($diskQuota));
         if (!DBUtil::insertObject($item, 'Files')) {
             return LogUtil::registerError($this->__('Error! Could not create the new item.'));
         }
     }
     return true;
 }
예제 #18
0
/**
 * Do the migration
 * 
 * With this function, the actual migration is done.
 * 
 * @return   boolean   true on sucessful migration, false else
 */
function EZComments_migrateapi_pnComments()
{
    if (!SecurityUtil::checkPermission('EZComments::', '::', ACCESS_ADMIN)) {
        return LogUtil::registerPermissionError();
    }
    if (!ModUtil::available('pnComments')) {
        return LogUtil::RegisterError('pnComments not available');
    }
    ModUtil::dbInfoLoad('pnComments');
    $comments = DBUtil::SelectObjectArray('pncomments');
    $counter = 0;
    foreach ($comments as $c) {
        $obj = array('modname' => $c['module'], 'objectid' => $c['objectid'], 'comment' => $c['text'], 'replyto' => -1, 'subject' => $c['subject'], 'uid' => $c['uid'], 'date' => $c['date'] . ' 00:00:00');
        if (!DBUtil::insertObject($obj, 'EZComments')) {
            return LogUtil::registerError('error inserting comments in ezcomments table');
        }
        $counter++;
    }
    return LogUtil::registerStatus("Migrated: {$counter} comments successfully.");
}
예제 #19
0
 public function createUser($user){
     if ($user) {
         $user['zk']['approved_date'] = DateUtil::getDatetime();
         $user['zk']['user_regdate'] = DateUtil::getDatetime();
         $user['zk']['approved_by'] = 2;
         DBUtil::insertObject($user['zk'], 'users', 'uid');
         $insertUserId = $user['zk']['uid'];
         $user['iw']['uid'] = $insertUserId;
         $user['iw']['suid'] = $insertUserId;
         DBUtil::insertObject($user['iw'], 'IWusers', 'suid');
         //Assignem els grups indicats en el formulari
         foreach ($user['gr'] as $grup) {
             $item = array('gid' => $grup, 'uid' => $user['zk']['uid']);
             DBUtil::insertObject($item, 'group_membership');
         }
         return $insertUserId;
     }else {
         return false;
     }
 }    
예제 #20
0
    public function createCategory($args) {

        // Security check
        if (!SecurityUtil::checkPermission('IWdocmanager::', "::", ACCESS_ADMIN)) {
            throw new Zikula_Exception_Forbidden();
        }

        $item = array('categoryName' => $args['categoryName'],
            'description' => $args['description'],
            'groups' => $args['groups'],
            'groupsAdd' => $args['groupsAdd'],
            'active' => $args['active'],
            'parentId' => $args['parent'],
        );

        if (!DBUtil::insertObject($item, 'IWdocmanager_categories', 'categoryId')) {
            return LogUtil::registerError($this->__('Error! Creation attempt failed.'));
        }

        // Return the id of the newly created item to the calling process
        return $item['categoryId'];
    }
예제 #21
0
    /**
     * Create a new forum in database
     * @author	Albert Pï¿œrez Monfort (aperezm@xtec.cat)
     * @param:	args   Array with the forum properties
     * @return	true if success
     */
    public function create($args) {
        $item = FormUtil::getPassedValue('item', isset($args['item']) ? $args['item'] : null, 'POST');
        
        // Security check
        if (!SecurityUtil::checkPermission('IWforums::', "::", ACCESS_ADMIN)) {
            throw new Zikula_Exception_Forbidden();
        }

        //Needed arguments
        if ((!isset($item['nom_forum']))) {
            return LogUtil::registerError($this->__('Error! Could not do what you wanted. Please check your input.'));
        }

        if (!DBUtil::insertObject($item, 'IWforums_definition', 'fid')) {
            return LogUtil::registerError($this->__('Error! Creation attempt failed.'));
        }

        // Let any hooks know that we have created a new item
        ModUtil::callHooks('item', 'create', $item['fid'],
                        array('module' => 'IWforums'));

        return $item['fid'];
    }
예제 #22
0
 /**
  * Create a new Ephemeride item
  * @author The Zikula Development Team
  * @param 'status' item status
  * @return id of item if success, false otherwise
  */
 public function create($ephemeride)
 {
     // Argument check
     if (!isset($ephemeride['did']) || !isset($ephemeride['mid']) || !isset($ephemeride['yid']) || !isset($ephemeride['content']) || !isset($ephemeride['language'])) {
         return LogUtil::registerArgsError();
     }
     if (!isset($ephemeride['status'])) {
         $ephemeride['status'] = 1;
     }
     if (!isset($ephemeride['type'])) {
         $ephemeride['type'] = 1;
     }
     // security check
     if (!SecurityUtil::checkPermission('Ephemerides::', '::', ACCESS_ADD)) {
         return LogUtil::registerPermissionError();
     }
     // insert the object and check the return value for error
     $res = DBUtil::insertObject($ephemeride, 'ephem', 'eid');
     if (!$res) {
         return LogUtil::registerError($this->__('Error! Ephemeride creation failed.'));
     }
     // return the id of the newly created item to the calling process
     return $ephemeride['eid'];
 }
예제 #23
0
 public function upgrade_MigrateLanguageCodes()
 {
     $objArray = DBUtil::selectObjectArray('categories_category');
     DBUtil::truncateTable('categories_category');
     $newObjArray = array();
     foreach ($objArray as $category) {
         // translate display_name l3 -> l2
         $data = unserialize($category['display_name']);
         if (is_array($data)) {
             $array = array();
             foreach ($data as $l3 => $v) {
                 $l2 = ZLanguage::translateLegacyCode($l3);
                 if ($l2) {
                     $array[$l2] = $v;
                 }
             }
             $category['display_name'] = serialize($array);
         }
         // translate display_desc l3 -> l2
         $data = unserialize($category['display_desc']);
         if (is_array($data)) {
             $array = array();
             foreach ($data as $l3 => $v) {
                 $l2 = ZLanguage::translateLegacyCode($l3);
                 if ($l2) {
                     $array[$l2] = $v;
                 }
             }
             $category['display_desc'] = serialize($array);
         }
         // commit
         DBUtil::insertObject($category, 'categories_category', 'id', true);
     }
     return;
 }
예제 #24
0
파일: DBObject.php 프로젝트: Silwereth/core
 /**
  * Generic insert handler for an object (ID is inserted into the object data).
  *
  * @return array|boolean The Object Data.
  */
 public function insert()
 {
     if (!$this->insertPreProcess()) {
         return false;
     }
     $res = DBUtil::insertObject($this->_objData, $this->_objType, $this->_objField, $this->_objInsertPreserve, $this->_objInsertForce);
     if ($res) {
         $this->insertPostProcess();
         return $this->_objData;
     }
     return false;
 }
예제 #25
0
파일: User.php 프로젝트: projectesIF/Sirius
    /**
     * Log search query for search statistics.
     */
    public function log($args)
    {
        $searchterms = DataUtil::formatForStore($args['q']);

        $obj = DBUtil::selectObjectByID('search_stat', $searchterms, 'search');

        $newobj['count'] = isset($obj['count']) ? $obj['count'] + 1 : 1;
        $newobj['date'] = date('Y-m-d H:i:s');
        $newobj['search'] = $searchterms;

        if (!isset($obj) || empty($obj)) {
            $res = DBUtil::insertObject($newobj, 'search_stat');
        } else {
            $res = DBUtil::updateObject($newobj, 'search_stat', '', 'search');
        }

        if (!$res) {
            return false;
        }

        return true;
    }
예제 #26
0
파일: User.php 프로젝트: projectesIF/Sirius
 public function changeDescription($args) {
     // Security check
     if (!SecurityUtil::checkPermission('IWusers::', '::', ACCESS_READ) || !ModUtil::getVar('IWusers', 'allowUserDescribeTheirSelves') == 1) {
         throw new Zikula_Exception_Forbidden();
     }
     $user = ModUtil::apiFunc('IWusers', 'user', 'get', array('uid' => UserUtil::getvar('uid')));
     if (!$user) {
         $items = array('uid' => UserUtil::getVar('uid'));
         // create user
         if (!DBUtil::insertObject($items, 'IWusers', 'suid')) {
             return LogUtil::registerError($this->__('Error! Creation attempt failed.'));
         }
     }
     $pntables = DBUtil::getTables();
     $c = $pntables['IWusers_column'];
     $where = "WHERE $c[uid]=" . UserUtil::getVar('uid');
     $item = array('description' => $args['description']);
     if (!DBUtil::updateObject($item, 'IWusers', $where)) {
         return LogUtil::registerError($this->__('Error! Update attempt failed.'));
     }
     return true;
 }
예제 #27
0
 public function requireLock($args)
 {
     $lockName = $args['lockName'];
     $sessionId = array_key_exists('sessionId', $args) ? $args['sessionId'] : session_id();
     $lockedByTitle = $args['lockedByTitle'];
     $lockedByIPNo = $args['lockedByIPNo'];
     $this->_pageLockRequireAccess();
     $locks = ModUtil::apiFunc('pagelock', 'user', 'getLocks', $args);
     if (count($locks) > 0) {
         $lockedBy = '';
         foreach ($locks as $lock) {
             if (strlen($lockedBy) > 0) {
                 $lockedBy .= ', ';
             }
             $lockedBy .= $lock['lockedByTitle'] . " ({$lock['lockedByIPNo']}) " . $lock['createdDate'];
         }
         return array('hasLock' => false, 'lockedBy' => $lockedBy);
     }
     $args['lockedBy'] = null;
     $dbtable = DBUtil::getTables();
     $pageLockTable =& $dbtable['pagelock'];
     $pageLockColumn =& $dbtable['pagelock_column'];
     // Look for existing lock
     $sql = "\nSELECT COUNT(*)\nFROM {$pageLockTable}\nWHERE {$pageLockColumn['name']} = '" . DataUtil::formatForStore($lockName) . "' AND {$pageLockColumn['lockedBySessionId']} = '" . DataUtil::formatForStore($sessionId) . "'";
     $count = DBUtil::selectScalar($sql);
     $now = time();
     $expireDate = $now + PageLockLifetime;
     if ($count > 0) {
         // Update existing lock
         $sql = "\nUPDATE {$pageLockTable}\nSET {$pageLockColumn['expiresDate']} = '" . DateUtil::getDatetime($expireDate) . "'\nWHERE {$pageLockColumn['name']} = '" . DataUtil::formatForStore($lockName) . "' AND {$pageLockColumn['lockedBySessionId']} = '" . DataUtil::formatForStore($sessionId) . "'";
         DBUtil::executeSql($sql);
     } else {
         $data = array('name' => $lockName, 'createdDate' => DateUtil::getDatetime($now), 'expiresDate' => DateUtil::getDatetime($expireDate), 'lockedBySessionId' => $sessionId, 'lockedByTitle' => $lockedByTitle, 'lockedByIPNo' => $lockedByIPNo);
         DBUtil::insertObject($data, 'pagelock');
     }
     $this->_pageLockReleaseAccess();
     return array('hasLock' => true);
 }
예제 #28
0
 /**
  * Insert a categorization data object.
  *
  * @param array   $obj            The object we wish to store categorization data for.
  * @param string  $tablename      The object's tablename.
  * @param string  $idcolumn       The object's idcolumn (optional) (default='id').
  * @param boolean $wasUpdateQuery True after an update and false after an insert.
  *
  * @return The result from the category data insert operation
  */
 public static function storeObjectCategories($obj, $tablename, $idcolumn = 'id', $wasUpdateQuery = true)
 {
     if (!$obj) {
         throw new \Exception(__f('Invalid %1$s passed to %2$s.', array('object', __CLASS__ . '::' . __FUNCTION__)));
     }
     if (!$tablename) {
         throw new \Exception(__f('Invalid %1$s passed to %2$s.', array('tablename', __CLASS__ . '::' . __FUNCTION__)));
     }
     if (!$idcolumn) {
         throw new \Exception(__f('Invalid %1$s passed to %2$s.', array('idcolumn', __CLASS__ . '::' . __FUNCTION__)));
     }
     if (!ModUtil::dbInfoLoad('ZikulaCategoriesModule')) {
         return false;
     }
     if (!isset($obj['__CATEGORIES__']) || !is_array($obj['__CATEGORIES__']) || !$obj['__CATEGORIES__']) {
         return false;
     }
     if ($wasUpdateQuery) {
         self::deleteObjectCategories($obj, $tablename, $idcolumn);
     }
     // ensure that we don't store duplicate object mappings
     $values = array();
     foreach ($obj['__CATEGORIES__'] as $k => $v) {
         if (isset($values[$v])) {
             unset($obj['__CATEGORIES__'][$k]);
         } else {
             $values[$v] = 1;
         }
     }
     // cache category id arrays to improve performance with DBUtil::(insert|update)ObjectArray()
     static $modTableCategoryIDs = array();
     // Get the ids of the categories properties of the object
     $modname = isset($obj['__META__']['module']) ? $obj['__META__']['module'] : ModUtil::getName();
     $reg_key = $modname . '_' . $tablename;
     if (!isset($modTableCategoryIDs[$reg_key])) {
         $modTableCategoryIDs[$reg_key] = CategoryRegistryUtil::getRegisteredModuleCategoriesIds($modname, $tablename);
     }
     $reg_ids = $modTableCategoryIDs[$reg_key];
     $cobj = array();
     $cobj['table'] = $tablename;
     $cobj['obj_idcolumn'] = $idcolumn;
     $res = true;
     foreach ($obj['__CATEGORIES__'] as $prop => $cat) {
         // if there's all the data and the Registry exists
         // the category is mapped
         if ($cat && $prop && isset($reg_ids[$prop])) {
             $cobj['id'] = '';
             $cobj['modname'] = $modname;
             $cobj['obj_id'] = $obj[$idcolumn];
             $cobj['category_id'] = $cat;
             $cobj['reg_id'] = $reg_ids[$prop];
             $res = DBUtil::insertObject($cobj, 'categories_mapobj');
         }
     }
     $dbtables = DBUtil::getTables();
     if (isset($dbtables[$tablename])) {
         DBUtil::flushCache($tablename);
     }
     return (bool) $res;
 }
예제 #29
0
    protected function newBlockPositions()
    {
        $positions = ModUtil::apiFunc('Blocks', 'user', 'getallpositions');

        // create the search block position if doesn't exists
        if (!isset($positions['search'])) {
            $searchpid = ModUtil::apiFunc('Blocks', 'admin', 'createposition', array('name' => 'search', 'description' => $this->__('Search block')));
        } else {
            $searchpid = $positions['search']['pid'];
        }

        // restores the search block if not present
        $dbtable      = DBUtil::getTables();
        $blockscolumn = $dbtable['blocks_column'];
        $searchblocks = DBUtil::selectObjectArray('blocks', "$blockscolumn[bkey] = 'Search'");

        if (empty($searchblocks)) {
            $block = array('bkey' => 'Search', 'collapsable' => 1, 'defaultstate' => 1, 'language' => '', 'mid' => ModUtil::getIdFromName('Search'), 'title' => $this->__('Search box'), 'description' => '', 'positions' => array($searchpid));
            $block['bid'] = ModUtil::apiFunc('Blocks', 'admin', 'create', $block);
            ModUtil::apiFunc('Blocks', 'admin', 'update', $block);
        } else {
            // assign the block to the search position
            $blockplacement = array('bid' => $searchblocks[0]['bid'], 'pid' => $searchpid);
            DBUtil::insertObject($blockplacement, 'block_placements');
        }

        // create new block positions if they don't exist
        if (!isset($positions['header'])) {
            $header = ModUtil::apiFunc('Blocks', 'admin', 'createposition', array('name' => 'header', 'description' => $this->__('Header block')));
        }
        if (!isset($positions['footer'])) {
            $footer = ModUtil::apiFunc('Blocks', 'admin', 'createposition', array('name' => 'footer', 'description' => $this->__('Footer block')));
        }
        if (!isset($positions['bottomnav'])) {
            $bottomnav = ModUtil::apiFunc('Blocks', 'admin', 'createposition', array('name' => 'bottomnav', 'description' => $this->__('Bottom navigation block')));
        }
        if (!isset($positions['topnav'])) {
            $topnav = ModUtil::apiFunc('Blocks', 'admin', 'createposition', array('name' => 'topnav', 'description' => $this->__('Top navigation block')));

            // Build content for the top navigation menu
            $languages = ZLanguage::getInstalledLanguages();
            $saveLanguage = ZLanguage::getLanguageCode();
            foreach ($languages as $lang) {
                ZLanguage::setLocale($lang);
                ZLanguage::bindCoreDomain();
                $topnavcontent = array();
                $topnavcontent['displaymodules'] = '0';
                $topnavcontent['stylesheet'] = 'extmenu.css';
                $topnavcontent['template'] = 'blocks_block_extmenu_topnav.tpl';
                $topnavcontent['blocktitles'][$lang] = $this->__('Top navigation');
                $topnavcontent['links'][$lang][] = array('name' => $this->__('Home'), 'url' => '{homepage}', 'title' => $this->__("Go to the site's home page"), 'level' => 0, 'parentid' => null, 'image' => '', 'active' => '1');
                $topnavcontent['links'][$lang][] = array('name' => $this->__('My Account'), 'url' => '{Users}', 'title' => $this->__('Go to your account panel'), 'level' => 0, 'parentid' => null, 'image' => '', 'active' => '1');
                $topnavcontent['links'][$lang][] = array('name' => $this->__('Site search'), 'url' => '{Search}', 'title' => $this->__('Search this site'), 'level' => 0, 'parentid' => null, 'image' => '', 'active' => '1');
            }

            ZLanguage::setLocale($saveLanguage);
            $topnavcontent = serialize($topnavcontent);
            $topnavblock = array('bkey' => 'Extmenu', 'collapsable' => 1, 'defaultstate' => 1, 'language' => '', 'mid' => ModUtil::getIdFromName('Blocks'), 'title' => $this->__('Top navigation'), 'description' => '', 'content' => $topnavcontent, 'positions' => array($topnav));
            $topnavblock['bid'] = ModUtil::apiFunc('Blocks', 'admin', 'create', $topnavblock);
            ModUtil::apiFunc('Blocks', 'admin', 'update', $topnavblock);
        }
    }
예제 #30
0
function mediashare_mediahandlerapi_addMediaHandler($args)
{
    $dom = ZLanguage::getModuleDomain('mediashare');
    $handler = array('mimeType' => strtolower($args['mimeType']), 'fileType' => strtolower($args['fileType']), 'foundMimeType' => strtolower($args['foundMimeType']), 'foundFileType' => strtolower($args['foundFileType']), 'handler' => $args['handler'], 'title' => $args['title']);
    $result = DBUtil::insertObject($handler, 'mediashare_mediahandlers', 'id');
    if ($result === false) {
        return LogUtil::registerError(__f('Error in %1$s: %2$s.', array('mediahandlerapi.addHandler', 'Could not add a handler.'), $dom));
    }
    return true;
}