bash_sync_perms.php 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421
  1. <?php
  2. /**
  3. * by plabudda 2013-10-09:
  4. *
  5. * 1. install:
  6. * - create *.plist file:
  7. * # php /Library/Server/Web/Data/Sites/Default/SE/se-dev-pl/bash_sync_perms.php biuro.biall-net.pl addToLaunchctl
  8. * # php /Library/Server/Web/Data/Sites/Default/SE/bash_sync_perms.php biuro.medical-opakowania.pl addToLaunchctl
  9. * - load by launchctl:
  10. * # launchctl load /Library/LaunchDaemons/pl.biallnet.sync_perms.php.plist
  11. *
  12. * 2. uninstall:
  13. * - unload from launchctl:
  14. * # launchctl unload /Library/LaunchDaemons/pl.biallnet.sync_perms.php.plist
  15. *
  16. * 3. debug:
  17. * - debug by www:
  18. * /SE/se-dev-pl/bash_sync_perms.php?DBG=1
  19. * - more verbose debug:
  20. * /SE/se-dev-pl/bash_sync_perms.php?DBG=6
  21. * - task:
  22. * /SE/se-dev-pl/bash_sync_perms.php?task=task
  23. * /SE/se-dev-pl/bash_sync_perms.php?task=newFiles
  24. * /SE/se-dev-pl/bash_sync_perms.php?task=testParse
  25. * /SE/se-dev-pl/bash_sync_perms.php?task=task&PROJ_ID={projID} -- force update project
  26. *
  27. *
  28. * 4. Sync users: `ADMIN_USERS`.`A_STATUS` - OFF - manual sync from users table (groups from CRM_LISTA_ZASOBOW)
  29. * 'WAITING' - Kandydaci
  30. * 'NORMAL' - Aktywni pracownicy
  31. * 'DELETED' - Wyłączone konta
  32. * 'OFF_SOFT' - ?
  33. * 'OFF_HARD' - ?
  34. *
  35. * @2014-01 recomended by A.Binder migration to separate dirs of koresp scripts:
  36. * robienie katalogow dla korespondencji przy migracji na nowy typ pism
  37. #read PASSWORD
  38. #for a in `echo "select concat(ID,';---;',K_OD_KOGO,K_ZAWARTOS) from IN7_DZIENNIK_KORESP" |mysql -p$PASSWORD -uroot -Damssystem -h127.0.0.1 | sed 's/[^a-zA-Z0-9;-]/_/g' |sed 's/;---;/\./g' ` ;
  39. #do
  40. #echo mkdir $a
  41. #mkdir $a
  42. #done
  43. *do wywolania w katalogach IN/OUT:
  44. # cd IN
  45. # for a in `ls |awk -F'.' '{ print $1 }' ` ; do mv $a.* ../$a.*; done
  46. *
  47. *
  48. *
  49. * DONE: koresp format: PISMA/ID/...
  50. * DONE: projekty -> koresp hardlink PROJEKTY/ID..../_PISMA/{HL:pismo.pdf}
  51. * TODO: PROJEKTY/ID..../_PISMA/ permy tylko read/listing
  52. * TODO: hardlink druki: mkdir DRUKI/ID.{DESC}/_PROJEKT/{proj_folder}/{HL:pliki z proj bez podkatalogów}
  53. * TODO: DRUKI/ID.{DESC}/_PROJEKT/{proj_folder} permy tylko read/listing
  54. * -- TODO: DRUKI/ID.{DESC}/ - permy z bazy danych A_ADM_COMPANY, A_CLASSIFIED
  55. *
  56. *
  57. * DONE: Trigger po update/insert Koresp po aktualizacji permów plików projektu
  58. *
  59. * 5. Sync custom tables
  60. * TEST 2014-10-27: # php /Users/plabudda/rsync-dev/SE/bash_sync_perms.php biuro.biall-net.pl SyncPermsCustomTables
  61. * 5.1 Table list in CRM_CONFIG(key=_SYNC_TABLE_FILE_PERMS__TablesList)
  62. * table must be defined in .cnf--folders-{domain}.ini.php as section [{tblName}_COLUMN]
  63. * table must have fields: ID, L_APPOITMENT_USER, A_ADM_COMPANY, A_CLASSIFIED @see generateTasksNewRecords
  64. */
  65. ini_set('max_execution_time', 300);
  66. ini_set('memory_limit', '512M');
  67. define('DS', DIRECTORY_SEPARATOR);
  68. define('APP_PATH_ROOT', dirname(__FILE__));
  69. define('APP_PATH_WWW', dirname(__FILE__));
  70. define('APP_PATH_CONFIG', APP_PATH_ROOT . DS . 'config');
  71. // set ini to log errors into error log file
  72. ini_set('display_startup_errors', '0');
  73. ini_set('log_errors', '1');
  74. ini_set('error_log', '/var/log/apache2/error_log');// TODO: php.ini ?
  75. require_once APP_PATH_ROOT . DS . 'se-lib' . DS . 'Lib.php';
  76. Lib::loadClass('V');
  77. Lib::loadClass('Config');
  78. Lib::loadClass('DB');
  79. Lib::loadClass('User');
  80. Lib::loadClass('FoldersConfig');
  81. Lib::loadClass('FileUploader');
  82. if (isset($_SERVER["argv"][1])) {
  83. $_SERVER['SERVER_NAME'] = $_SERVER["argv"][1];
  84. }
  85. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'info') {
  86. $info = array();
  87. $info['max_execution_time'] = ini_get('max_execution_time');
  88. $info['memory_limit'] = ini_get('memory_limit');
  89. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">info (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($info);echo'</pre>';
  90. ini_set('max_execution_time', 300);
  91. ini_set('memory_limit', '512M');
  92. $info = array();
  93. $info['max_execution_time'] = ini_get('max_execution_time');
  94. $info['memory_limit'] = ini_get('memory_limit');
  95. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">info (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($info);echo'</pre>';
  96. }
  97. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'users') {
  98. SyncPerms::run(null, null, 'users', null);
  99. }
  100. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'usersAll') {
  101. SyncPerms::run(null, null, 'usersAll', null);
  102. }
  103. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'task') {
  104. SyncPerms::run(null, null, 'nextTask', null);
  105. }
  106. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'newFiles') {
  107. SyncPerms::run(null, null, 'newFiles', null);
  108. }
  109. else if (empty($_SERVER["argv"]) && V::get('task', '', $_GET) == 'testParse') {
  110. $cmd = " ls -Rlea . ";
  111. exec("cd '/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/1657.Rekrutacja_z_dnia_2012-06_25_na_stanowisko_Przedstawiciel_Handlowy/1/'; {$cmd} ", $filesWithPerms);
  112. //$line = "-rwxrwx---+ 1 _www workgroup 212367 Feb 25 2013 {file_name}";
  113. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPerms);echo'</pre>';
  114. $filesWithPermsTree = array();
  115. $lastName = '';
  116. $folderParent = '';
  117. foreach ($filesWithPerms as $line) {
  118. if (substr($line, 0, 1) == '-' || substr($line, 0, 1) == 'd') {// file name
  119. $fileParts = array();
  120. $filePartsArr = explode(' ', $line);
  121. $lastInd = 0;
  122. foreach ($filePartsArr as $vPart) {
  123. if ($lastInd > 7) {// file name
  124. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  125. $lastInd++;
  126. }
  127. else if (!empty($vPart) || $vPart === '0') {
  128. $fileParts[] = $vPart;
  129. $lastInd++;
  130. }
  131. }
  132. if (end($fileParts) == '..' || (end($fileParts) == '.' && $folderParent)) {
  133. $lastName = '..';
  134. continue;
  135. }
  136. $file = new stdClass();
  137. if (!isset($fileParts[8])) {
  138. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  139. //continue;
  140. } else {
  141. // fix file name from bad chars
  142. // [8] => CV_Kowalski Mariusz`.pdf
  143. // "-$Model Bialnet .xlsm" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1518
  144. // [11-Oct-2013 21:00:28 UTC] PHP Notice: Error-cmd: chmod -a# 3 "/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/500.2009-12-01.INNE.DOFINANSOWANIE_PROJEKT_KOLBUDY/2013-02-26_harmonogram_EDORADCA_Aktualny/-$harmonogram 01.2013.xlsx" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1518
  145. // [11-Oct-2013 21:00:27 UTC] PHP Notice: Error-cmd: chmod -a# 3 "/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/500.2009-12-01.INNE.DOFINANSOWANIE_PROJEKT_KOLBUDY/2012-04-19_oferta_gpon_sprint_po_poprawkach/-$Wycena GPON 2012 Biall-Net_spr v1.xlsx" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1518
  146. // [11-Oct-2013 20:56:25 UTC] PHP Notice: Error-cmd: chmod +a "user:prejsi allow write,append,writeattr,writeextattr,writesecurity,chown,read,execute,readattr,readextattr,readsecurity" "/Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY/1695.Projekt_glowny_dzialu_rozwoju_biznesu_oraz_dystrybucji_informacji/HANDLOWY/HANDLOWY_2012/OTOMIN/-$Otomin.xlsx" in /Users/plabudda/se-dev-pl/SE/bash_sync_perms.php on line 1517
  147. //$fileParts[8] = str_replace('\\', '\\\\', $fileParts[8]);
  148. //$fileParts[8] = str_replace(array('`', '$'), array('\`', '\$'), $fileParts[8]);
  149. }
  150. echo'<pre style="max-height:230px;overflow:auto;border:1px solid red;text-align:left;">line/$fileParts/$filePartsArr (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($line, $fileParts, $filePartsArr));echo'</pre>';
  151. $file->name = end($fileParts);
  152. $file->path = array();
  153. if ($folderParent) $file->path[] = $folderParent;
  154. $file->path[] = end($fileParts);
  155. $file->path = implode('/', $file->path);
  156. //$file->owner = $fileParts[2];
  157. //$file->group = $fileParts[3];
  158. //$file->perms = $fileParts[0];
  159. $file->isDir = (substr($line, 0, 1) == 'd');
  160. $file->permsExt = array();
  161. $filesWithPermsTree[$file->name] = $file;
  162. $lastName = $file;
  163. }
  164. else if (substr($line, 0, 1) == ' ') {// extended perm line
  165. if ($lastName == '..') {
  166. continue;
  167. }
  168. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  169. }
  170. else if (substr($line, 0, 2) == './' && substr($line, -1) == ':') {// folder
  171. $folderParent = substr($line, 2, -1);
  172. }
  173. else if (substr($line, 0, 5) == 'total') {
  174. continue;
  175. }
  176. else if (empty($line)) {
  177. $folderParent = '';
  178. continue;
  179. }
  180. }
  181. echo'<pre style="max-height:400px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPermsTree);echo'</pre>';
  182. }
  183. else if (empty($_SERVER["argv"]) && V::get('DBG', '', $_GET, 'int') > 0) {
  184. SyncPerms::run(null, null);
  185. }
  186. else {
  187. die("\n The second argument should be server domain - e.g. biuro.kike.pl \n");
  188. }
  189. if (!empty($_SERVER["argv"][0]) && !empty($_SERVER["argv"][1])) {
  190. $arg2 = (!empty($_SERVER["argv"][2]))? $_SERVER["argv"][2] : null;
  191. $arg3 = (!empty($_SERVER["argv"][3]))? $_SERVER["argv"][3] : null;
  192. SyncPerms::run($_SERVER["argv"][0], $_SERVER["argv"][1], $arg2, $arg3);
  193. }
  194. class SyncPerms {
  195. public static function installTable() {
  196. $db = DB::getDB();
  197. if (!$db) die("DB Error: No DB! L." . __LINE__);
  198. $sql = "
  199. CREATE TABLE IF NOT EXISTS `_SYNC_FILE_PERMS` (
  200. `ID` int(11) NOT NULL AUTO_INCREMENT,
  201. `ID_PROJECT` int(11) NOT NULL,
  202. `L_APPOITMENT_USER` varchar(64) DEFAULT '',
  203. `A_ADM_COMPANY` varchar(64) NOT NULL DEFAULT '',
  204. `A_CLASSIFIED` varchar(64) NOT NULL DEFAULT '',
  205. `PARENT_L_APPOITMENT_USER` varchar(64) NOT NULL DEFAULT '',
  206. `A_LAST_SYNC` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  207. `A_SYNCHRONIZED` tinyint(4) NOT NULL DEFAULT '0',
  208. `A_SYNC_RESULT` varchar(255) NOT NULL DEFAULT '',
  209. PRIMARY KEY (`ID`),
  210. UNIQUE KEY `ID_PROJECT` (`ID_PROJECT`)
  211. ) ENGINE=MyISAM DEFAULT CHARSET=latin2 ;
  212. ";
  213. $db->query($sql);
  214. $sql = " DROP TRIGGER IF EXISTS `KORESP_change_ID_PROJECT`; ";
  215. $db->query($sql);
  216. $sql = "
  217. CREATE DEFINER=`root`@`localhost` TRIGGER `KORESP_change_ID_PROJECT` AFTER UPDATE ON `IN7_DZIENNIK_KORESP`
  218. FOR EACH ROW BEGIN
  219. IF (NEW.`ID_PROJECT` != OLD.`ID_PROJECT` and NEW.`ID_PROJECT` > 0) or OLD.`M_DIST_FILES`!=NEW.`M_DIST_FILES` THEN
  220. update `_SYNC_FILE_PERMS` as s set
  221. s.`A_SYNCHRONIZED`=0
  222. where
  223. s.`ID_PROJECT`=NEW.`ID_PROJECT`
  224. or s.`ID_PROJECT`=OLD.`ID_PROJECT`;
  225. END IF;
  226. END
  227. ";
  228. $db->query($sql);
  229. $sql = " DROP TRIGGER IF EXISTS `KORESP_add_ID_PROJECT`; ";
  230. $db->query($sql);
  231. $sql = "
  232. CREATE DEFINER=`root`@`localhost` TRIGGER `KORESP_add_ID_PROJECT` AFTER INSERT ON `IN7_DZIENNIK_KORESP`
  233. FOR EACH ROW BEGIN
  234. IF NEW.`ID_PROJECT` > 0 THEN
  235. update `_SYNC_FILE_PERMS` as s set
  236. s.`A_SYNCHRONIZED`=0
  237. where
  238. s.`ID_PROJECT`=NEW.`ID_PROJECT`;
  239. END IF;
  240. END
  241. ";
  242. $db->query($sql);
  243. if (V::get('DBG', '', $_GET, 'int') > 0) {
  244. if ($db->has_errors()) {
  245. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">DB errors (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($db->get_errors());echo'</pre>';
  246. }
  247. }
  248. }
  249. public static function run($script_name, $domain, $arg2 = null, $arg3 = null) {
  250. if ($arg2 == 'addToLaunchctl') {
  251. $plistFile = "/Library/LaunchDaemons/pl.biallnet.sync_perms.{$domain}.php.plist";
  252. system("echo \"<?xml version=\"1.0\" encoding=\"UTF-8\"?>
  253. <!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
  254. <plist version=\"1.0\">
  255. <dict>
  256. <key>Disabled</key>
  257. <false/>
  258. <key>Label</key>
  259. <string>pl.biallnet.sync_perms.{$domain}.php</string>
  260. <key>UserName</key>
  261. <string>root</string>
  262. <key>ProgramArguments</key>
  263. <array>
  264. <string>php</string>
  265. <string>{$_SERVER["argv"][0]}</string>
  266. <string>{$_SERVER["argv"][1]}</string>
  267. </array>
  268. <key>StartInterval</key>
  269. <integer>60</integer>
  270. </dict>
  271. </plist>
  272. \" > {$plistFile}");
  273. echo "Run as root: launchctl load {$plistFile} \n";
  274. }
  275. else if ($arg2 == 'newFiles') {
  276. $time = new stdClass();
  277. $time->start = time();
  278. self::newFilesAction();
  279. $time->end = time();
  280. // TODO: print operation time if DBG
  281. }
  282. else if ($arg2 == 'nextTask') {
  283. $time = new stdClass();
  284. $time->start = time();
  285. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">nextTask</pre>';}
  286. self::installTable();
  287. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">installTable DONE</pre>';}
  288. self::generateTasksNewRecords();
  289. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">generateTasksNewRecords DONE</pre>';}
  290. self::generateTasksUpdated();
  291. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">generateTasksUpdated DONE</pre>';}
  292. $limit = V::get('_limit', 1, $_GET, 'int');
  293. for ($i = 0; $i < $limit; $i++) {
  294. $time->cur = time();
  295. if ($time->cur - $time->start > 60 * 5) {
  296. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:2px solid red;text-align:left;">Force-break time('.($time->cur - $time->start).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';echo'</pre>';}
  297. break;
  298. }
  299. $task = self::nextTaskAction();
  300. if (!$task) {
  301. break;
  302. }
  303. }
  304. }
  305. else if ($arg2 == 'testErrorLog') {
  306. echo "display_errors: " . ini_get("display_errors") . "\n";
  307. echo "display_startup_errors: " . ini_get("display_startup_errors") . "\n";
  308. echo "log_errors: " . ini_get("log_errors") . "\n";
  309. echo "error_reporting: " . ini_get("error_reporting") . "\n";
  310. echo "error_log: " . ini_get("error_log") . "\n";
  311. trigger_error("Notice: Test Error Log", E_USER_NOTICE);
  312. }
  313. else if ($arg2 == 'users') {
  314. self::usersAction();
  315. }
  316. else if ($arg2 == 'usersAll') {
  317. self::usersAllAction();
  318. }
  319. else if ($arg2 == 'SyncPermsCustomTables') {
  320. $DBG_TIME = true;
  321. $dbgTime = new stdClass();
  322. $dbgTime->startTime = microtime(true);
  323. $dbgTime->lastTime = $dbgTime->startTime;
  324. $customSync = new SyncPermsCustomTables();
  325. // TODO: $customSync->run();
  326. $customSync->fetchConfig();
  327. if ($DBG_TIME) {
  328. $dbgTime->curTime = microtime(true);
  329. trigger_error("DBG:time after-fetchConfig (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  330. $dbgTime->lastTime = $dbgTime->curTime;
  331. }
  332. $customSync->installTable();
  333. if ($DBG_TIME) {
  334. $dbgTime->curTime = microtime(true);
  335. trigger_error("DBG:time after-installTable (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  336. $dbgTime->lastTime = $dbgTime->curTime;
  337. }
  338. $rowId = (int)$arg3;
  339. if ($rowId > 0) {
  340. $customSync->executeTask('DEALS_TABLE', $rowId);
  341. }
  342. else {
  343. $customSync->generateTasksNewRecords();
  344. if ($DBG_TIME) {
  345. $dbgTime->curTime = microtime(true);
  346. trigger_error("DBG:time after-generateTasksNewRecords (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  347. $dbgTime->lastTime = $dbgTime->curTime;
  348. }
  349. $customSync->generateTasksUpdated();
  350. if ($DBG_TIME) {
  351. $dbgTime->curTime = microtime(true);
  352. trigger_error("DBG:time after-generateTasksUpdated (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  353. $dbgTime->lastTime = $dbgTime->curTime;
  354. }
  355. $customSync->newFilesAction();
  356. if ($DBG_TIME) {
  357. $dbgTime->curTime = microtime(true);
  358. trigger_error("DBG:time after-newFilesAction (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  359. $dbgTime->lastTime = $dbgTime->curTime;
  360. }
  361. $limit = 1000;
  362. for ($i = 0; $i < $limit; $i++) {
  363. $loopTasksFired = 0;
  364. foreach ($customSync->_tbls as $tblName => $tblConf) {
  365. $task = $customSync->nextTaskAction($tblName);
  366. if ($DBG_TIME) {
  367. $dbgTime->curTime = microtime(true);
  368. trigger_error("DBG:time after-nextTaskAction (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  369. $dbgTime->lastTime = $dbgTime->curTime;
  370. }
  371. if (!$task) {
  372. // TODO: rm $tblName from config to prevent searching for task in next loops
  373. unset($customSync->_tbls[$tblName]);
  374. continue;
  375. }
  376. $loopTasksFired++;
  377. }
  378. if (!$loopTasksFired) {
  379. if ($DBG_TIME) {
  380. $dbgTime->curTime = microtime(true);
  381. trigger_error("DBG:time after-nextTaskAction (loop:{$i}) (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  382. $dbgTime->lastTime = $dbgTime->curTime;
  383. }
  384. break;
  385. }
  386. $i += $loopTasksFired;
  387. }
  388. }
  389. $dbgTime->endTime = microtime(true);
  390. trigger_error("Notice: sync end OK (time:" . number_format($dbgTime->endTime - $dbgTime->startTime, 6) . "s) !", E_USER_NOTICE);
  391. }
  392. else {
  393. $DBG_TIME = false;
  394. $DBG_MEMORY = false;
  395. $dbgTime = new stdClass();
  396. $dbgTime->start = time();
  397. $dbgTime->startTime = microtime(true);
  398. $dbgTime->lastTime = $dbgTime->startTime;
  399. self::installTable();
  400. if ($DBG_TIME) {
  401. $dbgTime->curTime = microtime(true);
  402. trigger_error("DBG:time after-installTable (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  403. $dbgTime->lastTime = $dbgTime->curTime;
  404. }
  405. self::generateTasksNewRecords();
  406. if($DBG_MEMORY)trigger_error("DBG:mem usage after-generateTasksNewRecords " . memory_get_usage(true) . ".", E_USER_NOTICE);
  407. if ($DBG_TIME) {
  408. $dbgTime->curTime = microtime(true);
  409. trigger_error("DBG:time after-generateTasksNewRecords (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  410. $dbgTime->lastTime = $dbgTime->curTime;
  411. }
  412. self::generateTasksUpdated();
  413. if($DBG_MEMORY)trigger_error("DBG:mem usage after-generateTasksUpdated " . memory_get_usage(true) . ".", E_USER_NOTICE);
  414. if ($DBG_TIME) {
  415. $dbgTime->curTime = microtime(true);
  416. trigger_error("DBG:time after-generateTasksUpdated (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  417. $dbgTime->lastTime = $dbgTime->curTime;
  418. }
  419. $dbgTime->cur = time();
  420. if ($dbgTime->cur - $dbgTime->start > 60 * 5) {
  421. trigger_error("Error: time end after-init " . ($dbgTime->cur - $dbgTime->start) . " !", E_USER_NOTICE);
  422. return;
  423. }
  424. self::newFilesAction();
  425. if($DBG_MEMORY)trigger_error("DBG:mem usage after-newFilesAction " . memory_get_usage(true) . ".", E_USER_NOTICE);
  426. if ($DBG_TIME) {
  427. $dbgTime->curTime = microtime(true);
  428. trigger_error("DBG:time after-newFilesAction (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  429. $dbgTime->lastTime = $dbgTime->curTime;
  430. }
  431. $limit = 100;
  432. for ($i = 0; $i < $limit; $i++) {
  433. $dbgTime->cur = time();
  434. if ($dbgTime->cur - $dbgTime->start > 60 * 5) {
  435. trigger_error("Error: time end after-nextTaskAction(loop:{$i}) " . ($dbgTime->cur - $dbgTime->start) . " !", E_USER_NOTICE);
  436. return;
  437. }
  438. $task = self::nextTaskAction();
  439. if($DBG_MEMORY)trigger_error("DBG:mem usage after-nextTaskAction (loop:{$i}) " . memory_get_usage(true) . ".", E_USER_NOTICE);
  440. if ($DBG_TIME) {
  441. $dbgTime->curTime = microtime(true);
  442. trigger_error("DBG:time after-nextTaskAction (loop:{$i}) (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  443. $dbgTime->lastTime = $dbgTime->curTime;
  444. }
  445. if (!$task) {
  446. $dbgTime->cur = time();
  447. break;
  448. }
  449. }
  450. $customSync = new SyncPermsCustomTables();
  451. $customSync->run();
  452. $dbgTime->cur = time();
  453. $dbgTime->endTime = microtime(true);
  454. trigger_error("Notice: sync end OK (time:" . number_format($dbgTime->endTime - $dbgTime->startTime, 6) . "s) !", E_USER_NOTICE);
  455. if ($DBG_TIME) {
  456. $dbgTime->curTime = microtime(true);
  457. trigger_error("DBG:time sync end OK (time:" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s)", E_USER_NOTICE);
  458. $dbgTime->lastTime = $dbgTime->curTime;
  459. }
  460. }
  461. }
  462. public static function newFilesAction() {
  463. $task = self::getTaskNewFiles();
  464. $taskResult = self::fixLastModifiedFiles($task);
  465. self::saveTask(-1);
  466. }
  467. public static function nextTaskAction() {
  468. $task = self::getTask();
  469. if (!$task) {
  470. return false;
  471. }
  472. self::executeTask($task);
  473. /*
  474. if (isset($task->A_SYNC_RESULT->total)
  475. && isset($task->A_SYNC_RESULT->lastDone)
  476. && $task->A_SYNC_RESULT->lastDone < $task->A_SYNC_RESULT->total
  477. ) {
  478. self::saveTask($task->ID_PROJECT, 0, $task->A_SYNC_RESULT);
  479. } else {
  480. self::saveTask($task->ID_PROJECT);
  481. }
  482. */
  483. self::saveTask($task->ID_PROJECT);
  484. return $task;
  485. }
  486. public static function generateTasksUpdated() {
  487. $db = DB::getDB();
  488. if (!$db) die("DB Error: No DB! L." . __LINE__);
  489. $sqlTest = "select p.ID, p.`L_APPOITMENT_USER`, p.`A_ADM_COMPANY`, p.`A_CLASSIFIED`, s. *
  490. from `_SYNC_FILE_PERMS` as s, `IN7_MK_BAZA_DYSTRYBUCJI` as p, `IN7_MK_BAZA_DYSTRYBUCJI` as pp
  491. where
  492. s.`ID_PROJECT`=p.`ID` and pp.`ID`=p.`P_ID`
  493. and (
  494. s.`L_APPOITMENT_USER`!=p.`L_APPOITMENT_USER`
  495. or s.`A_ADM_COMPANY`!=p.`A_ADM_COMPANY`
  496. or s.`A_CLASSIFIED`!=p.`A_CLASSIFIED`
  497. or s.`PARENT_L_APPOITMENT_USER`!=pp.`L_APPOITMENT_USER`
  498. )
  499. ";
  500. $sql = "update `_SYNC_FILE_PERMS` as s, `IN7_MK_BAZA_DYSTRYBUCJI` as p, `IN7_MK_BAZA_DYSTRYBUCJI` as pp
  501. set
  502. s.`L_APPOITMENT_USER`=p.`L_APPOITMENT_USER`
  503. , s.`A_ADM_COMPANY`=p.`A_ADM_COMPANY`
  504. , s.`A_CLASSIFIED`=p.`A_CLASSIFIED`
  505. , s.`PARENT_L_APPOITMENT_USER`=pp.`L_APPOITMENT_USER`
  506. , s.`A_SYNCHRONIZED`=0
  507. where
  508. s.`ID_PROJECT`=p.`ID` and pp.`ID`=p.`P_ID`
  509. and (
  510. s.`L_APPOITMENT_USER`!=p.`L_APPOITMENT_USER`
  511. or s.`A_ADM_COMPANY`!=p.`A_ADM_COMPANY`
  512. or s.`A_CLASSIFIED`!=p.`A_CLASSIFIED`
  513. or s.`PARENT_L_APPOITMENT_USER`!=pp.`L_APPOITMENT_USER`
  514. )
  515. ";
  516. $res = $db->query($sql);
  517. }
  518. public static function generateTasksNewRecords() {
  519. $db = DB::getDB();
  520. if (!$db) die("DB Error: No DB! L." . __LINE__);
  521. $sql = "insert ignore into `_SYNC_FILE_PERMS` (`ID_PROJECT`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  522. values (-1, '', '', '', '');
  523. ";
  524. $res = $db->query($sql);
  525. $sql = "insert ignore into `_SYNC_FILE_PERMS` (`ID_PROJECT`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  526. select p.`ID`, p.`L_APPOITMENT_USER`, p.`A_ADM_COMPANY`, p.`A_CLASSIFIED`, pp.`L_APPOITMENT_USER`
  527. from `IN7_MK_BAZA_DYSTRYBUCJI` as p
  528. left join `IN7_MK_BAZA_DYSTRYBUCJI` as pp on (pp.`ID`=p.`P_ID`)
  529. where p.`A_STATUS`!='DELETED'
  530. ";
  531. $res = $db->query($sql);
  532. }
  533. /**
  534. * Znajdź najstarszy aktualizowany projekt.
  535. */
  536. public static function getTask() {
  537. $task = null;
  538. $db = DB::getDB();
  539. if (!$db) die("DB Error: No DB! L." . __LINE__);
  540. $sqlWhereProjID = " s.`A_SYNCHRONIZED`=0 ";
  541. if (($projID = V::get('PROJ_ID', '', $_GET, 'int')) > 0){
  542. $sqlWhereProjID = " s.`ID_PROJECT`='{$projID}' ";
  543. }
  544. $sql = "select s.*
  545. , p.`L_APPOITMENT_USER` as p__L_APPOITMENT_USER
  546. , p.`A_ADM_COMPANY` as p__A_ADM_COMPANY
  547. , p.`A_CLASSIFIED` as p__A_CLASSIFIED
  548. , pp.`L_APPOITMENT_USER` as p__PARENT_L_APPOITMENT_USER
  549. , p.`M_DIST_DESC` as p__M_DIST_DESC
  550. , p.`M_DISTRIBUTOR` as p__M_DISTRIBUTOR
  551. , p.`CRM_LISTA_ZASOBOW_ID` as p__CRM_LISTA_ZASOBOW_ID
  552. from `_SYNC_FILE_PERMS` as s
  553. left join `IN7_MK_BAZA_DYSTRYBUCJI` as p on(p.`ID`=s.`ID_PROJECT`)
  554. left join `IN7_MK_BAZA_DYSTRYBUCJI` as pp on(pp.`ID`=p.`P_ID`)
  555. where
  556. {$sqlWhereProjID}
  557. order by s.`A_LAST_SYNC` asc, s.`ID` asc
  558. limit 1
  559. ";
  560. $res = $db->query($sql);
  561. if ($r = $db->fetch($res)) {
  562. $r->A_SYNC_RESULT = (!$r->A_SYNC_RESULT)? new stdClass() : json_decode($r->A_SYNC_RESULT);
  563. $task = $r;
  564. }
  565. return $task;
  566. }
  567. public static function getTaskNewerUsers() {
  568. $task = null;
  569. $db = DB::getDB();
  570. if (!$db) die("DB Error: No DB! L." . __LINE__);
  571. $sql = "select s.*
  572. from `_SYNC_FILE_PERMS` as s
  573. where s.`ID_PROJECT`=-2
  574. ";
  575. $res = $db->query($sql);
  576. if ($r = $db->fetch($res)) {
  577. $task = $r;
  578. }
  579. if (!$task) {
  580. $task = new stdClass();
  581. $task->ID_PROJECT = -2;
  582. $task->A_SYNC_RESULT = new stdClass();
  583. $task->A_LAST_SYNC = '';//mktime(date("H"), date("i") - 10, date("s"), date("n"), date("j"), date("Y"));
  584. //$task->A_LAST_SYNC = date("Y-m-d H:i", $task->A_LAST_SYNC);
  585. }
  586. return $task;
  587. }
  588. public static function getTaskNewFiles() {
  589. $task = null;
  590. $db = DB::getDB();
  591. if (!$db) die("DB Error: No DB! L." . __LINE__);
  592. $sql = "select s.*
  593. from `_SYNC_FILE_PERMS` as s
  594. where s.`ID_PROJECT`=-1
  595. ";
  596. $res = $db->query($sql);
  597. if ($r = $db->fetch($res)) {
  598. $task = $r;
  599. }
  600. if (!$task) {
  601. $task = new stdClass();
  602. $task->ID_PROJECT = -1;
  603. $task->A_SYNC_RESULT = new stdClass();
  604. $task->A_LAST_SYNC = mktime(date("H"), date("i") - 10, date("s"), date("n"), date("j"), date("Y"));
  605. $task->A_LAST_SYNC = date("Y-m-d H:i", $task->A_LAST_SYNC);
  606. }
  607. return $task;
  608. }
  609. public static function saveTask($idProject, $taskDone = 1, $result = null) {
  610. $task = null;
  611. $db = DB::getDB();
  612. if (!$db) die("DB Error: No DB! L." . __LINE__);
  613. $sqlResult = '';
  614. if ($result) {
  615. $resultJson = json_encode($result);
  616. $resultJson = $db->_($resultJson);
  617. $sqlResult .= " , s.`A_SYNC_RESULT`='{$resultJson}' ";
  618. }
  619. $sql = "update `_SYNC_FILE_PERMS` as s
  620. set
  621. s.`A_LAST_SYNC`=NOW()
  622. , s.`A_SYNCHRONIZED`={$taskDone}
  623. {$sqlResult}
  624. where s.`ID_PROJECT`={$idProject}
  625. ";
  626. $res = $db->query($sql);
  627. return $task;
  628. }
  629. public static function executeTask(&$task) {
  630. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">executeTask (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task);echo'</pre>';}
  631. $confTblName = 'IN7_MK_BAZA_DYSTRYBUCJI_COLUMN';
  632. $PROJ_mount_point = FoldersConfig::get($confTblName, 'mount_point');
  633. $project = new stdClass();
  634. $project->ID = $task->ID_PROJECT;
  635. $project->L_APPOITMENT_USER = $task->p__L_APPOITMENT_USER;
  636. $project->A_ADM_COMPANY = $task->p__A_ADM_COMPANY;
  637. $project->A_CLASSIFIED = $task->p__A_CLASSIFIED;
  638. $project->PARENT_L_APPOITMENT_USER = $task->p__PARENT_L_APPOITMENT_USER;
  639. $project->M_DIST_DESC = $task->p__M_DIST_DESC;
  640. $project->M_DISTRIBUTOR = $task->p__M_DISTRIBUTOR;
  641. $project->CRM_LISTA_ZASOBOW_ID = $task->p__CRM_LISTA_ZASOBOW_ID;
  642. $folderConf = FoldersConfig::getAll($confTblName);
  643. $uploader = new FileUploader($confTblName, $project);
  644. $errMsg = '';
  645. if (!$uploader->setConfig($folderConf, $errMsg)) {
  646. trigger_error("Error: folders config!", E_USER_NOTICE);
  647. die("Error: folders config!");
  648. }
  649. $uploader->findFolder();
  650. $mainFolder = $uploader->getDestFolder();
  651. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';var_dump($uploader);echo'</pre>';}
  652. if (!$mainFolder) {
  653. $mainFolder = $uploader->generateFolderName();
  654. $mainFolderPath = rtrim($PROJ_mount_point, '/') . '/' . $mainFolder;
  655. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($mainFolder, $mainFolderPath));echo'</pre>';}
  656. mkdir($mainFolderPath, 0770, true);
  657. @chmod($mainFolderPath, 0770);
  658. if (!file_exists($mainFolderPath)) {
  659. trigger_error("Error: Nie udało się utworzyć folderu! ({$mainFolder})", E_USER_NOTICE);
  660. return false;
  661. }
  662. $requirePermsExt = self::getRequiredPermsExtByRecord($project);
  663. $file = new stdClass();
  664. $file->name = '.';
  665. $file->path = '.';
  666. //$file->owner = '';
  667. //$file->group = '';
  668. //$file->perms = '';
  669. $file->isDir = true;
  670. $file->permsExt = array();
  671. $cmdList = self::fixFilePerms($file, $requirePermsExt, "{$PROJ_mount_point}/{$mainFolder}", $project);
  672. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$project->ID.') fixFilePerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  673. }
  674. else {
  675. $cmdList = self::fixProject($project, $mainFolder, $PROJ_mount_point, $task);
  676. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$project->ID.') fixProject (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  677. $mainFolderPath = rtrim($PROJ_mount_point, '/') . '/' . $mainFolder;
  678. $folderPismaPath = "{$mainFolderPath}/_PISMA";
  679. // if folder _PISMA not exists then create
  680. $cmdList[] = "if [ ! -d '{$folderPismaPath}' ] ; then mkdir '{$folderPismaPath}'; chmod 0770 '{$folderPismaPath}'; fi;";
  681. $cmdKorepList = self::fixProjectKoresp($project, $folderPismaPath);
  682. if (!empty($cmdKorepList)) {
  683. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$project->ID.') fixProjectKoresp (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdKorepList);echo'</pre>';}
  684. foreach ($cmdKorepList as $vCmd) {
  685. $cmdList[] = $vCmd;
  686. }
  687. }
  688. }
  689. if (!empty($cmdList)) {
  690. foreach ($cmdList as $vCmd) {
  691. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
  692. exec($vCmd, $out, $outValue);
  693. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
  694. if ($outValue != 0) {
  695. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  696. }
  697. }
  698. }
  699. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">';print_r("executeTask finished OK");echo'</pre>';}
  700. }
  701. public static function getActiveLoginList() {
  702. static $activeLoginList;
  703. if (!is_array($activeLoginList)) {
  704. $activeLoginList = array();
  705. $db = DB::getDB();
  706. if (!$db) {
  707. die('DB Error!');
  708. }
  709. $sql = "select u.`ADM_ACCOUNT`
  710. from `ADMIN_USERS` as u
  711. where u.`A_STATUS` = 'NORMAL'
  712. ";
  713. $res = $db->query($sql);
  714. while ($r = $db->fetch($res)) {
  715. $activeLoginList[] = $r->ADM_ACCOUNT;
  716. }
  717. }
  718. return $activeLoginList;
  719. }
  720. public static function isActiveUser($login) {
  721. $activeLoginList = self::getActiveLoginList();
  722. return in_array($login, $activeLoginList);
  723. }
  724. public static function getRequiredPermsExtByRecord($project) {
  725. // TODO: need to check if user is correct in field L_APPOITMENT_USER
  726. $requirePermsExt = array();
  727. if (!$project->L_APPOITMENT_USER && !$project->A_ADM_COMPANY) {// no owner, no write group
  728. // TODO: group PODMIOT
  729. $requirePermsExt["group:workgroup"] = array('write', 'read');
  730. }
  731. else {
  732. if ($project->L_APPOITMENT_USER) {
  733. if (self::isActiveUser($project->L_APPOITMENT_USER)) {
  734. $requirePermsExt["user:{$project->L_APPOITMENT_USER}"] = array('write', 'read');
  735. } else {
  736. // TODO: trigger error $project->L_APPOITMENT_USER is not active user!
  737. }
  738. }
  739. if (!empty($project->A_ADM_COMPANY) && $project->A_ADM_COMPANY == $project->A_CLASSIFIED) {
  740. $requirePermsExt["group:{$project->A_ADM_COMPANY}"] = array('read', 'write');
  741. }
  742. else if (empty($project->A_ADM_COMPANY) && empty($project->A_CLASSIFIED)) {
  743. $requirePermsExt["group:workgroup"] = array('write', 'read');
  744. }
  745. else {
  746. if ($project->A_ADM_COMPANY) {
  747. $requirePermsExt["group:{$project->A_ADM_COMPANY}"] = array('write');
  748. }
  749. if ($project->A_CLASSIFIED) {
  750. $requirePermsExt["group:{$project->A_CLASSIFIED}"] = array('read');
  751. }
  752. }
  753. }
  754. // add parent owner
  755. if (!empty($project->PARENT_L_APPOITMENT_USER) && $project->PARENT_L_APPOITMENT_USER != $project->L_APPOITMENT_USER) {
  756. if (self::isActiveUser($project->PARENT_L_APPOITMENT_USER)) {
  757. $requirePermsExt["user:{$project->PARENT_L_APPOITMENT_USER}"] = array('write', 'read');
  758. } else {
  759. // TODO: trigger error $project->PARENT_L_APPOITMENT_USER is not active user!
  760. }
  761. }
  762. // add user:_www perms read, write
  763. $requirePermsExt["user:_www"] = array('write', 'read');
  764. return $requirePermsExt;
  765. }
  766. /**
  767. * Used for files added/modified by samba/afp.
  768. *
  769. * @return TODO: object to store in task->A_SYNC_RESULT
  770. */
  771. public static function fixLastModifiedFiles($task) {
  772. $db = DB::getDB();
  773. if (!$db) die("DB Error: No DB! L." . __LINE__);
  774. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedFiles");echo'</pre>';}
  775. $PROJ_mount_point = FoldersConfig::get('IN7_MK_BAZA_DYSTRYBUCJI_COLUMN', 'mount_point');
  776. $PISMA_mount_point = FoldersConfig::get('IN7_DZIENNIK_KORESP_COLUMN', 'mount_point');
  777. $foundProjectFiles = array();
  778. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$lastRunDate (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task->A_LAST_SYNC);echo'</pre>';}
  779. //exec("cd {$PROJ_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' ", $foundPaths);
  780. exec("cd {$PROJ_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' -type f -exec ls -le '{}' \;", $filesWithPerms);// TODO: head -{$lastTotal + 10000}| tail
  781. if (!empty($filesWithPerms)) {
  782. $filesWithPermsTree = array();
  783. $lastName = '';
  784. foreach ($filesWithPerms as $line) {
  785. if (substr($line, 0, 1) == '-') {// file name
  786. $fileParts = array();
  787. $filePartsArr = explode(' ', $line);
  788. $lastInd = 0;
  789. foreach ($filePartsArr as $vPart) {
  790. if ($lastInd > 7) {// file name
  791. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  792. $lastInd++;
  793. }
  794. else if (!empty($vPart) || $vPart === '0') {
  795. $fileParts[] = $vPart;
  796. $lastInd++;
  797. }
  798. }
  799. $file = new stdClass();
  800. if (!isset($fileParts[8])) {
  801. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  802. //continue;
  803. }
  804. $file->name = end($fileParts);
  805. $file->path = end($fileParts);
  806. //$file->owner = $fileParts[2];
  807. //$file->group = $fileParts[3];
  808. //$file->perms = $fileParts[0];
  809. $file->isDir = (substr($line, 0, 1) == 'd');
  810. $file->permsExt = array();
  811. $filesWithPermsTree[$file->name] = $file;
  812. $lastName = $file->name;
  813. }
  814. else if (substr($line, 0, 1) == ' ') {// extended perm line
  815. if ($lastName == '..') {
  816. continue;
  817. }
  818. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  819. }
  820. else {// parse error
  821. $lastName = '..';
  822. }
  823. }
  824. foreach ($filesWithPermsTree as $vFile) {
  825. $vFile->path = ltrim($vFile->path, './');
  826. $vFile->path = explode('/', $vFile->path);
  827. $vFile->projectFolder = array_shift($vFile->path);
  828. $vFile->path = implode('/', $vFile->path);
  829. $projId = explode('.', $vFile->projectFolder);
  830. $projId = reset($projId);
  831. if (is_numeric($projId) && $projId > 0) {
  832. $foundProjectFiles[$projId][] = $vFile;
  833. }
  834. }
  835. }
  836. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($filesWithPerms);echo'</pre>';}
  837. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundProjectFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($foundProjectFiles);echo'</pre>';}
  838. if (!empty($foundProjectFiles)) {
  839. $sql = "select p.`ID`
  840. , p.`L_APPOITMENT_USER`
  841. , p.`A_ADM_COMPANY`
  842. , p.`A_CLASSIFIED`
  843. , pp.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  844. from IN7_MK_BAZA_DYSTRYBUCJI as p
  845. left join IN7_MK_BAZA_DYSTRYBUCJI as pp on (pp.ID=p.P_ID)
  846. where p.`ID` in (" . implode(',', array_keys($foundProjectFiles)) . ")
  847. ";
  848. $res = $db->query($sql);
  849. while ($r = $db->fetch($res)) {
  850. $requirePermsExt = self::getRequiredPermsExtByRecord($r);
  851. foreach ($foundProjectFiles[$r->ID] as $vFile) {
  852. $cmdList = self::fixFilePerms($vFile, $requirePermsExt, "{$PROJ_mount_point}/{$vFile->projectFolder}", $r);
  853. if (!empty($cmdList)) {
  854. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  855. foreach ($cmdList as $vCmd) {
  856. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
  857. exec($vCmd, $out, $outValue);
  858. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$project->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
  859. if ($outValue != 0) {
  860. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  861. }
  862. }
  863. } else {
  864. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList is empty P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("empty");echo'</pre>';}
  865. }
  866. }
  867. }
  868. }
  869. }
  870. public static function fixProjectKoresp($project, $folderPismaPath) {
  871. $db = DB::getDB();
  872. if (!$db) die("DB Error: No DB! L." . __LINE__);
  873. $PISMA_mount_point = FoldersConfig::get('IN7_DZIENNIK_KORESP_COLUMN', 'mount_point');
  874. $PISMA_mount_point = rtrim($PISMA_mount_point, '/');
  875. $pismaList = array();
  876. // $PISMA_mount_point / {TYP_KORESP} / {ID} . *
  877. $sql = "select k.`ID`
  878. , k.`K_TYP_KORESP`
  879. from `IN7_DZIENNIK_KORESP` as k
  880. where k.`ID_PROJECT`={$project->ID}
  881. order by k.`ID` DESC
  882. limit 100
  883. ";
  884. $res = $db->query($sql);
  885. while ($r = $db->fetch($res)) {
  886. $pismaList[$r->ID] = $r->K_TYP_KORESP;// TODO: K_TYP_KORESP not used
  887. }
  888. if (empty($pismaList)) {
  889. return false;
  890. }
  891. $lsCmd = array();
  892. $lsCmd[] = "0.*/";// if only one folder then it doesnt show folder name, only files
  893. foreach ($pismaList as $kID => $vTyp) {
  894. $lsCmd[] = "{$kID}.*/";
  895. }
  896. if (empty($lsCmd)) {
  897. return false;
  898. }
  899. $lsCmd = 'ls -le ' . implode($lsCmd, ' ') . ' 2>>/dev/null ';
  900. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Koreps lsCmd (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($lsCmd);echo'</pre>';}
  901. exec("cd {$PISMA_mount_point}; {$lsCmd} ", $filesWithPerms);
  902. $filesWithPermsTree = array();
  903. if (!empty($filesWithPerms)) {
  904. $lastName = '';
  905. $folderParent = '';
  906. foreach ($filesWithPerms as $line) {
  907. if (substr($line, 0, 1) == '-') {// file name
  908. $fileParts = array();
  909. $filePartsArr = explode(' ', $line);
  910. $lastInd = 0;
  911. foreach ($filePartsArr as $vPart) {
  912. if ($lastInd > 7) {// file name
  913. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  914. $lastInd++;
  915. }
  916. else if (!empty($vPart) || $vPart === '0') {
  917. $fileParts[] = $vPart;
  918. $lastInd++;
  919. }
  920. }
  921. $file = new stdClass();
  922. if (!isset($fileParts[8])) {
  923. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  924. //continue;
  925. }
  926. $file->name = end($fileParts);
  927. $file->path = array();
  928. if ($folderParent) $file->path[] = $folderParent;
  929. $file->path[] = end($fileParts);
  930. $file->path = implode('/', $file->path);
  931. //$file->owner = $fileParts[2];
  932. //$file->group = $fileParts[3];
  933. //$file->perms = $fileParts[0];
  934. $file->isDir = (substr($line, 0, 1) == 'd');
  935. $file->permsExt = array();
  936. $filesWithPermsTree[$file->name] = $file;
  937. $lastName = $file->name;
  938. }
  939. else if (substr($line, 0, 1) == ' ') {// extended perm line
  940. if ($lastName == '..') {
  941. continue;
  942. }
  943. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  944. }
  945. else if (substr($line, -1) == ':') {// folder
  946. $folderParent = trim(substr($line, 0, -1), '/');
  947. }
  948. else if (substr($line, 0, 5) == 'total') {
  949. continue;
  950. }
  951. else if (empty($line)) {
  952. $folderParent = '';
  953. continue;
  954. }
  955. else {// parse error
  956. $lastName = '..';
  957. }
  958. }
  959. }
  960. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PISMA_mount_point}\n";print_r($filesWithPerms);echo'</pre>';}
  961. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PISMA_mount_point}\n";print_r($filesWithPermsTree);echo'</pre>';}
  962. $cmdList = array();
  963. $requirePermsExt = self::getRequiredPermsExtByRecord($project);
  964. foreach ($filesWithPermsTree as $kFileName => $vFile) {
  965. $cmdFile = self::fixFilePerms($vFile, $requirePermsExt, "{$PISMA_mount_point}", $project);
  966. if (!empty($cmdFile)) {
  967. foreach ($cmdFile as $vCmd) {
  968. $cmdList[] = $vCmd;
  969. }
  970. }
  971. // if folder _PISMA not exists then create
  972. $fname = explode('/', $vFile->path);
  973. $fname = end($fname);
  974. $cmdList []= "if [ ! -f '{$folderPismaPath}/{$fname}' ] ; then ln '{$PISMA_mount_point}/{$vFile->path}' '{$folderPismaPath}'/; fi; ";
  975. }
  976. return $cmdList;
  977. }
  978. /*
  979. * Not used.
  980. */
  981. public static function preloadFixProject(&$task, $mainFolder, $PROJ_mount_point) {
  982. if ($task->ID_PROJECT == 1695) {// TODO: biall-net - 8853 pliki w katalog - stary HANDLOWY
  983. if (isset($task->A_SYNC_RESULT->total)) {
  984. exec("cd '{$PROJ_mount_point}/{$mainFolder}' && find . -type f | wc -l ", $filesTotal);
  985. if (!empty($filesTotal)) {
  986. $filesTotal = reset($filesTotal);
  987. $filesTotal = intval(trim($filesTotal));
  988. $task->A_SYNC_RESULT->total = $filesTotal;
  989. self::saveTask($task->ID_PROJECT, 0, $task->A_SYNC_RESULT);
  990. }
  991. }
  992. }
  993. }
  994. public static function fixProject($r, $mainFolder, $PROJ_mount_point, &$task) {
  995. $time = time();
  996. if ($r->ID == 1695) {// TODO: biall-net - 8853 pliki w katalog - stary HANDLOWY
  997. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">TODO: pomin - za dużo plików ('.$r->ID.'/'.$mainFolder.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($r);echo'</pre>';}
  998. //return false;
  999. }
  1000. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">r('.$r->ID.'/'.$mainFolder.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($r);echo'</pre>';}
  1001. $requirePermsExt = self::getRequiredPermsExtByRecord($r);
  1002. $filesWithPerms = array();
  1003. $cmd = " ls -Rlea . ";
  1004. if (false) {//$r->ID == 1695) {// TODO: biall-net - 8853 pliki w katalog - stary HANDLOWY
  1005. if (isset($task->A_SYNC_RESULT->total)) {
  1006. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">A_SYNC_RESULT (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("A_SYNC_RESULT[total]={$task->A_SYNC_RESULT->total}");echo'</pre>';}
  1007. if ($task->A_SYNC_RESULT->total > 1000) {
  1008. $lastDone = V::get('lastDone', 0, $task->A_SYNC_RESULT, 'int');
  1009. if ($lastDone > 0) {
  1010. $task->A_SYNC_RESULT->lastDone = $lastDone + 1000;
  1011. $cmd = " find . -type f | head -" . ($lastDone + 1000) . " | tail -1000 | xargs ls -le ";
  1012. } else {
  1013. $task->A_SYNC_RESULT->lastDone = 1000;
  1014. $cmd = " find . -type f | head -1000 | xargs ls -le ";
  1015. }
  1016. }
  1017. }
  1018. }
  1019. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmd (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("cd '{$PROJ_mount_point}/{$mainFolder}' && {$cmd} ");echo'</pre>';}
  1020. exec("cd '{$PROJ_mount_point}/{$mainFolder}' && {$cmd} ", $filesWithPerms);
  1021. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPerms);echo'</pre>';}
  1022. $filesWithPermsTree = array();
  1023. $lastName = '';
  1024. $folderParent = '';
  1025. foreach ($filesWithPerms as $line) {
  1026. if (substr($line, 0, 1) == '-' || substr($line, 0, 1) == 'd') {// file name
  1027. $fileParts = array();
  1028. $filePartsArr = explode(' ', $line);
  1029. $lastInd = 0;
  1030. foreach ($filePartsArr as $vPart) {
  1031. if ($lastInd > 7) {// file name
  1032. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  1033. $lastInd++;
  1034. }
  1035. else if (!empty($vPart) || $vPart === '0') {
  1036. $fileParts[] = $vPart;
  1037. $lastInd++;
  1038. }
  1039. }
  1040. if (end($fileParts) == '..' || (end($fileParts) == '.' && $folderParent)) {
  1041. $lastName = '..';
  1042. continue;
  1043. }
  1044. $file = new stdClass();
  1045. if (!isset($fileParts[8])) {
  1046. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  1047. //continue;
  1048. }
  1049. $file->name = end($fileParts);
  1050. $file->path = array();
  1051. if ($folderParent) $file->path[] = $folderParent;
  1052. $file->path[] = end($fileParts);
  1053. $file->path = implode('/', $file->path);
  1054. //$file->owner = $fileParts[2];
  1055. //$file->group = $fileParts[3];
  1056. //$file->perms = $fileParts[0];
  1057. $file->isDir = (substr($line, 0, 1) == 'd');
  1058. $file->permsExt = array();
  1059. $filesWithPermsTree[$file->name] = $file;
  1060. $lastName = $file;
  1061. }
  1062. else if (substr($line, 0, 1) == ' ') {// extended perm line
  1063. if ($lastName == '..') {
  1064. continue;
  1065. }
  1066. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  1067. }
  1068. else if (substr($line, 0, 2) == './' && substr($line, -1) == ':') {// folder
  1069. $folderParent = substr($line, 2, -1);
  1070. }
  1071. else if (substr($line, 0, 5) == 'total') {
  1072. continue;
  1073. }
  1074. else if (empty($line)) {
  1075. $folderParent = '';
  1076. continue;
  1077. }
  1078. }
  1079. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPermsTree);echo'</pre>';}
  1080. // check perms
  1081. /*
  1082. files:
  1083. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown
  1084. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity
  1085. R read, execute, readattr, readextattr, readsecurity
  1086. dir:
  1087. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown,file_inherit,directory_inherit
  1088. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity, file_inherit,directory_inherit
  1089. R list, search, readattr, readextattr, readsecurity, file_inherit,directory_inherit
  1090. */
  1091. $cmdList = array();
  1092. foreach ($filesWithPermsTree as $kFileName => $vFile) {
  1093. if (false) {
  1094. // TODO: $kFileName == '_PISMA' - readonly
  1095. // TODO: $vFile->path => _PISMA/...
  1096. }
  1097. else {
  1098. $cmdFile = self::fixFilePerms($vFile, $requirePermsExt, "{$PROJ_mount_point}/{$mainFolder}", $r);
  1099. if (!empty($cmdFile)) {
  1100. foreach ($cmdFile as $vCmd) {
  1101. $cmdList[] = $vCmd;
  1102. }
  1103. }
  1104. }
  1105. }
  1106. return $cmdList;
  1107. }
  1108. public static function fixFilePerms($vFile, $requirePermsExt, $mainPath, $r) {
  1109. //trigger_error("fixFilePerms: " . json_encode($vFile), E_USER_NOTICE);
  1110. $cmdList = array();
  1111. $vReqPermsExt = array();
  1112. foreach ($requirePermsExt as $kPermObj => $vPerms) {
  1113. $vReqPermsExt[$kPermObj] = array();
  1114. foreach ($vPerms as $vPerm) {
  1115. if ($vFile->isDir) {
  1116. if ($vPerm == 'read') {
  1117. $vReqPermsExt[$kPermObj]['list'] = 0;
  1118. $vReqPermsExt[$kPermObj]['search'] = 0;
  1119. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1120. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1121. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1122. $vReqPermsExt[$kPermObj]['file_inherit'] = 0;
  1123. $vReqPermsExt[$kPermObj]['directory_inherit'] = 0;
  1124. }
  1125. else if ($vPerm == 'write') {
  1126. $vReqPermsExt[$kPermObj]['add_file'] = 0;
  1127. $vReqPermsExt[$kPermObj]['add_subdirectory'] = 0;
  1128. $vReqPermsExt[$kPermObj]['delete_child'] = 0;
  1129. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1130. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1131. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1132. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1133. }
  1134. }
  1135. else {
  1136. if ($vPerm == 'read') {
  1137. $vReqPermsExt[$kPermObj]['read'] = 0;
  1138. $vReqPermsExt[$kPermObj]['execute'] = 0;
  1139. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1140. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1141. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1142. }
  1143. else if ($vPerm == 'write') {
  1144. $vReqPermsExt[$kPermObj]['write'] = 0;
  1145. $vReqPermsExt[$kPermObj]['append'] = 0;
  1146. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1147. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1148. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1149. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1150. }
  1151. }
  1152. }
  1153. }
  1154. $permsToRemove = array();
  1155. foreach ($vFile->permsExt as $vPermExtLine) {
  1156. $vPermExtArr = explode(' ', $vPermExtLine);
  1157. $vPermExt = new stdClass();
  1158. $vPermExt->nr = trim($vPermExtArr[0], ' :');
  1159. $vPermExt->permObj = $vPermExtArr[1];
  1160. $vPermExt->perms = '';
  1161. if (count($vPermExtArr) == 4) {
  1162. $vPermExt->perms = explode(',', $vPermExtArr[3]);
  1163. }
  1164. else if (count($vPermExtArr) == 5 && $vPermExtArr[2] == 'inherited') {
  1165. $vPermExt->perms = explode(',', $vPermExtArr[4]);
  1166. }
  1167. else {
  1168. echo "Error: Perm Ext Line format! ({$vPermExtLine})";
  1169. continue;
  1170. }
  1171. $permFound = false;
  1172. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1173. if (false !== strpos($vPermExtLine, $kPermObj)) {
  1174. foreach ($vPerms as $kPerm => $vPermChecked) {
  1175. if (in_array($kPerm, $vPermExt->perms)) {
  1176. $vReqPermsExt[$kPermObj][$kPerm] = 1;
  1177. $permFound = true;
  1178. }
  1179. }
  1180. }
  1181. }
  1182. if (!$permFound) {
  1183. $permsToRemove[] = $vPermExt->nr;
  1184. }
  1185. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$vReqPermsExt('.$vFile->name.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vReqPermsExt);echo'</pre>';
  1186. }
  1187. if (!empty($permsToRemove)) {
  1188. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-rm('.$r->ID.'): $permsToRemove('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToRemove'=>$permsToRemove, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
  1189. $permsToRemove = array_reverse($permsToRemove);
  1190. foreach ($permsToRemove as $vPermInd) {
  1191. $cmdList []= "chmod -a# {$vPermInd} '{$mainPath}/{$vFile->path}' ";
  1192. }
  1193. }
  1194. $permsToAdd = array();
  1195. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1196. foreach ($vPerms as $kPerm => $vPermChecked) {
  1197. if (!$vPermChecked) {
  1198. $permsToAdd[$kPermObj][$kPerm] = 1;
  1199. }
  1200. }
  1201. }
  1202. if (!empty($permsToAdd)) {
  1203. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-add('.$r->ID.'): $permsToAdd('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToAdd'=>$permsToAdd, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
  1204. foreach ($permsToAdd as $kPermObj => $vPerms) {
  1205. $cmdList []= "chmod +a \"{$kPermObj} allow " . implode(',', array_keys($vPerms)) . "\" '{$mainPath}/{$vFile->path}' ";
  1206. }
  1207. }
  1208. return $cmdList;
  1209. }
  1210. /**
  1211. * @returns array - last modified project ids.
  1212. */
  1213. public static function fixLastModifiedByFiles() {// TODO: RMME
  1214. $db = DB::getDB();
  1215. if (!$db) die("DB Error: No DB! L." . __LINE__);
  1216. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedByFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedByFiles");echo'</pre>';}
  1217. /*
  1218. * $ man find:
  1219. -newer file
  1220. True if the current file has a more recent last modification time than file.
  1221. -newerXY file
  1222. True if the current file has a more recent last access time (X=a), inode creation time (X=B), change time (X=c),
  1223. or modification time (X=m) than the last access time (Y=a), inode creation time (Y=B), change time (Y=c), or mod-
  1224. ification time (Y=m) of file. In addition, if Y=t, then file is instead interpreted as a direct date specifica-
  1225. tion of the form understood by cvs(1). Note that -newermm is equivalent to -newer.
  1226. *
  1227. * $ man chmod:
  1228. -i Removes the 'inherited' bit from all entries in the named file(s) ACLs.
  1229. *
  1230. * chmod -a "admin allow write" file1 # remove line
  1231. * chmod -a# 1 file1 # remove line at position 1
  1232. *
  1233. * chmod +a nie zmienia modify date: find . -newermt '2013-10-07 ...'
  1234. */
  1235. // find /Library/Server/Web/Data/Sites/Default/PLIKI/PROJEKTY -newermt '2013-10-07 16:20'
  1236. $PROJ_mount_point = FoldersConfig::get('IN7_MK_BAZA_DYSTRYBUCJI_COLUMN', 'mount_point');
  1237. $PISMA_mount_point = FoldersConfig::get('IN7_DZIENNIK_KORESP_COLUMN', 'mount_point');
  1238. $foundProjectIds = array();
  1239. $lastRunDate = self::getLastRunDate();
  1240. exec("cd {$PROJ_mount_point}; find . -newermt '{$lastRunDate}' ", $foundPaths);
  1241. if (!empty($foundPaths)) {
  1242. foreach ($foundPaths as $path) {
  1243. $path = ltrim($path, './');
  1244. $folder = explode('/', $path);
  1245. $folder = reset($folder);
  1246. $projId = explode('.', $folder);
  1247. $projId = reset($projId);
  1248. if (is_numeric($projId)) {
  1249. $foundProjectIds[$projId] = $folder;
  1250. }
  1251. }
  1252. }
  1253. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundPaths (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($foundPaths);echo'</pre>';}
  1254. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundProjectIds (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$PROJ_mount_point}\n";print_r($foundProjectIds);echo'</pre>';}
  1255. if (!empty($foundProjectIds)) {
  1256. $sql = "select p.`ID`
  1257. , p.`L_APPOITMENT_USER`
  1258. , p.`A_ADM_COMPANY`
  1259. , p.`A_CLASSIFIED`
  1260. , pp.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  1261. from IN7_MK_BAZA_DYSTRYBUCJI as p
  1262. left join IN7_MK_BAZA_DYSTRYBUCJI as pp on (pp.ID=p.P_ID)
  1263. where p.`ID` in (" . implode(',', array_keys($foundProjectIds)) . ")
  1264. ";
  1265. $res = $db->query($sql);
  1266. while ($r = $db->fetch($res)) {
  1267. $mainFolder = $foundProjectIds[$r->ID];
  1268. $cmdList = self::fixProject($r, $mainFolder, $PROJ_mount_point);
  1269. if (!empty($cmdList)) {
  1270. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  1271. } else {
  1272. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  1273. }
  1274. }
  1275. }
  1276. return array_keys($foundProjectIds);
  1277. }
  1278. public static function fixLastModifiedByDB($fixedProjIds) {// TODO: RMME
  1279. $db = DB::getDB();
  1280. if (!$db) die("DB Error: No DB! L." . __LINE__);
  1281. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedByDB (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedByDB");echo'</pre>';}
  1282. $sqlWhereAdd = '';
  1283. if (!empty($fixedProjIds)) {
  1284. $sqlWhereAdd = " and p.`ID` not in (" . implode(',', $fixedProjIds) . ") ";
  1285. }
  1286. $projectList = array();
  1287. $lastRunDate = self::getLastRunDate();
  1288. $sql = "select p.`ID`
  1289. , p.`L_APPOITMENT_USER`
  1290. , p.`A_ADM_COMPANY`
  1291. , p.`A_CLASSIFIED`
  1292. , pp.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  1293. from IN7_MK_BAZA_DYSTRYBUCJI as p
  1294. left join IN7_MK_BAZA_DYSTRYBUCJI as pp on (pp.ID=p.P_ID)
  1295. where
  1296. ( p.`A_RECORD_UPDATE_DATE`>'{$lastRunDate}'
  1297. or p.`A_RECORD_CREATE_DATE`>'{$lastRunDate}'
  1298. )
  1299. {$sqlWhereAdd}
  1300. ";
  1301. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">sql (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';}
  1302. $res = $db->query($sql);
  1303. while ($r = $db->fetch($res)) {
  1304. $projectList[$r->ID] = $r;
  1305. }
  1306. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">projectList (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($projectList);echo'</pre>';}
  1307. }
  1308. public static function getLastRunDate() {// TODO: RMME
  1309. if (($argFromDate = V::get('_fromDate', '', $_GET)) != '') {
  1310. // Format: 2013-10-07 23:46
  1311. if (strlen($argFromDate) == 16
  1312. && substr($argFromDate, 4, 1) == '-'
  1313. && substr($argFromDate, 7, 1) == '-'
  1314. && substr($argFromDate, 10, 1) == '-'
  1315. && substr($argFromDate, 13, 1) == ':'
  1316. && is_numeric(str_replace(array('-', ':'), '', $argFromDate))
  1317. ) {
  1318. $lastRunDate = mktime(substr($argFromDate, 11, 2), substr($argFromDate, 14, 2), 0, substr($argFromDate, 5, 2), substr($argFromDate, 8, 2), substr($argFromDate, 0, 4));
  1319. $lastRunDate = date("Y-m-d H:i", $lastRunDate);
  1320. }
  1321. }
  1322. if (!$lastRunDate) {
  1323. $lastRunDate = mktime(date("H") - 1, date("i"), date("s"), date("n"), date("j"), date("Y"));
  1324. $lastRunDate = date("Y-m-d H:i", $lastRunDate);
  1325. }
  1326. //$lastRunDate = '2013-09-01 01:00';
  1327. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">lastRunDate (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($lastRunDate);echo'</pre>';
  1328. return $lastRunDate;
  1329. }
  1330. public static function usersAction() {
  1331. $task = self::getTaskNewerUsers();
  1332. $users = self::getUsersNewerThen($task->A_LAST_SYNC);
  1333. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$users (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($users);echo'</pre>';
  1334. self::saveTask(-2);
  1335. }
  1336. public static function usersAllAction() {
  1337. /*
  1338. * DBU - DB User LDU - LDAP User
  1339. * DBG - DB Group LDG - LDAP Group
  1340. *
  1341. * DBU - ADMIN_USERS
  1342. * DBG - CRM_LISTA_ZASOBOW where TYPE in('STANOWISKO','PODMIOT','DZIAL')// TODO: GRUPA_PROJEKTOWA - ldap nested group?
  1343. *
  1344. * 1. fetch DB Users
  1345. * ? only active users (A_STATUS == 'NORMAL')
  1346. * 2. fetch LDAP Users
  1347. *
  1348. * DBU.ADM_ACCOUNT == LDU.uid
  1349. * DBG.A_LDAP_GID == LDG.gidNumber
  1350. *
  1351. * TODO: $group createLdapGroup()
  1352. *
  1353. */
  1354. Lib::loadClass('UsersHelper');
  1355. $users = self::getUsersAll();
  1356. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">users count('.count($users).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($users);echo'</pre>';
  1357. $allLdapUsers = UsersHelper::getLDAPUsersAll();
  1358. $ldapUsers = array();
  1359. foreach ($allLdapUsers as $vLdapUser) {
  1360. $ldapUsers[$vLdapUser->uid] = $vLdapUser;
  1361. }
  1362. unset($allLdapUsers);
  1363. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">ldapUsers count('.count($ldapUsers).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($ldapUsers);echo'</pre>';
  1364. foreach ($users as $kLogin => $vUser) {
  1365. if ($vUser->A_STATUS == 'NORMAL') {
  1366. if (array_key_exists($vUser->ADM_ACCOUNT, $ldapUsers)) {
  1367. echo '<div>'.$vUser->ADM_ACCOUNT.': OK? account exists in LDAP</div>';
  1368. }
  1369. else {
  1370. echo '<div>'.$vUser->ADM_ACCOUNT.': TODO: create account in LDAP</div>';
  1371. }
  1372. }
  1373. else if ($vUser->A_STATUS == 'DELETED') {
  1374. if (array_key_exists($vUser->ADM_ACCOUNT, $ldapUsers)) {
  1375. echo '<div>'.$vUser->ADM_ACCOUNT.': TODO: disable account</div>';
  1376. }
  1377. else {
  1378. //echo '<div>'.$vUser->ADM_ACCOUNT.': WARNING: account not exists in LDAP</div>';
  1379. }
  1380. }
  1381. }
  1382. }
  1383. public static function getUsersNewerThen($datetime) {
  1384. $users = array();
  1385. $db = DB::getDB();
  1386. if (!$db) die("DB Error: No DB! L." . __LINE__);
  1387. $sqlWhereAdd = "";
  1388. if ($datetime) {
  1389. $sqlWhereAdd = " and ( u.`A_RECORD_CREATE_DATE`>'{$datetime}' or u.`A_RECORD_UPDATE_DATE`>'{$datetime}' )";
  1390. } else {
  1391. // TODO: error datetime not set
  1392. }
  1393. $sql = "select u.ID
  1394. , u.`ADM_ACCOUNT`
  1395. , u.`ADM_NAME`
  1396. , u.`A_STATUS`
  1397. from `ADMIN_USERS` as u
  1398. where
  1399. u.`A_STATUS` in('NORMAL', 'DELETED')
  1400. ";
  1401. $res = $db->query($sql);
  1402. while ($r = $db->fetch($res)) {
  1403. $users[$r->ADM_ACCOUNT] = $r;
  1404. }
  1405. return $users;
  1406. }
  1407. public static function getUsersAll() {
  1408. $users = array();
  1409. $db = DB::getDB();
  1410. if (!$db) die("DB Error: No DB! L." . __LINE__);
  1411. $sql = "select u.ID
  1412. , u.`ADM_ACCOUNT`
  1413. , u.`ADM_NAME`
  1414. , u.`A_STATUS`
  1415. from `ADMIN_USERS` as u
  1416. where
  1417. u.`A_STATUS` in('NORMAL', 'DELETED')
  1418. ";
  1419. $res = $db->query($sql);
  1420. while ($r = $db->fetch($res)) {
  1421. $users[$r->ADM_ACCOUNT] = $r;
  1422. }
  1423. return $users;
  1424. }
  1425. }
  1426. class SyncPermsCustomTables {
  1427. public $_tbls;
  1428. private $_db;
  1429. private $_syncTblName = '_SYNC_TABLE_FILE_PERMS';
  1430. private $_activeLoginList;
  1431. public function run() {
  1432. if (!$this->fetchConfig()) return;
  1433. $this->installTable();
  1434. $this->generateTasksNewRecords();
  1435. $this->generateTasksUpdated();
  1436. $this->newFilesAction();
  1437. $limit = 100;
  1438. for ($i = 0; $i < $limit; $i++) {
  1439. $loopTasksFired = 0;
  1440. foreach ($this->_tbls as $tblName => $tblConf) {
  1441. $task = $this->nextTaskAction($tblName);
  1442. if (!$task) {
  1443. // TODO: rm $tblName from config to prevent searching for task in next loops
  1444. unset($this->_tbls[$tblName]);
  1445. continue;
  1446. }
  1447. $loopTasksFired++;
  1448. }
  1449. if (!$loopTasksFired) break;
  1450. $i += $loopTasksFired;
  1451. }
  1452. }
  1453. public function fetchConfig() {
  1454. $this->_db = DB::getDB();
  1455. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1456. $tbls = array();
  1457. $sql = "select c.`CONF_VAL` as tbl_names
  1458. from `CRM_CONFIG` as c
  1459. where c.`CONF_KEY`='_SYNC_TABLE_FILE_PERMS__TablesList'
  1460. ";
  1461. $res = $this->_db->query($sql);
  1462. while ($r = $this->_db->fetch($res)) {
  1463. if (!empty($r->tbl_names)) {
  1464. $tbls = explode("\n", $r->tbl_names);
  1465. }
  1466. }
  1467. //echo "DBG:" . __LINE__ . ":" . __FUNCTION__ . "(): tbls [" . implode(',', $tbls) . "]\n";
  1468. $configTbls = array();
  1469. Lib::loadClass('FoldersConfig');
  1470. if (!empty($tbls)) {
  1471. $folderConfAll = FoldersConfig::getRawData();
  1472. foreach ($tbls as $tblName) {
  1473. $tblName = trim($tblName);
  1474. if (empty($tblName)) continue;
  1475. $confTblName = "{$tblName}_COLUMN";
  1476. if (FoldersConfig::hasConfig($confTblName)) {
  1477. $configTbls[$tblName] = FoldersConfig::getAll($confTblName);
  1478. }
  1479. }
  1480. }
  1481. //echo "DBG:" . __LINE__ . ":" . __FUNCTION__ . "(): tbls [" . implode(',', array_keys($configTbls)) . "]\n";
  1482. if (!empty($configTbls)) {
  1483. $this->_tbls = $configTbls;
  1484. }
  1485. return $this->_tbls;
  1486. }
  1487. public function installTable() {
  1488. if (!$this->_tbls) return;
  1489. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1490. $sql = "
  1491. CREATE TABLE IF NOT EXISTS `{$this->_syncTblName}` (
  1492. `ID` int(11) NOT NULL AUTO_INCREMENT,
  1493. `TBL_NAME` varchar(64),
  1494. `TBL_ID` int(11) NOT NULL,
  1495. `L_APPOITMENT_USER` varchar(64) DEFAULT '',
  1496. `A_ADM_COMPANY` varchar(64) NOT NULL DEFAULT '',
  1497. `A_CLASSIFIED` varchar(64) NOT NULL DEFAULT '',
  1498. `PARENT_L_APPOITMENT_USER` varchar(64) NOT NULL DEFAULT '',
  1499. `A_LAST_SYNC` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  1500. `A_SYNCHRONIZED` tinyint(4) NOT NULL DEFAULT '0',
  1501. `A_SYNC_RESULT` varchar(255) NOT NULL DEFAULT '',
  1502. `A_POMIN_SYNC` tinyint(1) NOT NULL DEFAULT '0',
  1503. PRIMARY KEY (`ID`),
  1504. UNIQUE KEY `TBL` (`TBL_NAME`, `TBL_ID`)
  1505. ) ENGINE=MyISAM DEFAULT CHARSET=latin2 ;
  1506. ";
  1507. $this->_db->query($sql);
  1508. if ($this->_db->has_errors()) {
  1509. print_r($this->_db->get_errors());
  1510. }
  1511. }
  1512. public function generateTasksNewRecords() {
  1513. if (!$this->_tbls) return;
  1514. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1515. $sqlValues = array();
  1516. foreach ($this->_tbls as $tblName => $tblConf) {
  1517. $sqlValues[] = "('{$tblName}', -1, '', '', '', '')";
  1518. }
  1519. $sqlValues = implode(',', $sqlValues);
  1520. $sql = "insert ignore into `{$this->_syncTblName}` (`TBL_NAME`, `TBL_ID`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  1521. values {$sqlValues};
  1522. ";
  1523. $res = $this->_db->query($sql);
  1524. if ($this->_db->has_errors()) {
  1525. print_r($this->_db->get_errors());
  1526. }
  1527. foreach ($this->_tbls as $tblName => $tblConf) {
  1528. $sql = "insert ignore into `{$this->_syncTblName}` (`TBL_NAME`, `TBL_ID`, `L_APPOITMENT_USER`, `A_ADM_COMPANY`, `A_CLASSIFIED`, `PARENT_L_APPOITMENT_USER`)
  1529. select '{$tblName}' as TBL_NAME
  1530. , t.`ID`, t.`L_APPOITMENT_USER`, t.`A_ADM_COMPANY`, t.`A_CLASSIFIED`
  1531. , '' as PARENT_L_APPOITMENT_USER -- pp.`L_APPOITMENT_USER`
  1532. from `{$tblName}` as t
  1533. where t.`A_STATUS`!='DELETED'
  1534. ";
  1535. $res = $this->_db->query($sql);
  1536. if ($this->_db->has_errors()) {
  1537. print_r($this->_db->get_errors());
  1538. }
  1539. }
  1540. }
  1541. public function generateTasksUpdated() {
  1542. if (!$this->_tbls) return;
  1543. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1544. foreach ($this->_tbls as $tblName => $tblConf) {
  1545. $sql = "update `{$this->_syncTblName}` as s
  1546. , `{$tblName}` as t
  1547. -- , `IN7_MK_BAZA_DYSTRYBUCJI` as pt
  1548. set
  1549. s.`L_APPOITMENT_USER`=t.`L_APPOITMENT_USER`
  1550. , s.`A_ADM_COMPANY`=t.`A_ADM_COMPANY`
  1551. , s.`A_CLASSIFIED`=t.`A_CLASSIFIED`
  1552. , s.`PARENT_L_APPOITMENT_USER`='' -- pt.`L_APPOITMENT_USER`
  1553. , s.`A_SYNCHRONIZED`=0
  1554. where
  1555. s.`TBL_ID`=t.`ID`
  1556. and s.`TBL_NAME`='{$tblName}'
  1557. -- and pt.`ID`=t.`P_ID`
  1558. and (
  1559. s.`L_APPOITMENT_USER`!=t.`L_APPOITMENT_USER`
  1560. or s.`A_ADM_COMPANY`!=t.`A_ADM_COMPANY`
  1561. or s.`A_CLASSIFIED`!=t.`A_CLASSIFIED`
  1562. -- or s.`PARENT_L_APPOITMENT_USER`!=pt.`L_APPOITMENT_USER`
  1563. )
  1564. ";
  1565. $res = $this->_db->query($sql);
  1566. if ($this->_db->has_errors()) {
  1567. print_r($this->_db->get_errors());
  1568. }
  1569. }
  1570. }
  1571. public function newFilesAction() {
  1572. if (!$this->_tbls) return;
  1573. foreach ($this->_tbls as $tblName => $tblConf) {
  1574. $task = $this->_getTaskNewFiles($tblName);
  1575. $taskResult = $this->_fixLastModifiedFiles($task);
  1576. $this->_saveTask($tblName, -1);
  1577. }
  1578. }
  1579. private function _getTaskNewFiles($tblName) {
  1580. $task = null;
  1581. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1582. $sql = "select s.*
  1583. from `{$this->_syncTblName}` as s
  1584. where s.`TBL_ID`=-1 and s.`TBL_NAME`='{$tblName}'
  1585. ";
  1586. $res = $this->_db->query($sql);
  1587. if ($r = $this->_db->fetch($res)) {
  1588. $task = $r;
  1589. }
  1590. if (!$task) {
  1591. $task = new stdClass();
  1592. $task->TBL_NAME = $tblName;
  1593. $task->TBL_ID = -1;
  1594. $task->A_SYNC_RESULT = new stdClass();
  1595. $task->A_LAST_SYNC = mktime(date("H"), date("i") - 10, date("s"), date("n"), date("j"), date("Y"));
  1596. $task->A_LAST_SYNC = date("Y-m-d H:i", $task->A_LAST_SYNC);
  1597. }
  1598. return $task;
  1599. }
  1600. private function _fixLastModifiedFiles($task) {
  1601. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1602. $tblName = $task->TBL_NAME;
  1603. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fixLastModifiedFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("fixLastModifiedFiles");echo'</pre>';}
  1604. $confTblName = "{$task->TBL_NAME}_COLUMN";
  1605. $TBL_mount_point = FoldersConfig::get($confTblName, 'mount_point');
  1606. $record = null;
  1607. $folderConf = FoldersConfig::getAll($confTblName);
  1608. $uploader = new FileUploader($confTblName, $record);
  1609. if (!$uploader->setConfig($folderConf, $errMsg)) {
  1610. trigger_error("Error: folders config!", E_USER_NOTICE);
  1611. die("Error: folders config!");
  1612. }
  1613. $hasRecordOwnFolder = $uploader->hasRecordOwnFolder();
  1614. $foundTblFiles = array();
  1615. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$lastRunDate (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task->A_LAST_SYNC);echo'</pre>';}
  1616. //exec("cd {$TBL_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' ", $foundPaths);
  1617. $filesWithPerms = array();
  1618. $cmd = "cd {$TBL_mount_point}; find . -newermt '{$task->A_LAST_SYNC}' -type f -exec ls -le '{}' \;";
  1619. exec($cmd, $filesWithPerms);// TODO: head -{$lastTotal + 10000}| tail
  1620. if (!empty($filesWithPerms)) {
  1621. $filesWithPermsTree = array();
  1622. $lastName = '';
  1623. foreach ($filesWithPerms as $line) {
  1624. if (substr($line, 0, 1) == '-') {// file name
  1625. $fileParts = array();
  1626. $filePartsArr = explode(' ', $line);
  1627. $lastInd = 0;
  1628. foreach ($filePartsArr as $vPart) {
  1629. if ($lastInd > 7) {// file name
  1630. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  1631. $lastInd++;
  1632. }
  1633. else if (!empty($vPart) || $vPart === '0') {
  1634. $fileParts[] = $vPart;
  1635. $lastInd++;
  1636. }
  1637. }
  1638. $file = new stdClass();
  1639. if (!isset($fileParts[8])) {
  1640. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  1641. //continue;
  1642. }
  1643. $file->name = end($fileParts);
  1644. $file->path = end($fileParts);
  1645. //$file->owner = $fileParts[2];
  1646. //$file->group = $fileParts[3];
  1647. //$file->perms = $fileParts[0];
  1648. $file->isDir = (substr($line, 0, 1) == 'd');
  1649. $file->permsExt = array();
  1650. $filesWithPermsTree[$file->name] = $file;
  1651. $lastName = $file->name;
  1652. }
  1653. else if (substr($line, 0, 1) == ' ') {// extended perm line
  1654. if ($lastName == '..') {
  1655. continue;
  1656. }
  1657. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  1658. }
  1659. else {// parse error
  1660. $lastName = '..';
  1661. }
  1662. }
  1663. foreach ($filesWithPermsTree as $vFile) {
  1664. $vFile->path = ltrim($vFile->path, './');
  1665. $vFile->path = explode('/', $vFile->path);
  1666. $vFile->recordFolder = array_shift($vFile->path);// $vFile->projectFolder -> recordFolder
  1667. $vFile->path = implode('/', $vFile->path);
  1668. // TODO: _getTableIdFromFolderName($task->TBL_NAME, $vFile->recordFolder);
  1669. $tblId = 0;
  1670. if ($hasRecordOwnFolder) {
  1671. $tblId = explode('.', $vFile->recordFolder);
  1672. $tblId = reset($tblId);
  1673. }
  1674. else {
  1675. $tblId = explode('.', $vFile->path);
  1676. $tblId = reset($tblId);
  1677. }
  1678. if (is_numeric($tblId) && $tblId > 0) {
  1679. $foundTblFiles[$tblId][] = $vFile;
  1680. }
  1681. }
  1682. }
  1683. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">filesWithPerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$TBL_mount_point}\n";print_r($filesWithPerms);echo'</pre>';}
  1684. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">foundTblFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): '."path: {$TBL_mount_point}\n";print_r($foundTblFiles);echo'</pre>';}
  1685. if (!empty($foundTblFiles)) {
  1686. $rowsIds = array_keys($foundTblFiles);
  1687. $sql = "select t.`ID`
  1688. , t.`L_APPOITMENT_USER`
  1689. , t.`A_ADM_COMPANY`
  1690. , t.`A_CLASSIFIED`
  1691. -- , pt.`L_APPOITMENT_USER` as PARENT_L_APPOITMENT_USER
  1692. from `{$task->TBL_NAME}` as t
  1693. -- left join `{$task->TBL_NAME}` as pt on (pt.ID=t.P_ID)
  1694. where t.`ID` in (" . implode(',', $rowsIds) . ")
  1695. ";
  1696. $res = $this->_db->query($sql);
  1697. while ($r = $this->_db->fetch($res)) {
  1698. $requirePermsExt = $this->_getRequiredPermsExtByRecord($r);
  1699. foreach ($foundTblFiles[$r->ID] as $vFile) {
  1700. $cmdList = $this->_fixFilePerms($vFile, $requirePermsExt, "{$TBL_mount_point}/{$vFile->recordFolder}", $r);
  1701. if (!empty($cmdList)) {
  1702. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  1703. foreach ($cmdList as $vCmd) {
  1704. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$r->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
  1705. exec($vCmd, $out, $outValue);
  1706. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$r->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
  1707. if ($outValue != 0) {
  1708. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  1709. }
  1710. }
  1711. } else {
  1712. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$cmdList is empty P('.$r->ID.') total('.count($cmdList).') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r("empty");echo'</pre>';}
  1713. }
  1714. }
  1715. }
  1716. }
  1717. }
  1718. private function _getRequiredPermsExtByRecord($record) {
  1719. // TODO: need to check if user is correct in field L_APPOITMENT_USER
  1720. $requirePermsExt = array();
  1721. if (!$record->L_APPOITMENT_USER && !$record->A_ADM_COMPANY) {// no owner, no write group
  1722. // TODO: group PODMIOT
  1723. $requirePermsExt["group:workgroup"] = array('write', 'read');
  1724. }
  1725. else {
  1726. if ($record->L_APPOITMENT_USER) {
  1727. if ($this->_isActiveUser($record->L_APPOITMENT_USER)) {
  1728. $requirePermsExt["user:{$record->L_APPOITMENT_USER}"] = array('write', 'read');
  1729. } else {
  1730. // TODO: trigger error $record->L_APPOITMENT_USER is not active user!
  1731. }
  1732. }
  1733. if (!empty($record->A_ADM_COMPANY) && $record->A_ADM_COMPANY == $record->A_CLASSIFIED) {
  1734. $requirePermsExt["group:{$record->A_ADM_COMPANY}"] = array('read', 'write');
  1735. }
  1736. else if (empty($record->A_ADM_COMPANY) && empty($record->A_CLASSIFIED)) {
  1737. $requirePermsExt["group:workgroup"] = array('write', 'read');
  1738. }
  1739. else {
  1740. if ($record->A_ADM_COMPANY) {
  1741. $requirePermsExt["group:{$record->A_ADM_COMPANY}"] = array('write');
  1742. }
  1743. if ($record->A_CLASSIFIED) {
  1744. $requirePermsExt["group:{$record->A_CLASSIFIED}"] = array('read');
  1745. }
  1746. }
  1747. }
  1748. // add parent owner
  1749. if (!empty($record->PARENT_L_APPOITMENT_USER) && $record->PARENT_L_APPOITMENT_USER != $record->L_APPOITMENT_USER) {
  1750. if ($this->_isActiveUser($record->PARENT_L_APPOITMENT_USER)) {
  1751. $requirePermsExt["user:{$record->PARENT_L_APPOITMENT_USER}"] = array('write', 'read');
  1752. } else {
  1753. // TODO: trigger error $record->PARENT_L_APPOITMENT_USER is not active user!
  1754. }
  1755. }
  1756. // add user:_www perms read, write
  1757. $requirePermsExt["user:_www"] = array('write', 'read');
  1758. return $requirePermsExt;
  1759. }
  1760. private function _fixFilePerms($vFile, $requirePermsExt, $mainPath, $r) {
  1761. //trigger_error("fixFilePerms: " . json_encode($vFile), E_USER_NOTICE);
  1762. $cmdList = array();
  1763. $vReqPermsExt = array();
  1764. foreach ($requirePermsExt as $kPermObj => $vPerms) {
  1765. $vReqPermsExt[$kPermObj] = array();
  1766. foreach ($vPerms as $vPerm) {
  1767. if ($vFile->isDir) {
  1768. if ($vPerm == 'read') {
  1769. $vReqPermsExt[$kPermObj]['list'] = 0;
  1770. $vReqPermsExt[$kPermObj]['search'] = 0;
  1771. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1772. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1773. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1774. $vReqPermsExt[$kPermObj]['file_inherit'] = 0;
  1775. $vReqPermsExt[$kPermObj]['directory_inherit'] = 0;
  1776. }
  1777. else if ($vPerm == 'write') {
  1778. $vReqPermsExt[$kPermObj]['add_file'] = 0;
  1779. $vReqPermsExt[$kPermObj]['add_subdirectory'] = 0;
  1780. $vReqPermsExt[$kPermObj]['delete_child'] = 0;
  1781. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1782. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1783. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1784. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1785. }
  1786. }
  1787. else {
  1788. if ($vPerm == 'read') {
  1789. $vReqPermsExt[$kPermObj]['read'] = 0;
  1790. $vReqPermsExt[$kPermObj]['execute'] = 0;
  1791. $vReqPermsExt[$kPermObj]['readattr'] = 0;
  1792. $vReqPermsExt[$kPermObj]['readextattr'] = 0;
  1793. $vReqPermsExt[$kPermObj]['readsecurity'] = 0;
  1794. }
  1795. else if ($vPerm == 'write') {
  1796. $vReqPermsExt[$kPermObj]['write'] = 0;
  1797. $vReqPermsExt[$kPermObj]['append'] = 0;
  1798. $vReqPermsExt[$kPermObj]['writeattr'] = 0;
  1799. $vReqPermsExt[$kPermObj]['writeextattr'] = 0;
  1800. $vReqPermsExt[$kPermObj]['writesecurity'] = 0;
  1801. $vReqPermsExt[$kPermObj]['chown'] = 0;
  1802. }
  1803. }
  1804. }
  1805. }
  1806. $permsToRemove = array();
  1807. foreach ($vFile->permsExt as $vPermExtLine) {
  1808. $vPermExtArr = explode(' ', $vPermExtLine);
  1809. $vPermExt = new stdClass();
  1810. $vPermExt->nr = trim($vPermExtArr[0], ' :');
  1811. $vPermExt->permObj = $vPermExtArr[1];
  1812. $vPermExt->perms = '';
  1813. if (count($vPermExtArr) == 4) {
  1814. $vPermExt->perms = explode(',', $vPermExtArr[3]);
  1815. }
  1816. else if (count($vPermExtArr) == 5 && $vPermExtArr[2] == 'inherited') {
  1817. $vPermExt->perms = explode(',', $vPermExtArr[4]);
  1818. }
  1819. else {
  1820. echo "Error: Perm Ext Line format! ({$vPermExtLine})";
  1821. continue;
  1822. }
  1823. $permFound = false;
  1824. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1825. if (false !== strpos($vPermExtLine, $kPermObj)) {
  1826. foreach ($vPerms as $kPerm => $vPermChecked) {
  1827. if (in_array($kPerm, $vPermExt->perms)) {
  1828. $vReqPermsExt[$kPermObj][$kPerm] = 1;
  1829. $permFound = true;
  1830. }
  1831. }
  1832. }
  1833. }
  1834. if (!$permFound) {
  1835. $permsToRemove[] = $vPermExt->nr;
  1836. }
  1837. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$vReqPermsExt('.$vFile->name.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vReqPermsExt);echo'</pre>';
  1838. }
  1839. if (!empty($permsToRemove)) {
  1840. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-rm('.$r->ID.'): $permsToRemove('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToRemove'=>$permsToRemove, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
  1841. $permsToRemove = array_reverse($permsToRemove);
  1842. foreach ($permsToRemove as $vPermInd) {
  1843. $cmdList []= "chmod -a# {$vPermInd} '{$mainPath}/{$vFile->path}' ";
  1844. }
  1845. }
  1846. $permsToAdd = array();
  1847. foreach ($vReqPermsExt as $kPermObj => $vPerms) {
  1848. foreach ($vPerms as $kPerm => $vPermChecked) {
  1849. if (!$vPermChecked) {
  1850. $permsToAdd[$kPermObj][$kPerm] = 1;
  1851. }
  1852. }
  1853. }
  1854. if (!empty($permsToAdd)) {
  1855. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:300px;overflow:auto;border:1px solid red;text-align:left;">TO-add('.$r->ID.'): $permsToAdd('.$vFile->name.') isDir('.$vFile->isDir.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('permsToAdd'=>$permsToAdd, 'vFile->permsExt'=>$vFile->permsExt, 'r'=>$r));echo'</pre>';}
  1856. foreach ($permsToAdd as $kPermObj => $vPerms) {
  1857. $cmdList []= "chmod +a \"{$kPermObj} allow " . implode(',', array_keys($vPerms)) . "\" '{$mainPath}/{$vFile->path}' ";
  1858. }
  1859. }
  1860. return $cmdList;
  1861. }
  1862. private function _isActiveUser($usrLogin) {
  1863. $activeLoginList = $this->_fetchActiveLoginList();
  1864. return in_array($usrLogin, $activeLoginList);
  1865. }
  1866. public function _fetchActiveLoginList() {
  1867. if (!$this->_db) die('DB Error!');
  1868. if (!is_array($this->_activeLoginList)) {
  1869. $this->_activeLoginList = array();
  1870. $sql = "select u.`ADM_ACCOUNT`
  1871. from `ADMIN_USERS` as u
  1872. where u.`A_STATUS` = 'NORMAL'
  1873. ";
  1874. $res = $this->_db->query($sql);
  1875. while ($r = $this->_db->fetch($res)) {
  1876. $this->_activeLoginList[] = $r->ADM_ACCOUNT;
  1877. }
  1878. }
  1879. return $this->_activeLoginList;
  1880. }
  1881. private function _saveTask($tblName, $tblId, $taskDone = 1, $result = null) {
  1882. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1883. $sqlResult = '';
  1884. if ($result) {
  1885. $resultJson = json_encode($result);
  1886. $resultJson = $this->_db->_($resultJson);
  1887. $sqlResult .= " , s.`A_SYNC_RESULT`='{$resultJson}' ";
  1888. }
  1889. $sql = "update `{$this->_syncTblName}` as s
  1890. set
  1891. s.`A_LAST_SYNC`=NOW()
  1892. , s.`A_SYNCHRONIZED`={$taskDone}
  1893. {$sqlResult}
  1894. where s.`TBL_ID`={$tblId} and s.`TBL_NAME`='{$tblName}'
  1895. ";
  1896. $res = $this->_db->query($sql);
  1897. }
  1898. public function executeTask($tblName, $tblId) {
  1899. if (!$this->_tbls) return;
  1900. $task = $this->_getTask($tblName, $tblId);
  1901. if (!$task) return;
  1902. $this->_executeTask($task);
  1903. $this->_saveTask($task->TBL_NAME, $task->TBL_ID);
  1904. return $task;
  1905. }
  1906. public function nextTaskAction($tblName) {
  1907. if (!$this->_tbls) return;
  1908. $task = $this->_getTask($tblName);
  1909. if (!$task) return;
  1910. $this->_executeTask($task);
  1911. /*
  1912. if (isset($task->A_SYNC_RESULT->total)
  1913. && isset($task->A_SYNC_RESULT->lastDone)
  1914. && $task->A_SYNC_RESULT->lastDone < $task->A_SYNC_RESULT->total
  1915. ) {
  1916. $this->_saveTask($task->TBL_NAME, $task->TBL_ID, 0, $task->A_SYNC_RESULT);
  1917. } else {
  1918. $this->_saveTask($task->TBL_NAME, $task->TBL_ID);
  1919. }
  1920. */
  1921. $this->_saveTask($task->TBL_NAME, $task->TBL_ID);
  1922. return $task;
  1923. }
  1924. private function _getTask($tblName, $tblId = null) {
  1925. if (!$this->_db) die("DB Error: No DB! L." . __LINE__);
  1926. $task = null;
  1927. $recordFieldList = $this->_getRecordFieldList($tblName);
  1928. $recordFieldList[] = 'L_APPOITMENT_USER';
  1929. $recordFieldList[] = 'A_ADM_COMPANY';
  1930. $recordFieldList[] = 'A_CLASSIFIED';
  1931. $sqlRecordFields = array();
  1932. foreach ($recordFieldList as $fldName) {
  1933. $sqlRecordFields[] = "t.`{$fldName}` as t__{$fldName}";
  1934. }
  1935. $sqlRecordFields = implode(',', $sqlRecordFields);
  1936. $sqlTblId = "and s.`TBL_ID`!=-1";
  1937. if ($tblId > 0) $sqlTblId = "and s.`TBL_ID`='{$tblId}'";
  1938. $sql = "select s.*
  1939. , {$sqlRecordFields}
  1940. -- , pt.`L_APPOITMENT_USER` as p__PARENT_L_APPOITMENT_USER
  1941. from `{$this->_syncTblName}` as s
  1942. left join `{$tblName}` as t on(t.`ID`=s.`TBL_ID`)
  1943. -- left join `{$tblName}` as pt on(pt.`ID`=t.`P_ID`)
  1944. where
  1945. s.`TBL_NAME`='{$tblName}'
  1946. {$sqlTblId}
  1947. and s.`A_SYNCHRONIZED`=0
  1948. and s.`A_POMIN_SYNC`=0
  1949. order by s.`A_LAST_SYNC` asc, s.`ID` asc
  1950. limit 1
  1951. ";
  1952. $res = $this->_db->query($sql);
  1953. if ($r = $this->_db->fetch($res)) {
  1954. $r->A_SYNC_RESULT = (!$r->A_SYNC_RESULT)? new stdClass() : json_decode($r->A_SYNC_RESULT);
  1955. $task = $r;
  1956. $task->record = new stdClass();
  1957. foreach ($recordFieldList as $fldName) {
  1958. $aliasFldName = "t__{$fldName}";
  1959. $task->record->{$fldName} = $task->{$aliasFldName};
  1960. unset($task->{$aliasFldName});
  1961. }
  1962. }
  1963. return $task;
  1964. }
  1965. private function _getRecordFieldList($tblName) {
  1966. if (empty($this->_tbls[$tblName])) return;
  1967. $conf = $this->_tbls[$tblName];
  1968. $fldNames = array();
  1969. $fldName = V::get("LOOKAT_FOLDER_VARNAME", '', $conf);
  1970. $fldName = trim($fldName);
  1971. if (!empty($fldName)) $fldNames[$fldName] = true;
  1972. for ($i = 1; $i < 5; $i++) {
  1973. $fldName = V::get("LOOKAT_FOLDER_VARNAME{$i}", '', $conf);
  1974. $fldName = trim($fldName);
  1975. if (!empty($fldName)) $fldNames[$fldName] = true;
  1976. $fldName = V::get("DEST_FOLDER_VARNAME{$i}", '', $conf);
  1977. $fldName = trim($fldName);
  1978. if (!empty($fldName)) $fldNames[$fldName] = true;
  1979. }
  1980. if (!in_array('ID', $fldNames)) {
  1981. $fldNames['ID'] = true;
  1982. }
  1983. return array_keys($fldNames);
  1984. }
  1985. private function _executeTask($task) {
  1986. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">executeTask (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($task);echo'</pre>';}
  1987. $DBG_TIME = false;
  1988. $dbgTime = new stdClass();
  1989. $dbgTime->startTime = microtime(true);
  1990. $dbgTime->lastTime = $dbgTime->startTime;
  1991. $confTblName = "{$task->TBL_NAME}_COLUMN";
  1992. $TBL_mount_point = FoldersConfig::get($confTblName, 'mount_point');
  1993. $record = $task->record;
  1994. $folderConf = FoldersConfig::getAll($confTblName);
  1995. $uploader = new FileUploader($confTblName, $record);
  1996. $errMsg = '';
  1997. if (!$uploader->setConfig($folderConf, $errMsg)) {
  1998. trigger_error("Error: folders config!", E_USER_NOTICE);
  1999. die("Error: folders config!");
  2000. }
  2001. if ($DBG_TIME) {
  2002. $dbgTime->curTime = microtime(true);
  2003. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]: after-FileUploader->setConfig" . "\n";
  2004. $dbgTime->lastTime = $dbgTime->curTime;
  2005. }
  2006. $uploader->findFolder();
  2007. $mainFolder = $uploader->getDestFolder();
  2008. if ($DBG_TIME) {
  2009. $dbgTime->curTime = microtime(true);
  2010. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]:time after-FileUploader->getDestFolder" . "\n";
  2011. $dbgTime->lastTime = $dbgTime->curTime;
  2012. }
  2013. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$record->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';var_dump($uploader);echo'</pre>';}
  2014. if (!$mainFolder) {
  2015. $mainFolder = $uploader->generateFolderName();
  2016. $mainFolderPath = rtrim($TBL_mount_point, '/') . '/' . $mainFolder;
  2017. if(V::get('DBG', '', $_GET, 'int') > 2){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">generated folderName('.$record->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($mainFolder, $mainFolderPath));echo'</pre>';}
  2018. @mkdir($mainFolderPath, 0770, true);
  2019. @chmod($mainFolderPath, 0770);
  2020. if (!file_exists($mainFolderPath)) {
  2021. trigger_error("Error: Nie udało się utworzyć folderu! ({$mainFolder})", E_USER_NOTICE);
  2022. return false;
  2023. }
  2024. $requirePermsExt = $this->_getRequiredPermsExtByRecord($record);
  2025. $file = new stdClass();
  2026. $file->name = '.';
  2027. $file->path = '.';
  2028. //$file->owner = '';
  2029. //$file->group = '';
  2030. //$file->perms = '';
  2031. $file->isDir = true;
  2032. $file->permsExt = array();
  2033. $cmdList = $this->_fixFilePerms($file, $requirePermsExt, "{$TBL_mount_point}/{$mainFolder}", $record);
  2034. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">cmdList-P('.$record->ID.') fixFilePerms (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($cmdList);echo'</pre>';}
  2035. }
  2036. else {
  2037. $cmdList = $this->_fixRecord($record, $uploader, $mainFolder, $TBL_mount_point, $task);
  2038. }
  2039. if ($DBG_TIME) {
  2040. $dbgTime->curTime = microtime(true);
  2041. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]: after-generate cmdList - mainFolder(" . (($mainFolder)? 1 : 0) . ")" . "\n";
  2042. $dbgTime->lastTime = $dbgTime->curTime;
  2043. }
  2044. if (!empty($cmdList)) {
  2045. foreach ($cmdList as $vCmd) {
  2046. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Exec-cmdList-P('.$record->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCmd);echo'</pre>';}
  2047. exec($vCmd, $out, $outValue);
  2048. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Done-cmdList-P('.$record->ID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array($outValue, $out));echo'</pre>';}
  2049. if ($outValue != 0) {
  2050. trigger_error("Error-cmd: {$vCmd}", E_USER_NOTICE);
  2051. }
  2052. }
  2053. }
  2054. if ($DBG_TIME) {
  2055. $dbgTime->curTime = microtime(true);
  2056. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):" . __LINE__ . ":_executeTask({$task->TBL_NAME}/{$task->TBL_ID}]: after-executed cmdList " . "\n";
  2057. $dbgTime->lastTime = $dbgTime->curTime;
  2058. }
  2059. if(V::get('DBG', '', $_GET, 'int') > 0){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">';print_r("executeTask finished OK");echo'</pre>';}
  2060. }
  2061. public function _fixRecord($r, $uploader, $mainFolder, $TBL_mount_point, &$task) {
  2062. $requirePermsExt = $this->_getRequiredPermsExtByRecord($r);
  2063. $DBG_TIME = false;
  2064. $dbgTime = new stdClass();
  2065. $dbgTime->startTime = microtime(true);
  2066. $dbgTime->lastTime = $dbgTime->startTime;
  2067. $filesWithPerms = array();
  2068. if ($uploader->hasRecordOwnFolder()) {
  2069. $cmd = " ls -Rlea . ";
  2070. $cmd = "cd '{$TBL_mount_point}/{$mainFolder}' && {$cmd} ";
  2071. exec($cmd, $filesWithPerms);
  2072. }
  2073. else {
  2074. $lookGlob = $uploader->getFileSearchRegex();
  2075. $cmd = " ls -Rlea {$lookGlob} ";
  2076. $cmd = "cd '{$TBL_mount_point}/{$mainFolder}' && {$cmd} ";
  2077. exec($cmd, $filesWithPerms);
  2078. }
  2079. //echo "\n-----------------------\n";
  2080. //echo "filesWithPerms: ";print_r($filesWithPerms);echo "\n";
  2081. if ($DBG_TIME) {
  2082. $dbgTime->curTime = microtime(true);
  2083. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):_fixRecord: cd '{$TBL_mount_point}/{$mainFolder}' && {$cmd} " . "\n";
  2084. $dbgTime->lastTime = $dbgTime->curTime;
  2085. }
  2086. $filesWithPermsTree = array();
  2087. $lastName = '';
  2088. $folderParent = '';
  2089. foreach ($filesWithPerms as $line) {
  2090. if (substr($line, 0, 1) == '-' || substr($line, 0, 1) == 'd') {// file name
  2091. $fileParts = array();
  2092. $filePartsArr = explode(' ', $line);
  2093. $lastInd = 0;
  2094. foreach ($filePartsArr as $vPart) {
  2095. if ($lastInd > 7) {// file name
  2096. $fileParts[8] = ($lastInd > 8)? "{$fileParts[8]} {$vPart}" : $vPart;
  2097. $lastInd++;
  2098. }
  2099. else if (!empty($vPart) || $vPart === '0') {
  2100. $fileParts[] = $vPart;
  2101. $lastInd++;
  2102. }
  2103. }
  2104. if (end($fileParts) == '..' || (end($fileParts) == '.' && $folderParent)) {
  2105. $lastName = '..';
  2106. continue;
  2107. }
  2108. $file = new stdClass();
  2109. if (!isset($fileParts[8])) {
  2110. echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Error parse file name (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r(array('line'=>$line, 'fileParts'=>$fileParts));echo'</pre>';
  2111. //continue;
  2112. }
  2113. $file->name = end($fileParts);
  2114. $file->path = array();
  2115. if ($folderParent) $file->path[] = $folderParent;
  2116. $file->path[] = end($fileParts);
  2117. $file->path = implode('/', $file->path);
  2118. //$file->owner = $fileParts[2];
  2119. //$file->group = $fileParts[3];
  2120. //$file->perms = $fileParts[0];
  2121. $file->isDir = (substr($line, 0, 1) == 'd');
  2122. $file->permsExt = array();
  2123. $filesWithPermsTree[$file->name] = $file;
  2124. $lastName = $file;
  2125. }
  2126. else if (substr($line, 0, 1) == ' ') {// extended perm line
  2127. if ($lastName == '..') {
  2128. continue;
  2129. }
  2130. $filesWithPermsTree[$file->name]->permsExt[] = trim($line);
  2131. }
  2132. else if (substr($line, 0, 2) == './' && substr($line, -1) == ':') {// folder
  2133. $folderParent = substr($line, 2, -1);
  2134. }
  2135. else if (substr($line, 0, 5) == 'total') {
  2136. continue;
  2137. }
  2138. else if (empty($line)) {
  2139. $folderParent = '';
  2140. continue;
  2141. }
  2142. }
  2143. //echo "filesWithPermsTree: ";print_r($filesWithPermsTree);echo "\n";
  2144. if ($DBG_TIME) {
  2145. $dbgTime->curTime = microtime(true);
  2146. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):_fixRecord: parse cmd output" . "\n";
  2147. $dbgTime->lastTime = $dbgTime->curTime;
  2148. }
  2149. if(V::get('DBG', '', $_GET, 'int') > 1){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$filesWithPermsTree (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($filesWithPermsTree);echo'</pre>';}
  2150. // check perms
  2151. /*
  2152. files:
  2153. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown
  2154. W read,write,execute,append,readattr,writeattr,readextattr,writeextattr,readsecurity
  2155. R read, execute, readattr, readextattr, readsecurity
  2156. dir:
  2157. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown,file_inherit,directory_inherit
  2158. W list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity, file_inherit,directory_inherit
  2159. R list, search, readattr, readextattr, readsecurity, file_inherit,directory_inherit
  2160. */
  2161. $cmdList = array();
  2162. foreach ($filesWithPermsTree as $kFileName => $vFile) {
  2163. if (false) {
  2164. // TODO: $kFileName == '_PISMA' - readonly
  2165. // TODO: $vFile->path => _PISMA/...
  2166. }
  2167. else {
  2168. $cmdFile = $this->_fixFilePerms($vFile, $requirePermsExt, "{$TBL_mount_point}/{$mainFolder}", $r);
  2169. if (!empty($cmdFile)) {
  2170. foreach ($cmdFile as $vCmd) {
  2171. $cmdList[] = $vCmd;
  2172. }
  2173. }
  2174. }
  2175. }
  2176. //echo "cmdList: ";print_r($cmdList);echo "\n";
  2177. //echo "\n-----------------------\n";
  2178. if ($DBG_TIME) {
  2179. $dbgTime->curTime = microtime(true);
  2180. echo "DBG:(" . number_format($dbgTime->curTime - $dbgTime->lastTime, 6) . "s):_fixRecord: end" . "\n";
  2181. $dbgTime->lastTime = $dbgTime->curTime;
  2182. }
  2183. return $cmdList;
  2184. }
  2185. }
  2186. ?>